I’m not sure how your current “hidden” checkbox code is working (there’s an undefined $archive
variable, in_category
might not fire correctly in the context, and I doubt your post type is actually your_post_type
).
Just to make sure we get everything working, here is a complete solution for adding a checkbox to the edit post screen, where you can toggle it’s “hidden” state correctly:
/**
* 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' );
Read more in this answer for an explanation of the technique used above.
And now for actually hiding the “hidden” posts, it should be as simple as:
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' );