仅在 Woocommerce 单个产品页面中显示特定自定义字段值的文本

Show text only for a specific custom field value in Woocommerce single product pages

我试图在单个产品页面上显示自定义文本 'price only visible for logged in users',但仅当 $wpdb->postmetametafield 'show' 的值为 'yes',从当前 'post_id'.

加载单个产品页面时,我找不到正确的 SQL 查询来实现当前产品 post_id

这是我的代码:

function show_text() {
    global $wpdb;   
    $post_id_number = get_the_id();

    $meta = $wpdb->get_results( "select * from $wpdb->wp_postmeta WHERE meta_key = 'show' AND meta_value = 'yes'" );

    if ( $meta == TRUE ) {
        echo '<p>PRice is only visible for logged in users</p>';
    }
}
add_action( 'woocommerce_before_single_product', 'show_text' );

您可以这样简单地使用 Wordpress get_post_meta() 功能:

add_action( 'woocommerce_before_single_product', 'show_custom_text' );
function show_custom_text() {
    global $post;

    if ( get_post_meta( $post->ID, 'show', true ) == 'yes' && ! is_user_logged_in() ) {
        echo '<p>PRice is only visible for logged in users</p>';
    }
}

代码进入您的活动子主题(或活动主题)的 function.php 文件。它应该可以工作。