使用ACF分类标准字段作为Wordpress自定义帖子类型循环中的变量

问题描述 投票:0回答:1

我正在尝试使用高级自定义字段字段作为循环中的变量来创建自定义Wordpress查询。

用例是页面上有一个自定义循环。例如,有关场所的页面在页面底部显示事件循环(自定义帖子类型)。我想让创建页面的人选择他们想要附加到页面的事件标签(CPT上的标签分类法)。然后循环运行,并将该字段附加到用作变量的标签查询上。

到目前为止是我的代码:

            <?php if ( get_field('event_tag') ) : ?>

            <?php 
                $event_tag = get_field('event_tag');
                $args = array(
                    'post_type' => 'events',
                    'posts_per_page' => 3,
                    'tag_id' => $event_tag,
                    'meta_key' => 'event_start_date',
                    'orderby' => 'meta_value',
                    'order' => 'ASC',
                    'ignore_sticky_posts' => true
                );
            ?>
            <?php echo $event_tag; ?><!-- This is only here to check the variable -->

        <?php else : ?>

            <?php 
                $args = array(
                    'post_type' => 'events',
                    'posts_per_page' => 3,
                    'meta_key' => 'event_start_date',
                    'orderby' => 'meta_value',
                    'order' => 'ASC',
                    'ignore_sticky_posts' => true
                );
            ?>

        <?php endif; ?>

            <?php $secondquery = new WP_Query( $args ); 
                if ( $secondquery->have_posts() ) : while ( $secondquery->have_posts() ) : $secondquery->the_post(); ?>

我仍然想按事件日期排序,因此要按meta_key和orderby排序。我不确定这是否会影响这一点。需要注意的几件事:

•回显$ event_tag的临时行确实会输出标签ID(在本例中为31)。

•我尝试过将tag_id包裹在''中,并对其进行回显,等等。但是它什么也不显示。

•因为这是查询自定义帖子类型,所以我不确定标准标记是否有效。标签是这样注册的……如果有关系。

    // Taxonomy / Tags
function taxonomies_events_tags() {
  $args = array(
    'hierarchical'  => false, 
    'label'         => __( 'Event Tags','taxonomy general name'), 
    'singular_name' => __( 'Event Tag', 'taxonomy general name' ), 
    'rewrite'       => true, 
    'query_var'     => true,
    'show_in_rest' => true
  );
  register_taxonomy( 'custom-tag', 'events', $args );
}
add_action( 'init', 'taxonomies_events_tags', 0 );

我需要在查询中进行哪些更改以使指定标签中的事件得以显示,并且仍按event_start_date排序?

提前感谢。

wordpress wordpress-theming advanced-custom-fields custom-post-type custom-taxonomy
1个回答
0
投票

您需要使用税收查询来获取特定类别的事件。假设$ event_tag变量包含分类法术语的标签ID,则以下代码应该工作:

$args = array(
  'post_type' => 'events',
  'posts_per_page' => 3,
  'meta_key' => 'event_start_date',
  'orderby' => 'meta_value',
  'order' => 'ASC',
  'ignore_sticky_posts' => true,
  'tax_query' => array(
    array(
      'taxonomy' => 'custom-tag',
      'field'    => 'term_id',
      'terms'    => $event_tag
    )
  )
);
© www.soinside.com 2019 - 2024. All rights reserved.