我有一个自定义的帖子类型\'Commercials\' 和自定义post状态\'Featured\'. 现在我只想要一篇特色文章。我的意思是,现在我可以让所有帖子都成为特色,但我只想让其中一篇成为特色。如果已经有一篇特色文章,并且我选择了一篇新的作为特色文章,那么旧的文章将返回发布。
我已经试了几个小时想找到一个解决方案。这是我正在使用的代码。
// Register Custom Post Status
function register_custom_post_status_featured(){
register_post_status( \'Featured\', array(
\'label\' => _x( \'Featured\', \'commercials\' ),
\'public\' => true,
\'internal\' => true,
\'protected\' => true,
\'private\' => false,
\'publicly_queryable\' => true,
\'exclude_from_search\' => false,
\'show_in_admin_all_list\' => true,
\'show_in_admin_status_list\' => true,
\'label_count\' => _n_noop( \'Featured <span class="count">(%s)</span>\', \'Featured <span class="count">(%s)</span>\' ),
) );
}
add_action( \'init\', \'register_custom_post_status_featured\' );
// Display Custom Post Status Option in Post Edit
function display_custom_post_status_featured_option(){
global $post;
$complete = \'\';
$label = \'\';
if($post->post_type == \'commercials\'){
if($post->post_status == \'featured\'){
$selected = \'selected\';
}
echo \'<script>
$(document).ready(function(){
$("select#post_status").append("<option value=\\"featured\\" \'.$selected.\'>Featured</option>");
$(".misc-pub-section label").append("<span id=\\"post-status-display\\"> Featured</span>");
var currentPostStatus = $("select#post_status").find(":selected").text();
$("#post-status-display").html(currentPostStatus);
$( "select[name=\\"_status\\"]" ).append( "<option value=\\"featured\\">Featured</option>" );
});
</script>
\';
}
}
add_action(\'admin_footer\', \'display_custom_post_status_featured_option\');
// display label
function rudr_display_featured_status_label( $status ) {
global $post;
$complete = \'\';
$label = \'\';
if($post->post_type == \'commercials\'){
if($post->post_status == \'featured\'){
return array(\'Featured\');
}
}
return $status;
}
add_filter( \'display_post_states\', \'rudr_display_featured_status_label\' );
任何帮助都将不胜感激。
最合适的回答,由SO网友:nmr 整理而成
您可以为此使用状态转换筛选器挂钩之一:
在分配给挂钩的功能中,将状态更改为
publish
之前的特色帖子(使用例如。
$wpdb
). 这两个操作都是在保存帖子后执行的,因此您必须更改帖子中的状态,而不是编辑状态。
add_action( \'featured_commercials\', \'se339582_single_featured\', 10, 2 );
function se339582_single_featured( $post_id, $post )
{
global $wpdb;
$sql = $wpdb->prepare( "UPDATE {$wpdb->posts} SET post_status=\'publish\' "
." WHERE post_status=\'featured\' AND id <> %d", $post_id );
$wpdb->query( $sql );
}
更新:每个类别一篇特色文章的SQL:
$taxonomy_slug = \'commercials\';
$sql = $wpdb->prepare( "UPDATE {$wpdb->posts} p " .
" INNER JOIN {$wpdb->term_relationships} tr ON tr.object_id = p.id " .
" INNER JOIN {$wpdb->term_taxonomy} tt ON tt.term_taxonomy_id = tr.term_taxonomy_id " .
" SET p.post_status=\'publish\' " .
" WHERE p.id <> %d AND p.post_status=\'featured\' AND tt.taxonomy=%s AND tt.term_id = %d",
$post_id, $taxonomy_slug, $term_id
);