如何更改此代码以接受插件和ID?

时间:2014-04-25 作者:Desi

此代码来自codex.

/* ==  If In Parent Category... ==============================*/

if ( ! function_exists( \'post_is_in_descendant_category\' ) ) {
    function post_is_in_descendant_category( $cats, $_post = null ) {
        foreach ( (array) $cats as $cat ) {
            // get_term_children() accepts integer ID only
            $descendants = get_term_children( (int) $cat, \'category\' );
            if ( $descendants && in_category( $descendants, $_post ) )
                return true;
        }
        return false;
    }
}
我在主题中使用它,如下所示:

if ( post_is_in_descendant_category( 11 ) ) ...

它只接受post ID(11), 然而,我希望它能接受子弹。有没有办法以某种方式修改此代码以接受slug?

1 个回复
最合适的回答,由SO网友:s_ha_dum 整理而成

法典基本上解释了如何做到这一点:

if ( $category_to_check = get_term_by( \'name\', \'fruit\', \'category\' ))
   post_is_in_descendant_category($category_to_check->term_id);

https://codex.wordpress.org/Function_Reference/in_category#Testing_if_a_post_is_in_a_descendant_category

将所有这些放在您的功能中,您将拥有:

if ( ! function_exists( \'post_is_in_descendant_category\' ) ) {
    function post_is_in_descendant_category( $cats, $_post = null ) {
        foreach ( (array) $cats as $cat ) {
            if (!absint($cat)) {
//            $cat = get_category_by_slug($cat); // option one
              $cat = get_term_by(\'slug\',$cat,\'category\'); // option two
//            $cat = get_term_by(\'name\',$cat,\'category\'); // option three; by category name, not slug, as in the Codex
              if(!$cat) return false;
              $cat = $cat->term_id;
            }
            // get_term_children() accepts integer ID only
            $descendants = get_term_children( (int) $cat, \'category\' );
            if ( $descendants && in_category( $descendants, $_post ) )
                return true;
        }
        return false;
    }
}

结束

相关推荐

如何使用phpMyAdmin合并类别

我尝试了以下phpMyAdmin查询,以将我的类别112747合并到类别112748中:UPDATE `wp_term_relationships` SET `term_taxonomy_id` = 112747 WHERE `term_taxonomy_id` = 112748; 它不起作用。查询包含哪些错误?wordpress 3.8.2phpMyAdmin 4.18MySQL 5.5.34-cll-lve我的一个wordpress网站有近300000篇帖子,大多数类别至少包