【问题标题】:WordPress auto feature image code not workingWordPress 自动功能图像代码不起作用
【发布时间】:2023-01-31 22:06:03
【问题描述】:

我正在尝试让帖子中的第一个 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 比较陌生

【问题讨论】:

    标签: wordpress wordpress-theming custom-wordpress-pages


    【解决方案1】:

    使用 transition_post_status 操作挂钩检查从草稿到发布的过渡,并在此时自动设置特色图像。更新代码:

    function wpsites_auto_set_featured_image( $new_status, $old_status, $post ) {
        if ( 'publish' !== $new_status or 'publish' === $old_status ) {
            return;
        }
        if (has_post_thumbnail($post->ID)) {
            return;
        }
        $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( 'transition_post_status', 'wpsites_auto_set_featured_image', 10, 3 );
    

    【讨论】:

    • 它有效,但只在我更新帖子后才放特色 IMG。因此,如果我自动发布它,我必须手动进入并更新它以更新特色 img。有解决办法吗?
    • 我已经更新了答案,请检查。
    猜你喜欢
    • 1970-01-01
    • 2020-08-29
    • 1970-01-01
    • 1970-01-01
    • 2011-11-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-05-13
    相关资源
    最近更新 更多