【问题标题】:Run wp_query based on IDs found in array根据数组中找到的 ID 运行 wp_query
【发布时间】:2021-05-13 13:03:34
【问题描述】:

我有一个会话数组 ($_SESSION['recently_viewed']),它当前输出以下内容:

array(3) { [0]=> int(635) [1]=> int(643) [2]=> int(474) }

635643474 是我的自定义帖子类型中的 IDs,称为 accessories

我正在尝试显示属于该数组的帖子,但不确定如何在逻辑上执行此操作。

到目前为止我有:

<?php
global $post;

$args = array(
  'post_type' => 'accessories',
  'p' => $_SESSION['recently_viewed'], // something like this, but logically correct
  'post_status' => 'publish',
);

$query = new WP_Query( $args );

if($query->have_posts() ) :
  while ( $query->have_posts() ) : $query->the_post();
    echo the_title();
  endwhile; wp_reset_postdata(); ?>
<?php endif; ?>

我该怎么做?

【问题讨论】:

    标签: php arrays wordpress


    【解决方案1】:

    您可以在 WP_Query 的 post__in 参数中传入结果数组。

    $args = array(
      'post_type' => 'accessories',
      'post__in' => $_SESSION['recently_viewed'], 
      'post_status' => 'publish',
    );
    

    但您可能需要重组 $_SESSION['recently_viewed'] 并确保它是一个有效的数组。如果它已经有效,那么上面的查询应该没有问题。

    文档中的更多信息。

    //https://developer.wordpress.org/reference/classes/wp_query/#post-page-parameters

    【讨论】:

      猜你喜欢
      • 2015-12-01
      • 2021-01-13
      • 2015-09-16
      • 2022-06-21
      • 2016-09-28
      • 2022-01-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多