So based on our discussion, the meta named opposition
(for match
posts) has its value set to the slug of the corresponding club
post; e.g. club-1
, club-two
, etc., right?
If so, then you first get the ID of the club
post using a custom query (see in the code below) and then you can access any data you want from the club
post such as the post title and content. Just make sure to always check if the post ID (identified by $club_id
in the code below) is greater than 0
(zero), because otherwise the data you get would be for the current post in the foreach
loop, which is for the current match
post and not the club
post associated with that match
post. (I hope you can understand this..)
if ( $latestresult )
{
foreach ( $latestresult as $post )
{
setup_postdata( $post );
// Get the ID of the `club` post associated with the current `match` post.
$club_id = $wpdb->get_var( $wpdb->prepare( "
SELECT ID
FROM $wpdb->posts
WHERE post_name = %s
AND post_type="club"
", get_field( 'opposition', $post->ID ) ) );
// Don't use `get_the_title()` with a zero value; so check if $club_id > 0
$player_name = $club_id > 0 ? get_the_title( $club_id ) : 'N/A';
?>
...
<div class="result-info">
<a href="https://wordpress.stackexchange.com/questions/309811/<?php the_permalink(); ?>">
...
<span class="result-column"><?php echo $player_name; ?></span>
...
<span class="thumbnail">
<?php echo get_the_post_thumbnail( $club_id, 'thumbnail' ); ?>
</span>
</a>
</div>
<?php
}
}
However, if possible, you should probably better change the ACF field type to Post Object, where the meta value would be the ID of the club
post and not its slug. But for that, make sure to set the “Allow Null” to “Yes”, and “Select multiple values” to “No” — see this image.
And if you can do that, then the code would be simpler:
if ( $latestresult )
{
foreach ( $latestresult as $post )
{
setup_postdata( $post );
// Get the ID of the `club` post associated with the current `match` post.
// Set the third argument to `false` to get the post ID instead of object.
$club_id = get_field( 'opposition', $post->ID, false );
// Don't use `get_the_title()` with a zero value; so check if $club_id > 0
$player_name = $club_id > 0 ? get_the_title( $club_id ) : 'N/A';
?>
...
<div class="result-info">
<a href="https://wordpress.stackexchange.com/questions/309811/<?php the_permalink(); ?>">
...
<span class="result-column"><?php echo $player_name; ?></span>
...
<span class="thumbnail">
<?php echo get_the_post_thumbnail( $club_id, 'thumbnail' ); ?>
</span>
</a>
</div>
<?php
}
}
Additional Note
Although this code works:
$latestresult = $wpdb->get_results(
"SELECT * FROM $wpdb->wp_posts
WHERE p.post_type="match"
ORDER BY post_date DESC
LIMIT 2"
);
I did it using get_posts()
:
$latestresult = get_posts( [
'post_type' => 'match',
'orderby' => 'date',
'order' => 'DESC',
'posts_per_page' => 2, // LIMIT
] );
Because that’s how we’re supposed to do it in WordPress. =) (The other way would be using new WP_Query( [ ... ] )
.)