我不确定您当前的“隐藏”复选框代码是如何工作的(有一个未定义的$archive
变量in_category
在上下文中可能不正确,我怀疑你的帖子类型实际上是your_post_type
).
为了确保一切正常,这里提供了一个完整的解决方案,用于在编辑帖子屏幕中添加复选框,您可以在其中正确切换其“隐藏”状态:
/**
* Register our meta box that will show the "hide this post" checkbox.
*/
function wpse_188443_add_hidden_meta_box( $post_type ) {
$hidden_types = array(
\'post\',
// Add any other post types you need to hide
);
if ( in_array( $post_type, $hidden_types ) ) {
add_meta_box(
\'wpse_188443_hidden\',
\'Hide Post From Archives\',
\'wpse_188443_hidden_meta_box\',
$post_type,
\'side\' /* Either "advanced", "normal" or "side" */
);
}
}
add_action( \'add_meta_boxes\', \'wpse_188443_add_hidden_meta_box\' );
/**
* Display our meta box.
*/
function wpse_188443_hidden_meta_box( $post ) {
$is_hidden = !! get_post_meta( $post->ID, \'_hidden\', true );
?>
<label>
<input type="checkbox" name="wpse_188443_hidden" <?php checked( $is_hidden ) ?> />
Hide this post from archives
</label>
<!-- A hidden input so that we only update our checkbox state when this field exists in $_POST -->
<input type="hidden" name="wpse_188443_hidden_save" value="1" />
<?php
}
/**
* Save our checkbox state.
*/
function wpse_188443_hidden_save( $post_id ) {
if ( isset( $_POST[\'wpse_188443_hidden_save\'] ) ) {
if ( isset( $_POST[\'wpse_188443_hidden\'] ) )
update_post_meta( $post_id, \'_hidden\', \'1\' );
else
delete_post_meta( $post_id, \'_hidden\' );
}
}
add_action( \'wp_insert_post\', \'wpse_188443_hidden_save\' );
阅读更多信息
this answer 有关上述技术的说明。
现在要真正隐藏“隐藏”帖子,应该简单到:
function wpse_188443_hidden_posts( $wp_query ) {
if ( ! is_admin() && $wp_query->is_main_query() && ! $wp_query->is_singular() ) {
if ( ! $meta_query = $wp_query->get( \'meta_query\' ) )
$meta_query = array();
$meta_query[] = array(
\'key\' => \'_hidden\',
\'value\' => \'\',
\'compare\' => \'NOT EXISTS\',
);
$wp_query->set( \'meta_query\', $meta_query );
}
}
add_action( \'pre_get_posts\', \'wpse_188443_hidden_posts\' );