第一步是遍历所有帖子:
$wpse87964query = new WP_Query();
现在,这将获得所有帖子;但我们只对没有特色图片集的帖子感兴趣。WordPress通过post自定义元字段存储特色图像:
_thumbnail_id
; 所以
we can use that in a meta query, 要仅获取没有设置特色图像的帖子,请执行以下操作:
$wpse87964query_args = array(
\'nopaging\' => true,
meta_query( array(
array(
\'key\' => \'_thumbnail_id\',
\'compare\' => \'NOT EXISTS\'
)
) )
)
$wpse87964query = new WP_Query( wpse87964query_args );
现在,设置循环:
if ( $wpse87964query->have_posts() ) : while ( $wpse87964query->have_posts() ) : $wpse87964query->the_post();
// CODE WILL GO HERE
endwhile; endif;
wp_reset_postdata();
现在,查询附件:
$attachments = get_children( \'post_parent=\' . get_the_ID() . \'&post_type=attachment&post_mime_type=image&order=desc\' );
if( $attachments ) {
$keys = array_reverse( $attachments );
set_post_thumbnail( get_the_ID(), $keys[0]->ID );
};
现在,将整个内容封装在一个函数中,这样您就可以在某个地方调用它,或者将它挂接到某个对象中:
function wpse87964_set_post_thumbnails() {
// Query args
$wpse87964query_args = array(
\'nopaging\' => true,
meta_query( array(
array(
\'key\' => \'_thumbnail_id\',
\'compare\' => \'NOT EXISTS\'
)
) )
)
// Run query
$wpse87964query = new WP_Query( wpse87964query_args );
// Open query loop
if ( $wpse87964query->have_posts() ) : while ( $wpse87964query->have_posts() ) : $wpse87964query->the_post();
// Query post attachments
$attachments = get_children( \'post_parent=\' . get_the_ID() . \'&post_type=attachment&post_mime_type=image&order=desc\' );
if( $attachments ) {
$keys = array_reverse( $attachments );
set_post_thumbnail( get_the_ID(), $keys[0]->ID );
};
// Close query loop
endwhile; endif;
wp_reset_postdata();
}
您可以改进此功能,方法是分批遍历帖子,或者定义自己的帖子自定义元进行查询,以便只处理每个帖子一次,等等。