Support

Account

Home Forums General Issues Loading posts based on Post object selection within a repeater field

Helping

Loading posts based on Post object selection within a repeater field

  • Hi I have two custom post types I am loading the page titles of the first post type into the second post type using repeater field and post object, the idea is you can select more than one post.

    What i’m trying to do is this.

    Post type 1 – load all posts from post type 2 where single post title(post type 1) is selected in post type 2.

    I know I should us a meta_query but I’m not sure how to go about this. Can anyone give some guidance.

    Thanks

  • Hi @energystar

    I would suggest that you change your field from a repeater with a post object field to a relationship field instead.

    That way you’ll get a single meta value containing a serialized array of post IDs and you can do the query you want using this:

    
    <?php
    global $post; // This will be your post_type1 post object.
    $args = array(
    	'post_type' => 'post_type2',
    	'posts_per_page' => 10000, // Should never be set to -1 as it's a risk not setting boundaries. Good code practise!
    	'no_found_rows' => true, //Disables the use of pagination BUT saves us an additional query. Remove if you need pagination
    	'update_post_term_cache' => false, //Does not update a potentially old cache of the queried posts term relationships BUT saves us an additional query. Remove if you're going to display term info
    	'meta_query' => array( //Query the serialized array. Putting the value in quotes makes sure we dont get a hit on 1234 when we search for 123. 
    		array(
    			'key' => 'relationship_fieldname',
    			'value' => '"' . $post->ID . '"',
    			'compare' => 'LIKE'
    		)
    	)
    );
    

    Doing the same thing with repeaters are a lot more complex and more expensive performance-wise.

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

The topic ‘Loading posts based on Post object selection within a repeater field’ is closed to new replies.