如果您查看 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 被 woocommerce_single_product_summary 动作钩子钩住,优先级为 5 (所以它来了首先)。
您可以通过 2 种方式做到这一点:
1) 您可以使用 woocommerce_single_product_summary 挂钩中的自定义函数,其优先级介于 6 到 9 之间,这样:
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) 您可以直接编辑模板 single-product/title.php 位于 WooCommerce 文件夹中您的活动主题 (see below the reference about overriding WooCommerce templates through theme):
<?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>
官方参考:Template Structure + Overriding WooCommerce Templates via a Theme
我向您推荐第一种方法,因为它使用挂钩更简洁,并且如果更新模板,您无需进行任何更改。您还应该更好地使用子主题...