Skip to content

Instantly share code, notes, and snippets.

@askwpgirl
Last active January 29, 2021 03:13
Show Gist options
  • Save askwpgirl/618f982d4a91f99f74f3be1c53f49f34 to your computer and use it in GitHub Desktop.
Save askwpgirl/618f982d4a91f99f74f3be1c53f49f34 to your computer and use it in GitHub Desktop.
ACF Query for Posts with Specific Relational Field
<?php
/*
* Query posts for a relationship value.
* This method uses the meta_query LIKE to match the string "123" to the database value a:1:{i:0;s:3:"123";} (serialized array)
*/
$args = array(
'post_type' => 'doctor',
'posts_per_page' => 10,
'meta_query' => array(
array(
'key' => 'locations_serviced', // name of relational field
'value' => '253347', // matches exaclty "123", not just 123. This prevents a match for "12345". This is the ID of the Related Post.
'compare' => 'LIKE'
)
)
);
$loop = new WP_Query($args);
while ( $loop->have_posts() ) {
$loop->the_post();
?>
<div class="entry-content">
<?php the_title(); ?>
<?php the_content(); ?>
</div>
<?php
}
@askwpgirl
Copy link
Author

askwpgirl commented Jan 29, 2021

You can put this code on a page template or throw into a function and call the function on your page template. Or call via a shortcode:

function denver_docs_shortcode($atts) {
	
	$atts = doctor_query_denver();
 	return $atts;
}

add_shortcode( 'denverdocs', 'denver_docs_shortcode' );

Then add [denverdocs] to your page or post you want the results to show on, though I am getting a Gutenberg JSON notice when I use this shortcode.

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