繁体   English   中英

在 WooCommerce 单个产品标题下显示自定义字段

[英]Display a custom field under WooCommerce single product title

我在 WooCommerce 中遇到自定义字段的问题。

我有产品(书),我想添加带有自定义字段的作者。 我通过在主题自定义字段中注册来完成它,并使用 Wordpress 自定义字段添加新的。

自定义字段调用: product_author (即我的)和mbt_publisher_name (来自主题)

我在主题和 woocommerce 目录中找到了模板文件title.php

我尝试添加:

<?php echo get_post_meta($id, "product_author", true); ?> 

没有任何变化......来自title.php的原始来源

    <?php
/**
 * Single Product title
 *
 * @author  WooThemes
 * @package WooCommerce/Templates
 * @version 1.6.4
 */

if ( ! defined( 'ABSPATH' ) ) {
    exit; // Exit if accessed directly
}

?>

<h2 itemprop="name" class="product_title entry-title"><?php the_title(); ?></h2>

我应该怎么做才能在标题下显示该自定义字段?
我在哪里可以找到那个钩子?

谢谢

如果您查看 woocommerce 模板content-single-product.php您将看到以下代码(从第 54 行开始):

/**
 * woocommerce_single_product_summary hook.
 *
 * @hooked woocommerce_template_single_title - 5
 * @hooked woocommerce_template_single_rating - 10
 * @hooked woocommerce_template_single_price - 10
 * @hooked woocommerce_template_single_excerpt - 20
 * @hooked woocommerce_template_single_add_to_cart - 30
 * @hooked woocommerce_template_single_meta - 40
 * @hooked woocommerce_template_single_sharing - 50
 * @hooked WC_Structured_Data::generate_product_data() - 60
 */
do_action( 'woocommerce_single_product_summary' );

因此woocommerce_template_single_title以优先级为5的优先级挂在woocommerce_single_product_summary动作钩子中(所以它是第一个)。

您可以通过 2 种方式进行操作:

1)您可以使用优先级在69之间的woocommerce_single_product_summary钩子中挂钩的自定义函数,这样:

add_action( 'woocommerce_single_product_summary', 'custom_action_after_single_product_title', 6 );
function custom_action_after_single_product_title() { 
    global $product; 

    $product_id = $product->get_id(); // The product ID

    // Your custom field "Book author"
    $book_author = get_post_meta($product_id, "product_author", true);

    // Displaying your custom field under the title
    echo '<p class="book-author">' . $book_author . '</p>';
}

代码位于活动子主题(或主题)的 function.php 文件或任何插件文件中。

此代码经过测试并适用于 WooCommerce 3.0+


或者

2)您可以直接编辑位于您活动主题的 WooCommerce 文件夹的模板single-product/title.php 请参阅下面有关通过主题覆盖 WooCommerce 模板的参考

<?php
/**
 * Single Product title
 *
 * @author  WooThemes
 * @package WooCommerce/Templates
 * @version 1.6.4
 */

if ( ! defined( 'ABSPATH' ) ) {
    exit; // Exit if accessed directly
}

// Calling global WC_Product object
global $product;

$product_id = $product->get_id(); // The product ID

// Your custom field "Book author"
$book_author = get_post_meta($product_id, "product_author", true);

?>

<h2 itemprop="name" class="product_title entry-title"><?php the_title(); ?></h2>

<p class="book-author"><?php echo $book_author; ?></p>

官方参考:模板结构 + 通过主题覆盖 WooCommerce 模板

我向您推荐第一种方法,因为它使用钩子更干净,如果模板更新,您将不需要进行任何更改。 您还应该更好地使用子主题……

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM