因此,根据我们的讨论,元命名为opposition
(用于match
将其值设置为相应club
邮递e、 g。club-1
, club-two
, 等等,对吧?
如果是,那么您首先获得club
使用自定义查询发布(请参见下面的代码),然后您可以从club
帖子,如帖子标题和内容。只需确保始终检查post ID(由$club_id
在下面的代码中)大于0
(零),因为否则您得到的数据将是foreach
回路,用于当前match
发布而不是club
与之关联的帖子match
邮递(我希望你能理解这一点。)
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="<?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
}
}
但是,如果可能,您最好将ACF字段类型更改为
Post Object, 其中,元值是
club
而不是它的鼻涕虫。但为此,请确保将“允许Null”设置为“是”,并将“选择多个值”设置为“否”&mdash;看见
this image.
如果你能做到这一点,那么代码将是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="<?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
}
}
附加说明尽管此代码有效:
$latestresult = $wpdb->get_results(
"SELECT * FROM $wpdb->wp_posts
WHERE p.post_type = \'match\'
ORDER BY post_date DESC
LIMIT 2"
);
我是用
get_posts()
:
$latestresult = get_posts( [
\'post_type\' => \'match\',
\'orderby\' => \'date\',
\'order\' => \'DESC\',
\'posts_per_page\' => 2, // LIMIT
] );
因为在WordPress中,我们应该这样做(另一种方法是使用
new WP_Query( [ ... ] )
.)