要按两个自定义字段组合排序WordPress文章,你需要使用WP_Query
来创建自定义查询。假设你有两个自定义字段:custom_field_1
和custom_field_2
,你可以按以下方式组合它们进行排序:
$args = array( 'post_type' => 'post', // 文章类型,可以根据你的需要修改 'posts_per_page' => 1, // 获取所有符合条件的文章 'meta_key' => 'custom_field_1', 'meta_query' => array( 'relation' => 'AND', // 使用AND关系来组合两个自定义字段的条件 array( 'key' => 'custom_field_1', 'compare' => 'EXISTS', // 确保该字段存在 ), array( 'key' => 'custom_field_2', 'compare' => 'EXISTS', // 确保该字段存在 ), ), 'orderby' => array( 'custom_field_1' => 'ASC', // 第一个字段按升序排序 'custom_field_2' => 'ASC', // 第二个字段按升序排序 ), ); $custom_query = new WP_Query($args); if ($custom_query>have_posts()) : while ($custom_query>have_posts()) : $custom_query>the_post(); // 在这里输出文章内容 the_title(); // 其他内容 endwhile; wp_reset_postdata(); else : // 没有符合条件的文章 endif;
这个示例中,我们首先创建了一个WP_Query
的实例,然后设置了文章类型、希望获取的文章数量、自定义字段等参数。在meta_query
中,我们使用AND
关系来确保两个自定义字段都存在。最后,在orderby
中,我们指定了两个字段和它们的排序顺序。
你可以根据需要修改post_type
、posts_per_page
和自定义字段的名称。这个示例假设你希望按两个字段升序排序,如果你想按降序排序,只需将'ASC'
改为'DESC'
。