Search
 
SCRIPT & CODE EXAMPLE
 
CODE EXAMPLE FOR PHP

WooCommerce shop loop random array function not same values after each other

function random_result() {
    // Input
    $input = array( '<img src="/wp-content/uploads/2022/01/banner-001.svg">', '<img src="/wp-content/uploads/2022/01/banner-002.svg">', '<img src="/wp-content/uploads/2022/01/banner-003.svg">' );

    // NOT isset (result) OR NOT isset (counter)
    if ( ! isset( $GLOBALS['result'] ) || ! isset( $GLOBALS['counter'] ) ) {
        // Shuffle an array
        shuffle( $input );

        // Globals
        $GLOBALS['result'] = $input;
        $GLOBALS['counter'] = 0;
    } else {
        // Plus 1
        $GLOBALS['counter'] += 1;
    }

    // Store
    $counter = $GLOBALS['counter'];

    // Limit is reached, reset
    if ( $counter == ( count( $input ) - 1 ) ) {
        unset( $GLOBALS['counter'] );
    }

    return $GLOBALS['result'][$counter];
}

function action_woocommerce_shop_loop() {
    // Variables
    global $wp_query;
    
    // Add content every X product
    if ( (  $wp_query->current_post % 7 ) ==  0 && $wp_query->current_post !=  0 ) {
        // Call function, display result
        echo random_result();
    }
}
add_action( 'woocommerce_shop_loop', 'action_woocommerce_shop_loop' );
 
PREVIOUS NEXT
Tagged: #WooCommerce #shop #loop #random #array #function #values
ADD COMMENT
Topic
Name
6+3 =