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.
Hi @matteo Balocco
A quick google gave me this thread:
The relationship field will return an array of posts right? So, you can treat it much the same as in that above example.
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();
if( $random_post ):
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…
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:
Just test your code line by line. Print out vars and debug the data.
Thank you Elliot for your precious tips!
You must be logged in to reply to this topic.
Welcome to the Advanced Custom Fields community forum.
Browse through ideas, snippets of code, questions and answers between fellow ACF users
Helping others is a great way to earn karma, gain badges and help ACF development!
#CodeTidbits30 Day 28 🎄— Samantha Ming (@samantha_ming) December 28, 2019
One thing that doesn't get talk often is Flexbox with Auto Margins. Although not a Flexbox property, it can be used to align child elements. Which is great for creating layouts 💯#Codenewbie #100DaysOfCode #301DaysOfCode pic.twitter.com/PmRYyBSTjr
© 2020 Advanced Custom Fields. Subscribe