Query categories that have a description

I want to query the categories and tags that have a description to make sure only those are listed in the sitemap. The description__like argument used by get_terms() is the closest I've gotten to it.

// Clean sitemap
// https://wordpress.org/support/topic/remove-the-archive-pages-from-the-sitemap/

add_filter(
    'wp_sitemaps_taxonomies_query_args',
    function( $args, $taxonomy ) {
        // Show in sitemap categories and topics that have a description
        if ( $taxonomy == 'category' || $taxonomy == 'post_tag' ) {
            # First attempt
            $args['description__like'] = '';

            # Desperate second attempt
            $args['meta_query'][] = array(
                'key' = 'description',
                'value'   = array(''),
                'compare' = 'NOT IN'
            );

            # Third attempt: seems to work
            $args['description__like'] = ' ';
        }

        return $args;
    },
    10,
    2
);

The third approach with the empty space seems to work, but I feel unsure about edge cases as I don't know why it works. Any clue about a more explicit way to do it or is this one OK?

Topic sitemap hooks Wordpress

Category Web


How about looping all available terms, if term has description, add to to an object_ids, something like this.

add_filter(
    'wp_sitemaps_taxonomies_query_args',
    function( $args, $taxonomy ) {
        // Show in sitemap categories and topics that have a description
        if ( $taxonomy == 'category' || $taxonomy == 'post_tag' ) {
            // get the terms of the taxonomy
            $terms = get_terms( 'post_tag', [
                'hide_empty' => false, // change to true if you want not empty terms
                'taxonomy'   => $taxonomy,
            ]);

            // will contain all ids of terms that have description
            $object_ids = [];

            // loop terms
            foreach ($terms as $term) {
                // if term has description, add its id to our array
                if (!empty($term->description)) $object_ids[] = $term->term_id;
            }

            // if we have ids (found terms with description) add it to the filter $args
            if (!empty($object_ids)) $args['object_ids'] = $object_ids;
        }

        return $args;
    },
    10,
    2
);

About

Geeks Mental is a community that publishes articles and tutorials about Web, Android, Data Science, new techniques and Linux security.