Home > Mobile >  Show Custom Taxonomy Before WooCommerce Product title
Show Custom Taxonomy Before WooCommerce Product title

Time:10-30

I have created a custom taxonomy (shipment-status) for WooCommerce products having two terms i.e [Shipped from abroad & Available now]

Only one term is selected per product. I will like to show the selected term above the WooCommerce product title on the single product page and on the archive card as seen in the images below. I would like to style the two terms differently, so will like to have a class attached to them.

Am currently using the snippet below to display it but how do i change the class based on the term name or 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 }
}

Thanks in advance for helping.

enter image description hereenter image description here

CodePudding user response:

There are some things to be aware of but you could just use the term's slug as a class in the div like this:

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>";
    }
}

You have to be aware that in general slugs are not always valid css class names. But since you create the taxonomy and you say that there are exactly two terms I assume you also create the terms and you do not allow users to add or delete them. In that case you can specify the slugs for those terms when you create them and safely use them as css class names.

CodePudding user response:

Below is the snippet to show the taxonomy on the single product page.If anyone every needs it.

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>";
    }
}
  • Related