WooCommerce店铺循环随机数组函数后值不相同



我使用这个数组函数在WooCommerce商店循环中输出随机输入值。我现在试着让它像这样,相同的输入不会被依次选择。

:数组中有4个不同的输入值。现在,如果[0]是随机选择的,那么第二次捕获就不可能再次选择[0]。只有[1],[2]和[4]是可能的。如果第二个输入选择[2],那么第三个输入只选择值[0],[1]和[3]。

In general:不依次选择相同的数组值作为输入。但是有些输入可能不止一次被选中,而不是一个接一个地被选中。

有可能吗?

// Adding custom content block to shop loop row
add_action( 'woocommerce_shop_loop', 'add_custom_content_to_shop_loop_row' );
function add_custom_content_to_shop_loop_row() {
// Variables
global $wp_query;

// Custom array input options
$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'>" );
// Column count
$columns = esc_attr( wc_get_loop_prop( 'columns' ) );

// Add content every X product
if ( (  $wp_query->current_post % 7 ) ==  0 && $wp_query->current_post !=  0 ) {

// output random array custom content
$rand_keys = array_rand($input, 1);
echo $input[$rand_keys] . "n";
}
}

我试着从这里使用一个方法https://ofstack.com/PHP/37611/summary-of-5-methods-of-generating-non-repeating-random-numbers-in-php.html,但它根本不起作用。

有几种方法,您可以通过cookie,会话,瞬态,元数据等临时存储值。但我个人会选择一个全局变量,这样就不需要数据库请求了。

得到:

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

您必须以某种方式记住先前选择的值,然后在下次调用该函数时忽略该键。

// Get the latest key - I've saved this as a transient, but you can use another method.
$previous = get_transient( 'previous_content_index' );
if ( $previous !== false ) { // Check explicitly for false, as the previous key may be "0".
// Array diff will temporarily remove the previous index.
$input = array_diff_key( $input, array( $previous => '' ) );
}
$rand_keys = array_rand($input, 1);
// Remember this key for next time.
set_transient( 'previous_content_index', $rand_keys, DAY_IN_SECONDS );

最新更新