根据类别为 WooCommerce 产品标题添加前缀

Add a prefix to WooCommerce product titles based on categories

是否有机会为特定类别的 woocommerce 产品设置前缀标题?

例如:

如果我将 RTX 2080Ti 添加到 GPU 类别,标题需要是 [GPU] RTX 2080Ti。


我在互联网上尝试了很多代码,但无法达到我的目标。

add_filter('wp_title', 'WPSE_20181106_prepend_title', 10, 3);
function WPSE_20181106_prepend_title($title, $sep, $seplocation) {
    // not a single post
    if (!is_singular('post')) {
        return $title;
    }

    // IDs of categories that should prepend the title
    $prepend_categories = [15, 35];

    // get all categories of post
    $categories = get_the_category();
    foreach ($categories as $category) {
        // found category
        if (in_array($category->term_id, $prepend_categories)) {
            // return new format, using __() so it is translateable
            return sprintf('%s %s: %s',
                __('Download', 'lang-slug'),
                $category->name,
                $title
            );
        }
    }
    // category not found, return default
    return $title;
}

有人可以指导使这个功能适用于 woocommerce 吗?

You can use several Conditional Tags, depending on where you would like to change the product title.

With the code below the adjustment are done on the single product page

function change_title ( $title, $post_id ) {
    // Returns true on a single product page.
    if ( is_product() ) {
        // IDs of categories that should prepend the title
        $prepend_categories = array( 15, 16 );

        // get all categories via post id
        $categories = wp_get_post_terms( $post_id, 'product_cat' ); 

        foreach ( $categories as $category ) {          
            // Find category
            if ( in_array( $category->term_id, $prepend_categories ) ) {
                $title = '[' . $category->name . ']' . $title;
            }
        }
    }

    return $title;
} 
add_filter('the_title', 'change_title', 10, 2 );