Support

Account

Home Forums Backend Issues (wp-admin) Post Object at random

Solving

Post Object at random

  • We have added an advanced custom fields block to load a post object on the home page with the latest custom post type post. This setup allows us to choose a post to display.

    "fields": [
      {
          "key": "field_xxxxxx",
          "label": "Label",
          "name": "motd",
          "type": "post_object",
          "instructions": "",
          "required": 0,
          "conditional_logic": 0,
          "wrapper": {
              "width": "",
              "class": "",
              "id": ""
          },
          "post_type": [
              "label"
          ],
          "taxonomy": "",
          "allow_null": 1,
          "multiple": 0,
          "return_format": "object",
          "ui": 1
      }

    What we would like to have is the option to load on of the latest x posts at random.

    I looked at https://support.advancedcustomfields.com/forums/topic/using-acf-to-create-randomized-ad-block/ and array_rand seems to be useful to load at random from an array of posts.

    But how would we do that with the post object choice?

  • Your post object field only allows 1 selection. There wouldn’t be anything to use array_rand() on. Your post object field would need to allow multiple values which would return an array of post objects instead on just 1.

  • I guess I can better use a repeater field as well then. One to basically load post slides using array_rand() I do not need a radio select box like in the example.

    I would need to use a loop and load a post at random. A basic repeater field example in the ACF Repeater Field tutorial shows how to load a sub field value from a random row of a Repeater field:

    <?php
    $rows = get_field('repeater_field_name' );
    if( $rows ) {
        $index = array_rand( $rows );
        $rand_row = $rows[ $index ];
        $rand_row_title = $rand_row['title'];
        // Do something...
    }

    This loop is close to what I need, but I would need to “just” load a random post from a taxonomy from the last 3-4 months.

    Perhaps I just need an ACF block, in it do a new WP_Query to load custom post type at random from a date range. Will need to think about this more.

  • @hube2 I got somewhat further:

    <?php
    
    $motd = get_field('motd');
    
    ?>
    
    <div id="<?php echo esc_attr($id); ?>" class="<?php echo esc_attr($className); ?>">
    
    <?php
    $molecule_month = get_the_terms($motd->ID , 'molecules_of_the_month' );
    $month = array_pop($molecule_month);
    $molecule_link = get_term_link( $month->term_id, 'molecules_of_the_month' );
    
    // Set the post type here, and sort them randomly
    // molecule of the month presented as random molecule of the day.
    $args = array(
        'post_type' => 'molecule',
        'posts_per_page'=> 1, 
    		'post_category' => 'molecule_of_the_month',
        'order_by' => 'rand',
    );
    // Initiate a custom query
    	
    $cpt_query = new WP_Query($args);
    	
    // If the query has any post, start the loop
    if($cpt_query->have_posts()){
        while($cpt_query->have_posts()){
            // Output a link and a thumbnail of the post
            $cpt_query->the_post(); ?>
            <div class="random-post">
    					<div class="motd-img">
    						<a href="<?php echo $molecule_link ?>">
    								<?php echo get_the_post_thumbnail( $motd->ID, 'full');?>"/>
    						</a>
    					</div>
                <a href="<?php the_permalink();?>"><?php the_title();?></a>
            </div><?php
        }
    } ?>
    
    </div>

    But got this error

    : Uncaught TypeError: array_pop(): Argument #1 ($array) must be of type array, bool given in /Users/jasper/code/site/wp-content/themes/theme/blocks/random-molecule/block.php:30

    Why would ID be null? It refers to $month = array_pop($molecule_month); and the field has been set before that line. And we do have molecules of the day(based on month) and molecules of the month.

  • I think I cannot call $motd cause it is an ACF block with a post object and another ACF block at that. An existing one where you can select a post. I am working on loading a random one… Might need to create another ACF Block Field Group.

  • Sorry, don’t know anything to help with the second question.

    As for the first

    
    $molecule_month = get_the_terms($motd->ID , 'molecules_of_the_month' );
    

    You need to check the returned value to make sure that it is not empty, that it is not a WP error and that it is an array.

  • Seems the variable motd does not load anything so second check fails as well.

    <?php
    // new acf block field to be added
    $motd = get_field('motd');
    var_dump($motd); // NULL
    $molecule_month = get_the_terms($motd->ID , 'molecules_of_the_month' ); 
    var_dump($molecule_month); // warning trying to read property ID on NULL

    so results show

    NULL
    Warning: Attempt to read property “ID” on null in /Users/jasper/code/site/wp-content/themes/theme/blocks/random-molecule/block.php on line 24
    bool(false)

    And that gets me back to issue with ACF block. I have the base on just loading a molecule on selection and a new one

    <?php
    acf_register_block_type( array(
      'name'			=> 'molecule-of-the-day',
      'title'			=> __( 'Molecule of the day', 'theme' ),
      'render_template'	=> 'blocks/molecule-of-the-day/block.php',
      'category'		=> 'theme',
      'icon'			=> 'image-filter',
      'mode'			=> 'auto',
      'keywords'		=> array( 'molecule' )
      ));
      acf_register_block_type( array(
      'name'			=> 'random-molecule',
      'title'			=> __( 'Random Molecule', 'theme' ),
      'render_template'	=> 'blocks/random-molecule/block.php',
      'category'		=> 'theme',
      'icon'			=> 'image-filter',
      'mode'			=> 'auto',
      'keywords'		=> array( 'molecule' )
      ));

    In the first block $motd = get_field('motd'); works just fine. In my new one under construction it does not. Why is that? Am I doing something now I should not or that is not possible? Just do not understand this.

  • Needed to add another location for ACF Block. Loads now. Just still need to select post from selectbox. Need to have one loaded at random instead. Will check some more.

  • As I stated I now have an option to pick a molecule of the day. But I want one at random to load. In ACF we have a motd block with Field Type post object. This seems to create a setup where you can choose an item from the existing ones for the post object or search for one.

    How can we load a post at random using an ACF Block from the editor with a Gutenberg Block?

    current code:

    <?php
    // ACF updated to work with new block
    $motd = get_field('motd');
    var_dump($motd); // NULL
    $molecule_month = get_the_terms($motd->ID , 'molecules_of_the_month' ); 
    var_dump($molecule_month); // warning trying to read property ID on NULL
    
    ?>
    
    <div id="<?php echo esc_attr($id); ?>" class="<?php echo esc_attr($className); ?>">
    
    <?php
    // $molecule_month = get_the_terms($motd->ID , 'molecules_of_the_month' );
    // $month = array_pop($molecule_month);
    // $molecule_link = get_term_link( $month->term_id, 'molecules_of_the_month' );
    
    // Set the post type here, and sort them randomly
    // molecule of the month presented as random molecule of the day.
    $args = array(
        'post_type' => 'molecule',
        'posts_per_page'=> 1, 
    		'post_category' => 'molecule_of_the_month',
        'order_by' => 'rand',
    );
    // Initiate a custom query
    	
    $cpt_query = new WP_Query($args);
    	
    // If the query has any post, start the loop
    if($cpt_query->have_posts()){
        while($cpt_query->have_posts()){
            // Output a link and a thumbnail of the post
            $cpt_query->the_post(); ?>
            <div class="random-post">
    					<div class="motd-img">
    						<a href="<?php echo $molecule_link ?>">
    								<?php echo get_the_post_thumbnail( 'full');?>"/>
    						</a>
    					</div>
    					<div class="motd-content">
    						<h2 class="is-style-highlight">Molecule of the day</h2>
    						<h3 class="motd-name">
    							<a href="<?php // echo $molecule_link ?>">
    							<?php // echo esc_html( $title ); ?><?php // if($month){ ?> - <?php //echo $month->name; } ?>
    							</a>
    						</h3>
    						<a href="<?php the_permalink();?>"><?php the_title();?></a>
    					</div>
            </div>
    				<?php
        }
    } ?>
  • Might just need to use a shortcode to be added to a block

    <?php
    function imwz_rand_posts() { 
     
    $args = array(
        'post_type' => 'molecule',
        'orderby'   => 'rand',
        'posts_per_page' => 1, 
        );
     
    $the_query = new WP_Query( $args );
     
    if ( $the_query->have_posts() ) {
     
    $string .= '<ul>';
        while ( $the_query->have_posts() ) {
            $the_query->the_post();
            $string .= '<li><a href="'. get_permalink() .'">'. get_the_title() .'</a></li>';
        }
        $string .= '</ul>';
        /* Restore original Post Data */
        wp_reset_postdata();
    } else {
     
    $string .= 'no posts found';
    }
     
    return $string; 
    } 
     
    add_shortcode('imwz-random-posts','imwz_rand_posts');
    add_filter('widget_text', 'do_shortcode');

    See https://www.wpbeginner.com/wp-tutorials/how-to-display-random-posts-in-wordpress/

  • Only using

    <php?
    function imwz_rand_posts() { 
     
    $args = array(
        'post_type' => 'molecule',
        'orderby'   => 'rand',
        'posts_per_page' => 1, 
        );
     
    $the_query = new WP_Query( $args );
    $string = ''; 
    if ( $the_query->have_posts() ) {
    
    $string .= '<div>';
        while ( $the_query->have_posts() ) {
            $the_query->the_post();
            $string .= '<h3><a href="'. get_permalink() .'">'. get_the_title() .'</a></h3>';
    				$string .= '<p>' . the_excerpt() . '</p>';
        }
        $string .= '</div>';
        /* Restore original Post Data */
        wp_reset_postdata();
    } else {
     
    $string .= 'no posts found';
    }
     
    return $string; 
    } 
    
    // [imwz-random-posts] shortcode
    add_shortcode('imwz-random-posts','imwz_rand_posts');
    add_filter('widget_text', 'do_shortcode');

    the paragraph part loads above all other data/blocks and not below the title inside the same shortcode block. Any ideas why?

Viewing 12 posts - 1 through 12 (of 12 total)

You must be logged in to reply to this topic.

We use cookies to offer you a better browsing experience, analyze site traffic and personalize content. Read about how we use cookies and how you can control them in our Cookie Policy. If you continue to use this site, you consent to our use of cookies.