如果产品类别有子级,则从WooCommerce的父条款中删除永久链接

问题描述

get woocommerce categories with subcategory的启发,我正在创建一个下拉部分,我想知道是否有任何方法可以从父类别中删除永久链接(如果它具有子类别)。

这是我的代码示例:

apipassword=sys.argv[2]#'a'
loginst=apiuser+':'+apipassword
userAndPass =b64encode(loginst).decode("ascii")

仅当没有子条款时,如何才能在顶级产品类别条款上显示链接

解决方法

以下内容将显示产品类别术语的列表,其中如果顶层术语具有任何子术语,则顶级术语将不会被链接:

<?php
$taxonomy     = 'product_cat';

$parent_terms = get_terms( array(
    'taxonomy'   => $taxonomy,'hide_empty' => false,'parent'     => 0
) );

echo '<ul>';

// Loop through top level terms
foreach ( $parent_terms as $parent_term ) {
    $term_link  = get_term_link( $parent_term,'product_cat' );
    $thumb_id   = get_woocommerce_term_meta( $parent_term->term_id,'thumbnail_id',true );
    $image_html = $thumb_id > 0 ? '<img src="' . wp_get_attachment_url( $thumb_id ) . '"/>' : '';

    // Get children terms
    $child_terms = get_terms( array(
        'taxonomy'   => $taxonomy,'parent'     => $parent_term->term_id
    ) );

    // 1. There are children terms
    if( ! empty($child_terms) ) {
        echo '<li>' . $image_html . $parent_term->name . '</li>
        <ul>';

        // Loop through children terms
        foreach ( $child_terms as $term ) {
            $term_link = get_term_link( $term->term_id,$taxonomy );

            echo '<li><a href="' . $term_link . '">' . $term->name . '</a></li>';
        }

        echo '</ul>';
    }
    // 2. There are NOT children terms
    else {
        $parent_term_link = get_term_link( $parent_term->term_id,$taxonomy );

        echo '<li>' . $image_html . '<a href="' . $parent_term_link . '">' . $parent_term->name . '</a></li>';
    }
}
echo '</ul>';

经过测试可以正常工作。