我,正在寻找一种解决方案,在不影响单品页面标题的情况下为商店页面使用不同的产品标题。这是一个例子我想要实现的https://www.slickwraps.com/devices/phones/ios/iphone-xs-max.html你可以在上面看到链接产品标题在商店页面上是不同的,我知道这个网站是在不同的CMS中建立但我们可以在Woocommerce中实现类似的结果吗?
这是你可以做的。将以下代码添加到theme functions.php文件中。代码将在“产品数据” - >“常规”选项下添加自定义标题选项。如果未在管理员中添加自定义标题,它将显示默认标题。
在后端添加自定义字段
// Display the custom text field
function mos_create_custom_field() {
$args = array(
'id' => 'shop_page_field_title',
'label' => __( 'Shop Page product title' ),
'class' => 'mos-custom-field',
'desc_tip' => true,
'description' => __( 'Shop Page product title.', 'ctwc' ),
);
woocommerce_wp_text_input( $args );
}
add_action( 'woocommerce_product_options_general_product_data', 'mos_create_custom_field' );
add_action( 'woocommerce_product_options_inventory_product_data', 'mos_create_custom_field' );
保存自定义字段值
// Save the custom field
function mos_save_custom_field( $post_id ) {
$product = wc_get_product( $post_id );
$title = isset( $_POST['shop_page_field_title'] ) ? $_POST['shop_page_field_title'] : '';
$product->update_meta_data( 'shop_page_field_title', sanitize_text_field( $title ) );
$product->save();
}
add_action( 'woocommerce_process_product_meta', 'mos_save_custom_field' );
在商店页面上显示
// remove the default action for product title on shop page
remove_action( 'woocommerce_shop_loop_item_title', 'woocommerce_template_loop_product_title' );
// add the custom action to show the custom product title
add_action( 'woocommerce_shop_loop_item_title', 'custom_woocommerce_template_loop_product_title', 99 );
function custom_woocommerce_template_loop_product_title() {
global $post;
$product = wc_get_product( $post->ID );
$title = $product->get_meta( 'shop_page_field_title' );
if( $title ) {
// Only display our field if we've got a value for the field title
echo '<h2 class="woocommerce-loop-product__title">' . esc_html( $title ) . '</h2>';
} else {
// else display the defaul title
echo '<h2 class="woocommerce-loop-product__title">' . esc_html( $product->get_title() ) . '</h2>';
}
}
代码经过测试且运行正常。希望能帮助到你