Support

Account

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

  • 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/