根据类别向WooCommerce产品标题添加前缀 [英] Add a prefix to WooCommerce product titles based on categories

查看:59
本文介绍了根据类别向WooCommerce产品标题添加前缀的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Is there any chance to have a prefix title for specific categories of woocommerce products?

例如:

如果我将RTX 2080Ti添加到GPU类别,则标题必须为[GPU] RTX 2080Ti.

If I add an RTX 2080Ti to GPU Category the title needs to be [GPU] RTX 2080Ti.

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

I have tried many codes around the internet but couldn't reach my target.

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吗?

Can someone guide to make this function work for 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 );

这篇关于根据类别向WooCommerce产品标题添加前缀的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆