Woocommerce: How to show Product Attribute name on title when in a category page and “filtering” products via '?pa_attribute=' on address bar

荒凉一梦 提交于 2021-02-05 11:20:06

问题


So I have a product attribute (for ex.: color) and I can show only products inside a Category that have that attribute by using, for ex., ?pa_color=red in the address bar, so if I go '*www.mysite.com/product-category/t-shirts/?pa_color=red*' I'll have only t-shirts that have the color red as an attribute. That works.
The problem is, when I do that "filtering", the page title (above the product listing) still says only "T-Shirts", it does not specify that it's only showing Red T-shirts and it might confuse clients. What I need is for it to show something like "T-shirts (Color:Red)".
I know I can use sidebar widgets to filter attributes and then the widget will show what is being filtered but in this specific case is a very minimal design without sidebar or any filtering, I need it to show in the title.


回答1:


add_filter( 'woocommerce_page_title', 'custom_woocommerce_page_title', 15, 1 );

function custom_woocommerce_page_title( $page_title ) {
    if ( is_archive() ) {
        $exists_attr = false;

        foreach ( $_GET as $index => $value ) {
            if ( substr( $index, 0, 3 ) === 'pa_' ) {
                $attr_id = wc_attribute_taxonomy_id_by_name( $index );

                if ( $attr_id === 0 ) {
                    continue;
                }

                if ( ! $exists_attr ) {
                    $exists_attr = true;

                    $page_title .= ' (';
                } else {
                    $page_title .= ', ';
                }

                $page_title .= wc_attribute_label( $index ) . ': ' . esc_html( $value );
            }
        }

        if ( $exists_attr ) {
            $page_title .= ')';
        }
    }

    return $page_title;
}


来源:https://stackoverflow.com/questions/52892957/woocommerce-how-to-show-product-attribute-name-on-title-when-in-a-category-page

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!