Hi, I’ve a simple relationship field with 2 post type as filter (see image of link)-Struttura and Pagina
When I want to get all selected post use this code:
$posts = get_field( 'relazioni_strutture' , );
if ( $posts ) : ?>
<?php foreach( $posts as $post) : ?>
<?php setup_postdata( $post ); ?>
<?php the_title(); ?>
<?php endforeach; ?>
<?php wp_reset_postdata(); ?>
<?php endif; ?>
but if a want to get a specific post type? Only post of Struttura?
Thanks
IMAGE: https://drive.google.com/file/d/1W6JHlgwdviISfYtWB99KDO8t5F_3Rh2E/view?usp=sharing
Hi @toniup
Within your loop, you could use the get_post_type() to see which post type is the post is.
You could then add a conditional. Something like:
<?php
$posts = get_field( 'relazioni_strutture' );
if ( $posts ) : ?>
<?php foreach( $posts as $post) : ?>
<?php setup_postdata( $post ); ?>
<?php $post_type = get_post_type();
if( $post_type == 'Struttura' ):
?>
<?php the_title(); ?>
<?php endif; #$post_type ?>
<?php endforeach; ?>
<?php wp_reset_postdata(); ?>
<?php endif; ?>
May need tweaking but should get you underway
The answer by @jarvis is a good solution. There is another option that is slightly more complicated. You can use an acf/fields/relationship/query filter.
Somewhere in your functions.php file add
function acf_relationship_only_struttura($args) {
$args['post_type'] = 'struttura';
return $args;
}
Then just in your template where you want to show the field
add_filter('acf/fields/relationship/query/name=relazioni_strutture', 'acf_relationship_only_struttura');
$posts = get_field('relazioni_strutture');
remove_filter('acf/fields/relationship/query/name=relazioni_strutture', 'acf_relationship_only_struttura');
Thank you jarvis and John Huebner,
in my case I prefer the jarvis’s solution because directly in template file I can apply the both query quickly!
https://drive.google.com/file/d/1nQlxM8UZVU3uGwjZlRFlqnwmZoAUO4oC/view?usp=sharing