WordPress自动功能图像代码不工作

sulc1iza  于 2023-01-29  发布在  WordPress
关注(0)|答案(1)|浏览(99)

我试图有第一个img从岗位是精选的img自动这是我添加在我的functions.php在主题编辑器

// Auto add featured image
function wpsites_auto_set_featured_image() {
   global $post;
   $featured_image_exists = has_post_thumbnail($post->ID);
      if (!$featured_image_exists)  {
         $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);}
         }
      }
}
add_action('the_post', 'wpsites_auto_set_featured_image');

有什么我需要添加或更改我是真正的新php

db2dz4w8

db2dz4w81#

试试这个:

function wpsites_auto_set_featured_image() {
    global $post;
    if (!has_post_thumbnail($post->ID)) {
        $attached_image = get_children(array(
            '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);
                break;
            }
        }
    }
}
add_action('save_post', 'wpsites_auto_set_featured_image');

相关问题