wordpress自动设置第一张图为特色图片代码
wordpress自动设置第一张图为特色图片代码
将下方代码添加到当前主题的functions.php中
function wpforce_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); } } } } //end function add_action('the_post', 'wpforce_featured'); add_action('save_post', 'wpforce_featured'); add_action('draft_to_publish', 'wpforce_featured'); add_action('new_to_publish', 'wpforce_featured'); add_action('pending_to_publish', 'wpforce_featured'); add_action('future_to_publish', 'wpforce_featured');
上面的代码就会设置文章内的第一张图为特色图片。但是有时候我们文章里没有图片怎么办?
可以用下面的代码,设置某一个ID的图片为默认图片。
function wpforce_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); } } else { set_post_thumbnail($post->ID, '8888'); } } } //end function add_action('the_post', 'wpforce_featured'); add_action('save_post', 'wpforce_featured'); add_action('draft_to_publish', 'wpforce_featured'); add_action('new_to_publish', 'wpforce_featured'); add_action('pending_to_publish', 'wpforce_featured'); add_action('future_to_publish', 'wpforce_featured');
上面代码里的$post->ID, '8888’这个8888就是图片ID,自己在网站媒体库找一张图改一下ID吧。
以上代码可能会影响你手动设置的特色图。
Discussion
New Comments
暂无评论。 成为第一个!