Answers
There are several ways, you can store the value temporarily via a cookie, sessions, transients, meta data.. but personally I would go for a global variable so that no database requests are needed.
So you get:
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' );
0 comments:
Post a Comment
Thanks