3

I am stuck on this one and it's probably a really simple answer but can anyone please shine some light on how to add a filter menu with an option value of 'No Tags' that when clicking the Filter button will only show posts that have no tags associated with them? Many thanks in advance!

1

The first part is to add a dropdown using restrict_manage_posts filter, and the second one is to actually get posts without tags using pre_get_posts filter:

function wpse147471_add_no_tags_filter() {
    if ( 'post' !== get_current_screen()->post_type ) {
        return;
    }

    $selected = ( isset( $_GET['tag-filter'] ) && 'no-tags' === $_GET['tag-filter'] );
    ?>
    <select name="tag-filter">
        <option value="">&mdash; Select &mdash;</option>
        <option value="no-tags" <?php echo selected( $selected ); ?>>No Tags</option>
    </select>
    <?php
}
add_action( 'restrict_manage_posts', 'wpse147471_add_no_tags_filter' );

function wpse147471_get_posts_with_no_tags( $query ) {
    if ( ! is_admin() || ! $query->is_main_query() ) {
        return;
    }

    if ( ! isset( $_GET['tag-filter'] ) || 'no-tags' !== $_GET['tag-filter'] ) {
        return;
    }

    $tag_ids = get_terms( 'post_tag', array( 'fields' => 'ids' ) );

    $query->set( 'tax_query', array(
        array(
            'taxonomy' => 'post_tag',
            'field'    => 'id',
            'terms'    => $tag_ids,
            'operator' => 'NOT IN'
        )
    ) );
}
add_action( 'pre_get_posts', 'wpse147471_get_posts_with_no_tags' );

Looks like there is no cleaner way to get all posts without tags via WP_Query than using a 'NOT IN' taxonomy query with all existing tag IDs, but at least it works.

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.