Support

Account

Home Forums General Issues Get a random item from a relationship field

Solved

Get a random item from a relationship field

  • Hi,
    I read the documentation but I cannot figure how to query a single random item from a relationship field.

    I’m using the relationship field to show related posts to certain pages.
    I want to set some related posts for each page, but I want to extract just one of them at time, randomly…

    Is it possible?

    Thank you in advance for your help.

    Matteo

    • Elliot

    • October 30, 2013 at 4:53 pm

    Hi @matteo Balocco

    A quick google gave me this thread:
    http://stackoverflow.com/questions/4241300/simple-php-random-array

    The relationship field will return an array of posts right? So, you can treat it much the same as in that above example.

    Thanks
    E

  • Thank you Elliot!
    Actually I tried that before opening this topic. When I try to access and echo a random page by declaring its index I get:

    Catchable fatal error: Object of class WP_Post could not be converted to string in...

    As you may guess I’m more a front-end guy than a php one…

  • And if I try to reduce the array to one element only, I get an error and, at the bottom I don’t get the right related post but another one, outside the original related group.


    $posts = get_field('related_content');
    $random_post = array();
    array_push($random_post,$posts[array_rand($posts)]);
    if( $random_post ):
    setup_postdata($random_post);
    the_title();
    endif;

    returns a bunch of:

    Notice: Trying to get property of non-object in /Users/totanus/Sites/ovestsesia/wordpress/wp-includes/query.php on line...

    And then prints an incorrect the_title();

    I’m missing something, of course…

    Teo

    • Elliot

    • October 31, 2013 at 9:56 am

    Hi @matteo Balocco

    Your above code shows some mixed directions and doesn’t make too much sense looking at it.

    The best thing you can do is simplify the task into steps.

    Firstly, just get a random $post from the $posts array. Please read the above link I posted to find out how to do this.

    Once you have the random $post, you can then echo it’s title like this:

    
    echo get_the_title($post->ID)
    

    Just test your code line by line. Print out vars and debug the data.

    Good luck

    Thanks
    E

  • Thank you Elliot for your precious tips!

Viewing 6 posts - 1 through 6 (of 6 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.