[英]How to automatically add a featured image to a custom post when the post is created?
I have a custom post called 'project'.我有一个名为“项目”的自定义帖子。
When a user logs in, post is automatically created.当用户登录时,会自动创建帖子。
When the post is created, I need to automatically add a featured image (only one image: number 6120) for all posts.创建帖子后,我需要为所有帖子自动添加特色图片(仅一张图片:编号 6120)。
I tried the following code but it doesn't add a featured image.我尝试了以下代码,但它没有添加特色图片。
I'm a beginner so I'm not good at coding, would you please let me know how to solve this problem?我是初学者,所以我不擅长编码,请您告诉我如何解决这个问题?
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');
Thank you.谢谢你。
Use save_post_{$post->post_type} for particular post type.对特定的帖子类型使用save_post_{$post->post_type} 。 check below code.检查下面的代码。
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 );
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.