【问题标题】:PHP: sort multi-dimensional array based on key for AJAX with WP_QueryPHP:使用 WP_Query 根据 AJAX 的键对多维数组进行排序
【发布时间】:2016-09-28 00:55:04
【问题描述】:

我有一个 WP_Query,用于通过 AJAX 进行自定义帖子类型过滤器。每个帖子类型都有一个自定义帖子分类(类别),但只有一个。在过滤过程中,我希望结果基于类别的名称,然后基于产品的名称,但我还没有找到正确的文档来使用这些类型的方法,如 usortksort数组。

这是我的 PHP:

$args = array(
    'posts_per_page'    => -1,
    'post_type'             => 'product',
    'orderby'                   => 'title',
    'order'                     => 'ASC',
    'tax_query' => array(
        array(
            'taxonomy'  => 'products_tag',
            'field'         => 'slug',
            'terms'         => $taxonomy,
            'operator'  => 'AND',
        ),
    ),
);

$filter_query = new WP_Query($args);
$num_posts = $filter_query->found_posts;

if( $filter_query->have_posts() ):

    while( $filter_query->have_posts() ) : $filter_query->the_post();

        $titles[] = get_the_title();
        $ids[] = get_the_ID();
        $product_categories = get_the_terms( get_the_ID(), 'products_category' );
        $product_category = array_pop( $product_categories );
        $categories[] = $product_category->name;
        $permalinks[] = get_permalink();
        $image_field = get_field('images');
        $images[] = $image_field[0]['url'];
        $descriptions[] = get_field('short-description');

    endwhile;

endif;

wp_reset_postdata();

$response = array(
    'success' => true,
    'titles' => $titles,
    'ids' => $ids,
    'categories' => $categories,
    'permalinks' => $permalinks,
    'images' => $images,
    'descriptions' => $descriptions,
    'taxonomy' => $taxonomy,
    'num_posts' => $num_posts
);

所以在声明$results 变量之前,我希望所有数组都以一种简单的方式跟随$categories 数组,但没有方法如何。我可能完全误解了文档,但我没有看到我的案例出现在 php.net 手册中。

【问题讨论】:

  • 但只有一个什么?期限?
  • @RutwickGangurde 是的。
  • @RutwickGangurde 谢谢,但根据我的解释,这对于自定义分类法是不可行的。编辑:我会被诅咒的,我错了。它奏效了!谢谢!
  • 太棒了!我会将其添加为答案,以便您接受。

标签: php arrays ajax wordpress sorting


【解决方案1】:

这应该可以,虽然我还没有尝试过。

$query = new WP_Query( array( 'post_type' => 'page', 'orderby' => 'title menu_order', 'order' => 'ASC' ) );

注意 orderby 有 2 个由空格分隔的参数。

关注此主题以获取更多信息:How to order by two different things at once in a query in WordPress

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-04-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-04-27
    相关资源
    最近更新 更多