Home:ALL Converter>Display random custom content in WooCommerce shop archive loop

Display random custom content in WooCommerce shop archive loop

Ask Time:2022-05-10T01:11:41         Author:Nik7

Json Formatter

I created the code below to display custom content in the shop archive loop. This is working in a nice way but I have problems with the last step. I want to have it more dynamic. Therefore I want that the output is always random calculated and not hardcoded.

In this example I have 3 input variables and currently I only can output the same image in the loop row.

After every 3 products the custom image content should be displayed but not always the same. I try now to have it dynamic. Means, for every output select a random input. How can I do something like that?

// 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 input options
    $input1 = '<img src="/wp-content/uploads/2022/01/banner-test-01.svg">' ;
    
    $input2 = '<img src="/wp-content/uploads/2022/01/banner-test-02.svg">' ;
    
    $input3 = '<img src="/wp-content/uploads/2022/01/banner-test-03.svg">' ;

    // Column count
    $columns = esc_attr( wc_get_loop_prop( 'columns' ) );
    
    // Add content every X product
    if ( (  $wp_query->current_post % 3 ) ==  0 && $wp_query->current_post !=  0 ) {

       // output random input
       echo $input1 ;
    }

}

I know, that I have to use an array for this. But i tried everything with the information from here Get random item from array but it does not work with the html echo output.

$input = array("$input1 = '<img src="/wp-content/uploads/2022/01/banner-test-01.svg">'", "$input2 = '<img src="/wp-content/uploads/2022/01/banner-test-02.svg">'", "$input3 = '<img src="/wp-content/uploads/2022/01/banner-test-03.svg">'");

  $rand_keys = array_rand($input, 2);
  echo $input[$rand_keys[0]] . "\n";
  echo $input[$rand_keys[1]] . "\n";

Author:Nik7,eproduced under the CC 4.0 BY-SA copyright license with a link to the original source and this disclaimer.
Link to original article:https://stackoverflow.com/questions/72175829/display-random-custom-content-in-woocommerce-shop-archive-loop
yy