【问题标题】:Show Custom Taxonomy Before WooCommerce Product title在 WooCommerce 产品标题之前显示自定义分类
【发布时间】:2021-12-13 22:41:33
【问题描述】:

我为 WooCommerce 产品创建了一个自定义分类法(shipment-status),它有两个术语,即 [从国外发货且现在可用]

每个产品只选择一个术语。我想在单个产品页面和存档卡上的 WooCommerce 产品标题上方显示所选术语,如下图所示。我想为这两个术语设置不同的样式,因此希望为它们附加一个类。

目前正在使用下面的 sn-p 来显示它,但我如何根据术语名称或 id 更改类?

add_action( 'woocommerce_before_shop_loop_item_title', 'add_artist_term');
function add_artist_term() {
    $terms = wp_get_post_terms(get_the_ID(), 'shipment-status');
    if (!is_wp_error($terms) && !empty($terms)) { ?>
        <div class="shipment-status"><a href="<?php echo esc_url(get_term_link($terms[0])); ?>"><?php echo esc_html($terms[0]->name); ?></a></div>
    <?php }
}

提前感谢您的帮助。

【问题讨论】:

    标签: php wordpress woocommerce


    【解决方案1】:

    有一些事情需要注意,但你可以像这样在 div 中使用术语的 slug 作为一个类:

    add_action( 'woocommerce_before_shop_loop_item_title', 'add_artist_term');
    function add_artist_term() {
        $terms = wp_get_post_terms(get_the_ID(), 'shipment-status');
        if (!is_wp_error($terms) && !empty($terms)) {
            $term = $terms[0];
            $class = esc_attr( $term->slug );
            $url = esc_url( get_term_link( $term ) );
            $name = esc_html( $term->name );
            echo "<div class=\"shipment-status $class\"><a href=\"$url\">$name</a></div>";
        }
    }
    

    您必须注意,通常 slug 并不总是有效的 css 类名。但是由于您创建了分类并且您说正好有两个术语,我假设您也创建了这些术语并且您不允许用户添加或删除它们。在这种情况下,您可以在创建这些术语时为它们指定 slug,并将它们安全地用作 css 类名。

    【讨论】:

    • 这非常有效。非常感谢
    【解决方案2】:

    下面是在单个产品页面上显示分类的 sn-p。如果每个人都需要它。

    add_action( 'woocommerce_single_product_summary', 'ship_status', 5);
    function ship_status() {
        $terms = wp_get_post_terms(get_the_ID(), 'shipment-status');
        if (!is_wp_error($terms) && !empty($terms)) {
            $term = $terms[0];
            $class = esc_attr( $term->slug );
            $url = esc_url( get_term_link( $term ) );
            $name = esc_html( $term->name );
            echo "<div class=\"shipment-status $class\"><a href=\"$url\">$name</a></div>";
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2021-09-23
      • 1970-01-01
      • 2019-06-15
      • 1970-01-01
      • 2019-10-05
      • 2020-12-04
      • 2021-07-30
      • 2018-06-14
      • 2017-11-16
      相关资源
      最近更新 更多