使用自定义(ACF)字段创建自定义查询以在Wordpress中显示关系数据

时间:2018-09-19 16:41:26

标签: php wordpress

我正在尝试使用自定义(ACF)字段创建自定义查询,以在Wordpress中显示关系数据。我什么也没显示。我也没有任何错误。

我有两种自定义帖子类型,“城镇”和“事件”

“事件”帖子类型具有一个名为“镇”的自定义关系字段(使用ACF),可以在其中将事件与特定镇相关联。

在用于显示城镇的页面(single-town.php)上,我试图显示该城镇中发生的所有事件。

<?php
 get_header();
 ?>
 <br>

 /* display the current town, title, feature image, and description */
<?php
 while (have_posts()){
  the_post();
  $title = get_the_title(); /* use this var in custom query below */
  ?><h2><?php echo $title ?> </H2>
  <hr><?php
  the_post_thumbnail('large');
  the_content();
  }?>
  <br>
  <?php 

 /*create a custom query to fetch all the events for that town */
 $posts = get_posts(array(
  'paged'=> get_query_var('paged',25),
  'posts_per_page' => 25,
  'post_type' => 'event',
  'orderby'=> 'title',
  'order'=> 'ASC',
  'meta_key'=> 'town',
  'meta_query'=> array(
         array(
      'key'=> 'town',
      'compare'=> '=',
      'value'=> $title
  ));
));

 /* display custom query results */

if( $posts ): ?>
    <ul>
    <?php foreach( $posts as $post ):
        setup_postdata( $post );
        ?>
        <li>
            <a href="<?php the_permalink(); ?>"><?php the_title(); ?></a>
        </li>
    <?php endforeach; ?>
    </ul>
    <?php wp_reset_postdata(); ?>
<?php endif; 

 wp_reset_postdata();
 get_footer();
?>

我也尝试使用:

 $eventQuery = new WP_Query(array(
 'paged'=> get_query_var('paged',25),
 'posts_per_page' => 25,
 'post_type' => 'event',
 'orderby'=> 'title',
 'order'=> 'ASC',

 'meta_key'=> 'town',
 'meta_query'=> array(
        array(
     'key'=> 'town',
     'compare'=> '=',
     'value'=> $title
))
));

while ($eventQuery->have_posts()){
$eventQuery->the_post();
$eventQuery->the_title();
}

1 个答案:

答案 0 :(得分:1)

“关系”字段将数据保存为ID数组,但不保存帖子标题。因此,尽管您的第二个示例使用WP_Query更近了,但它找不到任何匹配项,因为您将值与当前帖子的标题进行了比较。与ID进行比较:

$eventQuery = new WP_Query( array(
    'posts_per_page' => 25,
    'post_type'      => 'event',
    'orderby'        => 'title',
    'order'          => 'ASC',
    'meta_query'     => array(
        array(
            'key'     => 'town', 
            'value'   => '"' . get_the_ID() . '"',
            'compare' => 'LIKE'
        )
    ),
));