wordpress自动设置第一张图为特色图片代码
WordPress教程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 functionadd_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 functionadd_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吧。
以上代码可能会影响你手动设置的特色图。
下载仅供下载体验和测试学习,不得商用和正当使用。
[ppwp passwords=”zhishitu.cn”]
下载体验
应版权要求,禁止分享,敬请谅解,有问题务必找客服哈。
有问题找客服哈,并领取学习福利!
[/ppwp]