我有一个自定义的帖子类型,叫做“新来者”。我正在尝试整合一个功能,当CPT帖子更新或发布时,该功能将删除自定义帖子类型的所有图片附件(除了特色图片)。但这似乎不起作用,我做错了什么?
function delete_extra_images() {
if ( $post->post_type == \'newcomer\' && $post->post_status == \'publish\' ) {
$attachments = get_posts( array(
\'post_type\' => \'attachment\',
\'posts_per_page\' => -1,
\'post_parent\' => $post->ID,
\'exclude\' => get_post_thumbnail_id()
));
if ( $attachments ) {
foreach ( $attachments as $attachment ) {
wp_delete_attachment( $attachment->ID, false );
}
}
}
}
add_action( \'publish_newcomer\', \'delete_extra_images\' );
最合适的回答,由SO网友:Adam 整理而成
试试这个尺码:
add_action(\'save_post\', function($post_id, $post, $update){
if ( $post->post_type === \'newcomer\' && $post->post_status === \'publish\' ) {
$attachments = get_attached_media( \'image\', $post->ID );
$featured_id = get_post_thumbnail_id();
//unset the featured image by ID if it exists
unset($attachments[$featured_id]);
foreach ( $attachments as $attachment ) {
wp_delete_attachment( $attachment->ID, false );
}
}
}, 10, 3);
注意:您可以放弃包装
foreach
条件检查中的语句
$attachments
变量as
get_attached_media()
在内部将其结果强制转换为数组。当然,如果您希望在核心内部更改事件中保持谨慎,那么您可以自己进行转换或添加回您的条件检查。
有用参考:http://codex.wordpress.org/Function_Reference/get_attached_media