当前位置: 首页 > 知识库问答 >
问题:

在WooCommerce档案页面中的产品标题下添加自定义域值

贺文彬
2023-03-14

在WooCommerce中,我想添加自定义文本到我的产品显示,这将从产品的编辑页面中的自定义字段抓取。

这就是现在的样子:

我找到了一些自定义php代码来在产品的页面中添加自定义字段,如下所示:

    // Display Fields
add_action('woocommerce_product_options_general_product_data', 'woocommerce_product_custom_fields');

// Save Fields
add_action('woocommerce_process_product_meta', 'woocommerce_product_custom_fields_save');

function woocommerce_product_custom_fields()
{
    global $woocommerce, $post;
    echo '<div class="product_custom_field">';
    // Custom Product Text Field
    woocommerce_wp_text_input(
        array(
            'id' => '_custom_product_text_field',
            'placeholder' => 'Custom Product Text Field',
            'label' => __('Custom Product Text Field', 'woocommerce'),
            'desc_tip' => 'true'
        )
    );

}

function woocommerce_product_custom_fields_save($post_id)
{
    // Custom Product Text Field
    $woocommerce_custom_product_text_field = $_POST['_custom_product_text_field'];
    if (!empty($woocommerce_custom_product_text_field))
        update_post_meta($post_id, '_custom_product_text_field', esc_attr($woocommerce_custom_product_text_field));
}

如何显示产品标题下的自定义域

共有1个答案

鄢英哲
2023-03-14

更新:

尝试此自定义挂钩函数,它将在产品标题下面显示自定义域值:

add_action( 'woocommerce_after_shop_loop_item_title', 'custom_field_display_below_title', 2 );
function custom_field_display_below_title(){
    global $product;

    // Get the custom field value
    $custom_field = get_post_meta( $product->get_id(), '_custom_product_text_field', true );

    // Display
    if( ! empty($custom_field) ){
        echo '<p class="my-custom-field">'.$custom_field.'</p>';
    }
}

代码放在您的活动子主题(或活动主题)的function.php文件中。

 类似资料: