【问题标题】:Multiple Queries in Wordpress Custom PostWordPress 自定义帖子中的多个查询
【发布时间】:2019-10-14 16:00:30
【问题描述】:

我有 2 个 CPT:位置和人员。 在每个位置页面上,我都有一个部分显示在该位置工作的所有人员。

我希望它们按两个字段进行组织:

  • 员工组(标签为 #1-6 的单选按钮)
  • 姓氏

我以为我找到了按员工组组织它们的东西,但它似乎并不是在每个页面上都有效。

<?php
/**
 * The Template for displaying single posts.
 */
?>

                <?php while (have_posts()):
    the_post(); ?>

                <?php
    /*
     *  Query posts for a relationship value.
     *  This method uses the meta_query LIKE to match the string "123" to the database value a:1:{i:0;s:3:"123";} (serialized array)
    */
    $staff = get_posts(
        array(
            'post_type' => 'people', 
            'posts_per_page' => - 1, 
            'meta_query' => array(
                'relation' => 'AND', 

                'location_clause' => array(
                    'key' => 'location', // name of custom field
                    'value' => '"' . get_the_ID() . '"', // matches exactly "123", not just 123. This prevents a match for "1234"
                    'compare' => 'LIKE',
                    ), 

                'order_clause' => array(
                    'key' => 'staff_group', 
                    'compare' => 'EXISTS'
                    )
            ), 
            'orderby' => array(
                'location_clause' => 'ASC', 
                'order_clause' => 'ASC')
                )
            );
?>

我仍处于学习自定义 WP 的早期阶段,因此非常感谢任何帮助!

【问题讨论】:

    标签: php wordpress custom-wordpress-pages alphabetical


    【解决方案1】:

    有几点很突出:

    'posts_per_page' => - 1, 
    

    我认为 - 和 1 之间不应该有空格。

    另外,而不是:

    'location_clause' => array(
        'key' => 'location',
        'value' => '"' . get_the_ID() . '"',
        'compare' => 'LIKE',
        ),
    

    用以下方法简化这个查询:

    'location_clause' => array(
        'key' => 'location',
        'value' => get_the_ID(),
        ),
    

    默认的compare 是'='。

    最后,你真的不需要:

    'location_clause' => 'ASC',
    

    因为位置应该只有一个值,对吧?

    否则,查询看起来是正确的。所以让我们清理一下,看看我们得到了什么:)

    【讨论】:

    • 建议 #1 和 3 有所帮助,但 #2(关于简化)破坏了我的页面......也许我需要用于 ACF 关系字段的 ACF 关系字段,用于将人员分配到某个位置。不幸的是,我仍然无法按姓氏对每个类别进行排序。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-09-15
    • 1970-01-01
    • 2015-10-24
    相关资源
    最近更新 更多