如何从 Woocommerce 中的后元获取自定义分类法?

问题描述 投票:0回答:1

我在尝试在 WooCommerce 中显示自定义分类中的术语时遇到一些问题。

目前,我已经使用了 WooCommerce 产品类别,因此我创建了一个名为

sale_type

的自定义分类法
function add_custom_taxonomies() {
  // Add new "Sale Type" taxonomy to Posts
  register_taxonomy('sale_type', 'product', array(
    // Hierarchical taxonomy (like categories)
    'hierarchical' => true,
    // This array of options controls the labels displayed in the WordPress Admin UI
    'labels' => array(
      'name' => _x( 'Sale Type', 'taxonomy general name' ),
      'singular_name' => _x( 'Sale Type', 'taxonomy singular name' ),
      'search_items' =>  __( 'Search Sale Type' ),
      'all_items' => __( 'All Sale Type' ),
      'parent_item' => __( 'Parent Sale Type' ),
      'parent_item_colon' => __( 'Parent Sale Type:' ),
      'edit_item' => __( 'Edit Sale Type' ),
      'update_item' => __( 'Update Sale Type' ),
      'add_new_item' => __( 'Add New Sale Type' ),
      'new_item_name' => __( 'New Sale Type Name' ),
      'menu_name' => __( 'Sale Type' ),
    ),
    // Control the slugs used for this taxonomy
    'rewrite' => array(
      'slug' => 'sale-type', // This controls the base slug that will display before each term
      'with_front' => false, // Don't display the category base before "/locations/"
      'hierarchical' => true // This will allow URL's like "/locations/boston/cambridge/"
    ),
  ));
}
add_action( 'init', 'add_custom_taxonomies', 0 );

然后,在我尝试在单个产品页面上显示自定义分类法的术语名称

sale_type
失败时,我使用了 wp_get_post_terms 函数,类似于使用“product_cat”的方式。

这是一个例子:

<span class="badge">
    <?php
    $terms = wp_get_post_terms(get_the_id(), 'sale_type');
    $term = reset($terms);
    echo $term->name;
    ?>
</span>

<span class="badge"><?php $terms=wp_get_post_terms(get_the_id(),'product_cat');$term=reset($terms);echo $term->name; ?></span>

什么也没有输出。首先,我做了明显的事情并检查了“sale_type”自定义分类元框并验证是否选择了术语。然后我尝试使用 get_the_terms 而不是 wp_get_post_terms - 然后还做了一个 var dump 调试输出 = array(0) { }

调试产品的后元,我可以看到所有各种自定义字段,但我在此输出中没有看到“sale_type”分类法。

我以前从未真正使用过自定义分类法,所以我现在很好奇“sale_type”是否可能以不同的方式存储或根本不存储在帖子元中。那么,是否有其他方法可以直接获取自定义分类术语?

谢谢

php wordpress woocommerce taxonomy custom-taxonomy
1个回答
0
投票

我已经尝试过您的 WooCommerce 产品自定义分类法并且它有效......现在我对您的显示代码做了一些小更改。尝试以下操作:

$term_names = wp_get_post_terms( get_the_ID(), 'sale_type', array('fields' => 'names') );
if ( ! empty($term_names) ) {
    printf('<span class="badge">%s</span>', implode(' ', $term_names));
}

如果在产品上设置了术语名称,代码将正确显示术语名称......

  • 我已将
    get_the_id()
    更改为
    get_the_ID()
  • 我已将
    array('fields' => 'names')
    添加为
    wp_get_post_terms()
    作为参数,以直接获取术语名称数组,
  • 由于产品可以有多个术语名称,我使用
    implode()
    而不是
    reset()
    ,
  • 最后,我使用
    IF
    语句来避免在没有为产品设置术语名称时显示...
© www.soinside.com 2019 - 2024. All rights reserved.