自定义下拉列表的条款作为链接(woocommerce,wordpress)

Custom dropdown list of terms as links (woocommerce, wordpress)

我想添加一个属性的自定义下拉列表(在本例中是品牌),选项导致属性页面作为 link。

我成功了

add_filter('woocommerce_before_shop_loop','wc_reg_for_menus', 1, 2);
function wc_reg_for_menus() {
    $terms = get_terms( 'pa_marke' );
    if ( ! empty( $terms ) && ! is_wp_error( $terms ) ){
        echo '<select>';
        foreach ( $terms as $term ) {
            echo '<option value="'.$term->name.'">'.$term->name.'</option>';
        }
        echo '</select>';
    }
}

而且我想我需要以某种方式添加这部分

get_term_link( WP_Term|int|string $term, string $taxonomy = '' )

谢谢! 菲利克斯

您的代码可以很好地获取特定分类法(属性)的值。
我只更改了 get_terms 函数。

我还添加了一些数据属性来获取每个术语的分类法和 slug(选项)。

add_filter( 'woocommerce_before_shop_loop','wc_reg_for_menus' );
function wc_reg_for_menus() {

    $terms = get_terms( array(
        'taxonomy' => 'pa_marke',
        'hide_empty' => false,
    ));

    if ( ! empty( $terms ) && ! is_wp_error( $terms ) ){
        echo '<select id="shop_pa_marke">';
        foreach ( $terms as $term ) {
            echo '<option value="' . $term->name . '" data-taxonomy="' . $term->taxonomy . '" data-slug="' . $term->slug . '">' . $term->name . '</option>';
        }
        echo '</select>';
    }
}

然后您将需要使用 jQuery 脚本根据所选的属性选项重定向用户。

add_action( 'wp_footer', 'redirect_after_select_option' );
function redirect_after_select_option() {
    ?>
    <script type="text/javascript">
        jQuery( function($){
            $('#shop_pa_marke').change(function(){

                const url = window.location.href;
                const taxonomy = $(this).children("option:selected").data('taxonomy').replace('pa_','filter_');
                const slug = $(this).children("option:selected").data('slug');

                let urlParams = new URLSearchParams(window.location.search);
                urlParams.set(taxonomy, slug);
                window.location.replace( '?'+urlParams.toString() );

            });
        });
    </script>
    <?php
}

代码已经过测试并且可以工作。将它添加到您的活动主题 functions.php.

谢谢!

刚才我找到了一个没有 jQuery 的解决方案,它也很好用:



add_filter('woocommerce_before_shop_loop','wc_reg_for_menus', 1, 2);
function wc_reg_for_menus() {
     $terms = get_terms( 'pa_marke' );
 
if ( ! empty( $terms ) && ! is_wp_error( $terms ) ){
 
echo '<select onchange="location = this.value;">';
 
foreach ( $terms as $term ) {
 
echo '<option value="'.get_term_link( $term ).'">'.$term->name.'</option>';
}
 
echo '</select>';
 
}
}

只有在新页面加载后,才会再次选择菜单的第一个选项,但这对我来说没问题,因为以后不会显示在那里。