John Davidson

WordPress PHP Query for Custom Taxonomy

0 comments
Message:


I am using WP Facet to query a custom post type with a custom taxonomy. I can successfully display all the results from one custom taxonomy with the following query:


<?php
return [
"post_type" => [
"case-studies"
],
"post_status" => [
"publish"
],
"tax_query" => [
[
"taxonomy" => "case_study_type",
"field" => "slug",
"operator" => "IN",
"terms" => [
"private-coaching"
]
]
],
"posts_per_page" => 2
];

I can also display all the posts from either one taxonomy or another taxonomy using the or operator and the following code:


<?php
return [
"post_type" => [
"case-studies"
],
"post_status" => [
"publish"
],
"tax_query" => [
[
"taxonomy" => "case_study_type",
"field" => "slug",
"operator" => "IN",
"terms" => [
"private-coaching"
]
] ||
[
"taxonomy" => "case_study_type",
"field" => "slug",
"operator" => "IN",
"terms" => [
"behavior-therapy"
]
]
],
"posts_per_page" => 2
];

The problem I'm having is that I want to display the results by priority. So if there is only one post in the first category and 6 posts in the second category, then there is a set of 8 posts in the second query and I'm just getting the first two that satisfy the conditions. What I really want is the single one in the first category to show up first in the list, and then one from the second category to show next in the list.


Any help or pointing in the right direction would be greatly appreciated!!



My Answer:
php
$args = array(
'post_type' => 'your_custom_post_type',
'tax_query' => array(
array(
'taxonomy' => 'your_custom_taxonomy',
'field' => 'slug',
'terms' => 'your_custom_taxonomy_term',
),
),
);

$query = new WP_Query($args);

if ($query->have_posts()) {
while ($query->have_posts()) {
$query->the_post();
// Display your post content here
}
} else {
// No posts found
}

wp_reset_postdata();

Rate this post

4 of 5 based on 9135 votes

Comments




© 2024 Hayatsk.info - Personal Blogs Platform. All Rights Reserved.
Create blog  |  Privacy Policy  |  Terms & Conditions  |  Contact Us