我想创建一个条件,检查帖子是否有缩略图,以及是否显示缩略图,否则显示帖子中的第一个图像。
我在循环中尝试了类似的东西。php,但它似乎不起作用:
<?php if (has_post_thumbnail()) { ?>
<a href="<?php the_permalink(); ?>"><?php the_post_thumbnail(array(640,320)); ?></a>
<?php } else { ?>
<a href="<?php the_permalink(); ?>"><img src="<?php echo catch_that_image(); ?>" /></a>
<?php } ?>
这是我的函数。php文件:
<?php
function catch_that_image() {
global $post, $posts;
$first_img = \'\';
ob_start();
ob_end_clean();
$output = preg_match_all(\'/<img.+src=[\\\'"]([^\\\'"]+)[\\\'"].*>/i\', $post->post_content, $matches);
$first_img = $matches [1] [0];
// no image found display default image instead
if(empty($first_img)){
$first_img = get_bloginfo(\'template_url\')."/images/no_image.gif";
}
return $first_img;
}
$imgURL = catch_that_image();
?>
SO网友:Sara
这应该可以做到,我正在使用它,它非常简单,只需将它粘贴到functions.php
:
function autoset_featured() {
global $post;
$already_has_thumb = has_post_thumbnail($post->ID);
if (!$already_has_thumb) {
$attached_image = get_children(
"post_parent=$post->ID&post_type=attachment&post_mime_type=image&numberposts=1"
);
if ($attached_image) {
foreach ($attached_image as $attachment_id => $attachment) {
set_post_thumbnail($post->ID, $attachment_id);// the size of the thumbnail is defined in a function above
}
}
}
} //end function
add_action(\'the_post\', \'autoset_featured\');
add_action(\'save_post\', \'autoset_featured\');
add_action(\'draft_to_publish\', \'autoset_featured\');
add_action(\'new_to_publish\', \'autoset_featured\');
add_action(\'pending_to_publish\', \'autoset_featured\');
add_action(\'future_to_publish\', \'autoset_featured\');