为了账号安全,请及时绑定邮箱和手机立即绑定

通过短代码获取 Woocommerce 产品标签帖子计数

通过短代码获取 Woocommerce 产品标签帖子计数

PHP
倚天杖 2023-08-11 18:03:28
我需要计算整个网站上使用“产品标签”的次数。每个产品都有许多与之相关的标签。我考虑过创建一个短代码,然后在需要时可以引用。我在下面创建的短代码会使网站崩溃。// function function tag_count_shortcode() {  // Identify the tag ID and then run a count. $term = get_tag( $tag_ID );$count = $term->count;  // Output the total number of times a tag is usedreturn $count;} // register shortcodeadd_shortcode('tagcount', 'tag_count_shortcode'); 我不确定我哪里出了问题。非常感谢任何帮助。平台:WordPress | 包含代码的文件:“Functions.php”
查看完整描述

1 回答

?
largeQ

TA贡献2039条经验 获得超7个赞

这是关于产品标签,它是 WooCommerce 自定义分类法,而不是 WordPress 标签。

此外,一个产品可以有多个产品标签,因此以下代码将处理第一个产品标签术语的计数。这个短代码还处理一些参数:

  • (也taxonomy可以处理任何自定义分类法、WordPress 标签和类别)- 默认情况下:产品标签

  • term_id可以处理任何定义的术语 ID) - 默认情况下它会在单个产品页面上获取术语

  • -post_id默认情况下当前产品 ID

代码:

function term_count_shortcode( $atts ) {

    extract( shortcode_atts( array(

        'taxonomy'  => 'product_tag', // Product tag taxonomy (by default)

        'term_id' => 0,

        'post_id' => get_queried_object_id(), // The current post ID

    ), $atts ) );


    // For a defined term ID

    if( $term_id > 0 ) {

        // Get the WP_term object

        $term = get_term_by( 'id', $term_id, $taxonomy );


        if( is_a( $term, 'WP_Term' ) )

            $count = $term->count;

        else

            $count = 0;

    }

    // On product single pages

    elseif ( is_product() && $term_id == 0 && $post_id > 0 ) {

        // Get the product tag post terms

        $terms = get_the_terms( $post_id, $taxonomy );

        // Get the first term in the array

        $term  = is_array($terms) ? reset( $terms ) : '';


        if( is_a( $term, 'WP_Term' ) )

            $count = $term->count;

        else

            $count = 0;

    } else {

        $count = false;

    }

    return $count;

}

add_shortcode('term_count', 'term_count_shortcode');

代码位于活动子主题(或活动主题)的 function.php 文件中。经过测试并有效。


用法:

1)。基本用法:显示产品单页第一个产品标签计数:[term_count]

2)。与参数一起使用:

  • 使用定义的术语 ID:[term_count term_id="58"]

  • 具有定义的术语 ID 和分类法:[term_count term_id="15" taxonomy="product_cat"]

  • 使用定义的术语 ID 和帖子 ID:[term_count term_id="15" post_id="37"]


查看完整回答
反对 回复 2023-08-11
  • 1 回答
  • 0 关注
  • 96 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信