查询具有说明的类别

时间:2021-08-13 作者:Juan R.

我想查询具有描述的类别和标记,以确保只有这些类别和标记列在网站地图中。这个description__like 使用的参数get_terms() 是我最接近它的。

// 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
);
第三种处理空白区域的方法似乎有效,但我对边缘情况感到不确定,因为我不知道它为什么有效。有没有关于更明确的方法的线索,或者这个方法可以吗?

1 个回复
SO网友:Buttered_Toast

循环所有可用术语如何?如果术语有描述,请添加到object_ids, 像这样的。

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
);

相关推荐

Gutenberg通过wp.hooks.addFilter修改核心分类面板元素

我已经研究过修改现有的编辑器元素……但几乎没有。但我确实在Github得到了一个很好的回复,指出了这一点:https://github.com/WordPress/gutenberg/tree/master/packages/editor/src/components/post-taxonomies#custom-taxonomy-selector显然,分类小组可以通过wp.hooks.addFilter. 这是一个很好的开始!我已经能够使用该代码片段模拟一些虚拟代码,用Dashicon替换分类法面板。(