php - 将相关产品类别描述附加到 Woocommerce 中的产品描述

标签 php wordpress woocommerce product wordpress-hook

我无法在每个项目下方的“描述”选项卡的每个产品的每个描述末尾添加产品的类别描述。到目前为止,我的函数(在底部)放置了所有类别描述,而不是产品实际所属的一个类别。

Here's the example带有描述页面的类别。

Sample product page with description (起始于:美国原住民的故事和传说传统上服务于……的故事)

这是我用来组合两个函数的代码。它可以添加所有类别描述,但我试图使其仅显示一个相关描述:

add_filter( 'the_content', 'customizing_woocommerce_description' );
function customizing_woocommerce_description( $content ) {

    // Only for single product pages (woocommerce)
    if ( is_product() ) {

        // The custom content
        $args  = array( 'taxonomy' => 'product_cat' );
        $terms = get_terms('product_cat', $args);

        $count = count($terms); 
        // if ($count > 0) {

            foreach ($terms as $term) {
                /*  echo $term->description;*/
                $custom_content = '<p class="custom-content">' . __($term->description, "woocommerce").'</p>';

                // Inserting the custom content at the end
                $content .= $custom_content;
            }
        // }
    }
    return $content;
}

https://pastebin.com/GHBxe23i

到目前为止,我正在 WordPress 的非破坏性 php 插件中实现代码。

最佳答案

您应该在代码中将 get_terms() 替换为 wp_get_post_terms(),如下所示:

add_filter( 'the_content', 'woocommerce_custom_product_description', 20, 1 );
function woocommerce_custom_product_description( $content ) {
    global $post;

    // Only for woocommerce single product pages
    if ( ! is_product() ) 
        return $content; // exit

    $terms =  wp_get_post_terms( $post->ID, 'product_cat' );
    if ( count( $terms ) == 0 ) 
        return $content; // exit

    foreach ( $terms as $term )
        $content .= '<p class="custom-content">' . $term->description . '</p>';

    return $content;
}

代码位于事件子主题(或主题)的 function.php 文件中。已测试且有效。

关于php - 将相关产品类别描述附加到 Woocommerce 中的产品描述,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49391466/

相关文章:

php - 数据库中的数据未出现在 PHP 应用程序的表中

php - 设置灯箱的最小和最大高度,当使用下一个/上一个按钮时,它会覆盖 css

php - .po 文件中的 CakePhp i18n 翻译词顺序

php - 普通 wordpress 菜单和移动菜单之间的分辨率差距

php - 如何更改 Woocommerce 星级评分的位置

php - 将 null 转换为字符串

php - WooCommerce 按标签或描述搜索产品查询帖子

sql - SQL查询的确认

php - 在 WooCommerce 中隐藏基于产品类型的付款方式

php - 获取与 Woocommerce 中的产品类别相关的所有属性及其术语