在 Woocommerce 单品页面中显示自定义分类法

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

我使用以下代码向 Woocommerce 添加了一个名为“供应商”的新分类法:

// hook into the init action and call taxonomy when it fires

add_action( 'init', 'create_vendor_taxonomy', 0 );

// create and register vendor taxonomy (hierarchical)

function create_vendor_taxonomy() {

    $labels = array(
        'name'              => _x( 'Vendors', 'taxonomy general name', 'textdomain' ),
        'singular_name'     => _x( 'Vendor', 'taxonomy singular name', 'textdomain' ),
        'search_items'      => __( 'Search Vendors', 'textdomain' ),
        'all_items'         => __( 'All Vendors', 'textdomain' ),
        'parent_item'       => __( 'Parent Vendor', 'textdomain' ),
        'parent_item_colon' => __( 'Parent Vendor:', 'textdomain' ),
        'edit_item'         => __( 'Edit Vendor', 'textdomain' ),
        'update_item'       => __( 'Update Vendor', 'textdomain' ),
        'add_new_item'      => __( 'Add New Vendor', 'textdomain' ),
        'new_item_name'     => __( 'New Vendor Name', 'textdomain' ),
        'menu_name'         => __( 'Vendors', 'textdomain' ),
    );

    $args = array(
        'hierarchical'      => true,
        'labels'            => $labels,
        'show_ui'           => true,
        'show_admin_column' => true,
        'query_var'         => true,
        'rewrite'           => array( 'slug' => 'vendor' ),
    );

    register_taxonomy( 'vendor', array( 'product' ), $args );

}

我想在单个产品页面上出现的类别和标签标签之间插入这个新分类法。

我有一个子主题,我知道我必须在子主题中创建一个 woocommerce 文件夹,然后将我必须编辑的 woo 模板文件的副本添加到该文件夹。

有人能帮帮我吗?

  1. 我必须编辑哪些 woo 模板文件?
  2. 我需要在这些文件中添加什么代码才能将我的新分类法插入产品页面?

在此先感谢您提供任何帮助。

更新: 经过进一步研究,我似乎不需要编辑 Woo 模板文件。

单个产品页面上的类别和标签元下方有一个挂钩。这样就可以了。

所以我可以使用以下内容插入供应商分类详细信息:

add_action( 'woocommerce_product_meta_end', 'insert_vendor_custom_action', 5 );

function insert_vendor_custom_action() {
    global $product;
    if [WHAT DO I NEED HERE?]
    echo [WHAT DO I NEED HERE?];
}

感谢任何能帮助我的人。

php wordpress woocommerce product custom-taxonomy
2个回答
11
投票

要在 Woocommerce 单个产品页面的元部分中显示来自自定义分类术语的帖子术语,您不需要覆盖任何 Woocommerce 模板。

相反,您可以通过这种方式使用特定的专用操作挂钩:

add_action( 'woocommerce_product_meta_end', 'action_product_meta_end' );
function action_product_meta_end() {
    global $product;

    $taxonomy = 'vendor'; // <== Here set your custom taxonomy

    if( ! taxonomy_exists( string $taxonomy ) ) 
        return; // exit
    
    $term_ids = wp_get_post_terms( $product->get_id(), $taxonomy, array('fields' => 'ids') );

    if ( ! empty($term_ids) ) {
        echo get_the_term_list( $product->get_id(), 'vendor', '<span class="posted_in">' . _n( 'Vendor:', 'Vendors:', count( $term_ids ), 'woocommerce' ) . ' ', ', ', '</span>' );
    }
}

代码进入您的活动子主题(或活动主题)的 function.php 文件。 测试和工作。


0
投票

keeping

string $taxonomy
将导致 php 错误,可以通过删除
string
并保留代码作为
if( ! taxonomy_exists( $taxonomy ) )
来解决问题

© www.soinside.com 2019 - 2024. All rights reserved.