Search code examples
phpwordpresswoocommerceproductadvanced-custom-fields

Show ACF field based on time range on WooCommerce single product page


I'm trying to show a text ACF on WooCommerce single product page. Based on time range.

This is the code, which I am currently using:

function time_promo() {
    // Set the correct time zone  (http://php.net/manual/en/timezones.php)
    date_default_timezone_set( 'Europe/Brussels' );
    
    // Set the start time and the end time
    $start_time = mktime( 06, 00, 00, date( 'm' ), date( 'd' ), date( 'y' ) );
    $end_time   = mktime( 15, 00, 00, date( 'm' ), date( 'd' ), date( 'y' ) );
    $time_now   = strtotime( 'now' );
    
    // Check time
    if ($time_now >= $start_time && $time_now <= $end_time){
    
        // Show Field
        echo '<p id="promo">'.get_field('promo').'</p>';
    }
}
add_action( 'woocommerce_single_product_summary', 'time_promo' );

However, this does not show anything on the single product page. Someone who can tell me where the mistake is?


Solution

  • This will work, and if it doesn't, you will see the reason why.

    Adjust to your needs:

    function action_woocommerce_single_product_summary() {
        // Set the correct time zone  (http://php.net/manual/en/timezones.php)
        date_default_timezone_set( 'Europe/Brussels' );
    
        // Set the start time and the end time
        $start_time = mktime( 06, 00, 00, date( 'm' ), date( 'd' ), date( 'y' ) );
        $end_time   = mktime( 21, 00, 00, date( 'm' ), date( 'd' ), date( 'y' ) );
        $time_now   = strtotime( 'now' );
    
        // Check time
        if ( $time_now >= $start_time && $time_now <= $end_time ) {
            
            // ACF plugin is active
            if ( class_exists('ACF') ) {
                // Get field
                $promo = get_field('promo');
            
                // Check if value exists
                if ( $promo ) {
                    // Show Field
                    echo '<p id="promo">' . $promo . '</p>';    
                } else {
                    echo '<p id="promo">ACF field not found!</p>';              
                }
            } else {
                echo '<p id="promo">ACF does not exist!</p>';               
            }
        } else {
            echo '<p id="promo">The time conditions are not met!</p>';  
        }
    }
    add_action( 'woocommerce_single_product_summary', 'action_woocommerce_single_product_summary', 11 );