简体   繁体   中英

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

I'm trying to display a custom text 'price only visible for logged in users' on a single product pages, but only when the $wpdb->postmeta , metafield 'show' has value 'yes' , from the current 'post_id' .

I can't find the right SQL query for implement the current product post_id when it's load the single product page.

Here is my code:

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' );

You can simply use Wordpress get_post_meta() function this way:

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>';
    }
}

Code goes in function.php file of your active child theme (or active theme). It should work.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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