wordpress自动设置第一张图为特色图片代码
Warning: Undefined variable $output in /home/wwwroot/xiaoyuo.com/wp-content/themes/ripro-child/functions.php on line 68
本文共1676个字,预计阅读时间需要5分钟 发布时间: 2024-10-4 共3.12K人阅读
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吧。
以上代码可能会影响你手动设置的特色图。
下载仅供下载体验和测试学习,不得商用和正当使用。
常见问题FAQ
Warning: foreach() argument must be of type array|object, string given in /home/wwwroot/xiaoyuo.com/wp-content/themes/ripro-child/parts/author-box.php on line 12