限制 WooCommerce 产品后端的字符/单词数量

问题描述 投票:0回答:1

当我们在 WooCommerce 中创建产品时,我想要 :

  • 产品标题限制为 30 个字符
  • 产品简短描述限制为50个字

我发现很多短代码在前端限制了它,但我想在后端限制它,这样商店经理本身就被迫遵守这个限制。

enter image description here

enter image description here

php wordpress woocommerce product limit
1个回答
0
投票

您可以使用

wp_insert_post_data
过滤钩和一些
PHP
工作使其成为可能。

使用以下代码限制标题和产品内容的字数。

给定的代码将从标题和内容中删除多余的单词。

function limit_product_title_and_content_words($data, $postarr) {
    // Check if it's a product
    if ($data['post_type'] == 'product') {
        // Explode the title into an array of words
        $title_words = explode(' ', $data['post_title']);
        $content_words = explode(' ', $data['post_content']);

        // If the number of words exceeds the maximum, truncate the title
        if(!empty($data['post_title'])){
            if (count($title_words) > 30) {
                $data['post_title'] = implode(' ', array_slice($title_words, 0, 30));
            }
        }
        if(!empty($data['post_content'])){ 
            if (count($content_words) > 50) {
                $data['post_content'] = implode(' ', array_slice($content_words, 0, 50));
            }
        }

    }
    return $data;
}

add_filter('wp_insert_post_data', 'limit_product_title_and_content_words', 10, 2);

代码经过测试和运行

© www.soinside.com 2019 - 2024. All rights reserved.