Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save tdrayson/0b915b4d89615ca663f2bd1f03e0f364 to your computer and use it in GitHub Desktop.
Save tdrayson/0b915b4d89615ca663f2bd1f03e0f364 to your computer and use it in GitHub Desktop.
/*
* Add post object field on the CPT you want to display
* In the post object field select the CPT post you want this post to show on
*
* Example:
* 2 CPT's - Tours and Reviews
*
* To show reviews on the relevant tours:
* - Add the post object field to the reviews CPT
* - Select the tours that I want the reviews to show on inside the Review post
* - Add the before and after code in codeblocks before and after the repeater
* - On the repeater use custom query and set post type and number of posts per page as you wish)
*/
//Before Repeater Code
<?php
function dynamic_category_query( $query ) {
if ( $query->query['post_type'][0] == 'CPT_SLUG' ) {
$query->set( 'meta_query', array(
array(
'key' => 'FIELD_NAME', //name of custom field
'value' => '"' . get_the_ID() . '"',
'compare' => 'LIKE'
)
) );
$query->set( 'orderby', 'rand' );
$query->set( 'no_found_rows', true );
}
}
add_action( 'pre_get_posts', 'dynamic_category_query' );
?>
/*
* REPEATER (use custom query and set post type and number of posts per page as you wish)
*/
/* Put this in a code block just AFTER the repeater if you need to make other queries later on the page */
<?php
remove_action( 'pre_get_posts', 'dynamic_category_query' );
?>
@craigrileyuk
Copy link

I've been trying for ages to get something like this to work and your example finally cracked it.

Any idea why using 'compare' => 'LIKE' works and, as I had been doing, using 'compare' => '=' doesn't?

Also, would it return a false positive if the get_the_ID() returned 51, but you also had a post with an ID of 151?

@Jimmyg128
Copy link

Hi, I'm not a programmer so I may be uterly wrong.

On a video about acf relationship the creator told to use '"' . . '"' eg: 'value' => '"' . get_the_ID() . '"', So that it won't select postID 123 by mistake if you query postID 12.

im also french so maybe I didn't understood at all lol.

thank you very much tdrayson for this code

@alexsoluweb
Copy link

alexsoluweb commented Jan 30, 2022

Hey guys, any tips would be appreciate on this please.

When using pre_get_posts action hook inside oxygen repeater (any custom query):

when updating $query->set('something', 'value'), it does not update his object property $this->found_posts.

This is a really strange behavior....or i missing something ...

  function my_pre_get_post($query){
    ...
    $query->set('somefilter', 'value');
    $query->found_posts // 0 why is that? There is post showing up on the front end
    ...
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment