首页 > 解决方案 > 创建帖子时如何自动将特色图片添加到自定义帖子?

问题描述

我有一个名为“项目”的自定义帖子。
当用户登录时,会自动创建帖子。
创建帖子后,我需要为所有帖子自动添加特色图片(仅一张图片:编号 6120)。
我尝试了以下代码,但它没有添加特色图片。
我是初学者,所以我不擅长编码,请您告诉我如何解决这个问题?

function wpsites_auto_set_featured_image() {
global $post, $post_type;
if( $post_type == "project" ) {
$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, '6120');
wp_reset_query();                                
   }
  }
 }
}
}
add_action('save_post', 'wpsites_auto_set_featured_image');

谢谢你。

标签: phpwordpressimage

解决方案


对特定的帖子类型使用save_post_{$post->post_type}。检查下面的代码。

function wpsites_auto_set_featured_image( $post_id ) {
    if ( !has_post_thumbnail( $post_id ) )  {
        $thumbnail_id = 6120;
        update_post_meta( $post_id, '_thumbnail_id', $thumbnail_id );
    }
}
add_action( 'save_post_project', 'wpsites_auto_set_featured_image', 10 );

推荐阅读