0

我为 CPT 事件添加了两个自定义字段:日 (event_day) 和月 (event_month)(均为收音机类型)。现在我希望能够按 meta_key 日期和月份获取帖子。

除了带有 $meta_query 的部分外,短代码有效。

这里是岸码的样子:[tribe_custom_events_list_mm_wed cat="Rodrigo" num="6" day="Monday" month="October"]

Bellow是负责短代码的代码,添加在functions.php中

function tribe_custom_events_shortcode($atts, $content = null)
{

  global $post;

  extract(shortcode_atts(array(
    'cat'     => '',
    'num'     => '',
    'order'   => 'ASC',
    'orderby' => 'post_date',
    'taxonomy' => 'tribe_events_cat',
    'field'   => 'name',
    'day'   => '',
    'month' => '',
  ), $atts));

  $tax_query = array(
      'taxonomy' => $taxonomy,
      'field'    => $field,
      'terms'    => $cat,
  );

  $day = $day;
  $month = $month;

  $meta_query = array(
    array(
      'key'   => 'event_day',
      'value' => '$day',
      'compare' => '='
    ),
    array(
      'key'   => 'event_month',
      'value' => '$month',
      'compare' => '='
    ),
  );

  $args = array(
    'post_type'      => 'tribe_events',
    'posts_per_page' => $num,
    'order'          => $order,
    'orderby'        => $orderby,
    'tax_query' => array($tax_query),
    'meta_query' => array($meta_query),
  );

  $output = '';

  $posts = get_posts($args);

  foreach ($posts as $post) {

    setup_postdata($post);

    $output .= '<div class="tribe-mini-calendar-event event-0  first  last">';
    $output .= '<h4 class="tribe-events-title"><a href="' . get_the_permalink() . '">' . get_the_title() . '</a></h4>';
    $output .= '</div>';
  }

  echo '<pre>' , var_dump($meta_query) , '</pre>';

  wp_reset_postdata();

  return '<div>' . $output  . '</br>' . '</div>';
}
add_shortcode('tribe_custom_events_list_mm_wed', 'tribe_custom_events_shortcode');

4

1 回答 1

2

这应该适合你。您的代码中有一些错误......在下面的评论中注明。

$tax_query = array(
    'taxonomy' => $taxonomy,
    'field'    => $field,
    'terms'    => $cat,
);

/* This is unnecessary since $day already = $day
  $day = $day;
  $month = $month;
*/

$meta_query = array(
    array(
        'key'   => 'event_day',
        'value' => $day, // Don't put quotes around variables
        'compare' => '='
    ),
    array(
        'key'   => 'event_month',
        'value' => $month,
        'compare' => '='
    ),
);

$args = array(
    'post_type'      => 'tribe_events',
    'posts_per_page' => $num,
    'order'          => $order,
    'orderby'        => $orderby,
    'tax_query' => $tax_query, // This is already an array defined above
    'meta_query' => $meta_query,
);
于 2021-10-16T20:13:11.400 回答