php - 创建帖子时如何自动将特色图片添加到自定义帖子?
问题描述
我有一个名为“项目”的自定义帖子。
当用户登录时,会自动创建帖子。
创建帖子后,我需要为所有帖子自动添加特色图片(仅一张图片:编号 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');
谢谢你。
解决方案
对特定的帖子类型使用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 );
推荐阅读
- android - 以编程方式更改开关的状态
- json - 快速解析 json 错误“没有与键 CodingKeys 关联的值(stringValue:\“id\”,intValue:nil)(\“id\”)。”
- ios - 如何使用一个 ContainerView 显示多个 ViewController
- product - 获取 BigCommerce 产品选项 variantId
- netbeans - 如何运行 Netbeans Vaadin 示例项目?
- coq - 如何在 CoqIDE 中拥有多个窗格?
- java - 将某些列复制到另一个表中并在同一个 SQL 语句中插入新值?
- python - python - celery - 在调度程序上修改时间
- python - SageMath:减少商环 (x^2 - x = 0)
- python - 网络编程 Python UDP recvfrom 不起作用