I'm going to have a WP_Query run with arguments based on user input. The user can select multiple categories/terms and the query will filter based on the AND boolean.
// main arguments
$args = array(
'tax_query' => array(
'relation' => 'AND',
array(
'taxonomy' => 'industry',
'terms' => $user_input,
),
array(
'taxonomy' => 'format',
'terms' => $user_input2,
),
),
);
// less specific arguments
$lessargs = array(
'tax_query' => array(
array(
'taxonomy' => 'industry',
'terms' => $user_input,
),
),
);
If no results are returned in the first query, I want to run the second query with less specificity ($lessargs). I know I need to use if/else statements but I don't know the correct way to do this within the loop. Example:
<?php $the_query = new WP_Query( $args ); ?>
<?php if ($the_query->have_posts()) : ?>
<?php while ($the_query->have_posts()) : the_post(); ?>
// Return Query Results
<?php endwhile; ?>
<?php else : ?>
<?php $the_second_query = new WP_Query( $less_args ); ?>
<?php while ($the_second_query->have_posts()) : the_post(); ?>
// Return Second Query Results
<?php endwhile; ?>
<?php endif; ?>
Is this the proper way to conditionally call queries if the previous query returns empty?
I always build my own loop whenever I needed a custom query.
You can probably do it like this,
# First Argument
$args = array(
'tax_query' => array(
'relation' => 'AND',
array(
'taxonomy' => 'industry',
'terms' => $user_input,
),
array(
'taxonomy' => 'format',
'terms' => $user_input2,
),
),
);
# Second Argument
$lessargs = array(
'tax_query' => array(
array(
'taxonomy' => 'industry',
'terms' => $user_input,
),
),
);
$query = new WP_QUery( $args ); //Run First Query
$posts = $query->get_posts(); //Get Post of first Query
if ( !$posts ) { //If no post on First query Run Second Query
$query = new WP_QUery( $lessargs );
$posts = $query->get_posts(); //Get Post of second query
}
if ( !$posts ) return 'No Result Found'; //stop execution if no results
foreach( $posts as $post ) { //Loop through each result
_e( $post->post_title ); // Echo the title
}
}
I would do it slightly differently, just to cater for the fact that neither query will return any rows:
$the_query = new wp_query($args);
if ($the_query->have_posts()) {
while ($the_query->have_posts()) {
the_post();
// Return Query Results
}
} else {
$the_query = new wp_query($lessargs);
if ($the_query->have_posts()) {
while ($the_query->have_posts()) {
the_post();
// Return Second Query Results
}
} else {
echo '<p>No posts found.</p>';
}
}
Note you have a typo with your $lessargs variable.
Related
I'm working on a WP_Query loop that is suppose to show the list of posts in a following way
+ Custom taxonomy term 1
++ Post 1
++ Post 2
+ Custom taxonomy term 2
++ Post 1
++ Post 2
So in general it will work for CPT called 'career'. In a real life my custom taxonomy (job-category) is like: Drivers, Logistics, HR etc. And to each of such taxonomy/category I've got created specific posts. There is also a custom taxonomy called job-country which suggests the territory.
To achieve the way of showing my posts I am using the following code:
<?php
$terms = get_terms([
'taxonomy' => 'job-category',
'hide_empty' => true,
'orderby' => 'count',
'order' => 'DESC'
]);
usort( $terms, function( $a, $b ) {
$a_ste = (int) get_term_meta( $a->term_id, 'stick_to_end', true );
$b_ste = (int) get_term_meta( $b->term_id, 'stick_to_end', true );
if ($a_ste == $b_ste) return 0;
return ($a_ste < $b_ste) ? -1 : 1;
} );
if ($terms) { //categories exists
foreach ($terms as $category) { ?>
<h2 class="category-title">
<?= $category->name ?>
</h2>
<?php
$posts = get_posts(array(
'posts_per_page' => -1,
'post_type' => 'career',
'tax_query' => [
[
'taxonomy' => 'job-category',
'field' => 'term_id',
'terms' => $category->term_id,
]
]
));
if ( $posts ) {
foreach( $posts as $post ) {
setup_postdata( $post );
include 'JobListThumb.php';
};
wp_reset_postdata();
}
}
} else { //no categories
$posts = get_posts(array(
'posts_per_page' => -1,
'post_type' => 'career'
));
if ( $posts ) {
foreach( $posts as $post ) {
setup_postdata( $post );
include 'JobListThumb.php';
};
wp_reset_postdata();
}
}
?>
And it works. But because of certain reasons (working on an ajax filtering function) I need to achieve the same thing using traditional wp_query.
This is what I've got:
$args = array(
'orderby' => 'date', // we will sort posts by date
'order' => $_POST['date'], // ASC or DESC
'post_type' => 'career',
);
// for taxonomies / categories
if( isset( $_POST['categoryfilter'] ) && isset( $_POST['taxonomyfilter'] ))
$args['tax_query'] = array(
'relation' => 'AND',
array(
'taxonomy' => 'job-category',
'field' => 'id',
'terms' => $_POST['categoryfilter']
),
array(
'taxonomy' => 'job-country',
'field' => 'id',
'terms' => $_POST['taxonomyfilter']
)
);
// if you want to use multiple checkboxes, just duplicate the above 5 lines for each checkbox
$query = new WP_Query( $args );
if( $query->have_posts() ) :
while( $query->have_posts() ): $query->the_post();
echo '<h2>' . $query->post->post_title . '</h2>';
endwhile;
wp_reset_postdata();
else :
echo 'No posts found';
endif;
die();
But I've stucked in a place - how to add those terms / elements to the query? Obviously cannot mix get_terms with wpquery by simply copying instead echo'ing the title.
Do you have any suggestions how to solve this?
I am working on a filter for a post grid in Wordpress with ajax.
It's fundamentally working as a whole, but I'm trying to filter using multiple taxonomies. But instead of it combining the taxonomies to refine the search such as posts tagged with 'a' AND 'b'
It's just showing all posts with the tag 'a' and with the tag 'b'
$args = array(
'post_type' => 'projects',
'orderby' => 'date', // we will sort posts by date
'order' => $_POST['date'] // ASC or DESC
);
if( isset($_POST['multi_subject']) && !empty($_POST['multi_subject']) ) {
$args['tax_query'] = array(
array(
'taxonomy' => 'category',
'field' => 'id',
'terms' => $_POST['multi_subject']
)
);
}
if( isset($_POST['multi_style']) && !empty($_POST['multi_style']) ) {
$args['tax_query'] = array(
array(
'taxonomy' => 'styles',
'field' => 'id',
'terms' => $_POST['multi_style']
)
);
}
$query = new WP_Query( $args );
if( $query->have_posts() ) :
while( $query->have_posts() ): $query->the_post();
echo '<a href="'. get_permalink() .'" data-author="'. get_the_author() .'" data-tier="'. get_author_role() .'">';
echo '<h2>' . $query->post->post_title . '</h2>';
echo '<div>'. the_post_thumbnail() .'</div>';
echo '</a>';
endwhile;
wp_reset_postdata();
else :
echo 'No posts found';
endif;
die();
I'm sure it's something simple to do with the isset then setting the args but I can't figure it out.
Your current tax query does not allow for both taxonomies to be checked cause if both are set your second tax check will overrite the first. To allow for both you need to append them... refactor your tax_query to something like this:
// start with an empty array
$args['tax_query'] = array();
// check for first taxonomy
if( isset($_POST['multi_subject']) && !empty($_POST['multi_subject']) ) {
// append to the tax array
$args['tax_query'][] = array(
'taxonomy' => 'category',
'field' => 'id',
'terms' => $_POST['multi_subject']
);
}
// check for another taxonomy
if( isset($_POST['multi_style']) && !empty($_POST['multi_style']) ) {
// append to the tax array
$args['tax_query'][] = array(
'taxonomy' => 'styles',
'field' => 'id',
'terms' => $_POST['multi_style']
);
}
I am trying to feed in a tax_query argument with a variable pulling from a Custom Field. Yet nothing is returned. I did a var_dump on my variable and it keeps returning "boolean:False". So I thought maybe I needed to run a loop (my custom field is a sub_field of a group), and then var_dump returns nothing at all. I'm fairly new to WP/PHP development, not sure what's going on here. Any help would be greatly appreciated!
<?php
if(have_rows('wine_profile')) :
while(have_rows('wine_profile')) : the_row();
$label = get_sub_field("taxonomy_label");
var_dump($label);
$wineProfiles = new WP_Query(array(
'posts_per_page' => '-1',
'post_type' => 'wines',
'tax_query' => array(
array(
'taxonomy' => 'labels',
'field' => 'slug',
'terms' => $label
)
),
'order' => 'DESC',
'orderby' => 'ID'
));
if ($wineProfiles->have_posts()) : while ($wineProfiles->have_posts()) : $wineProfiles->the_post();
get_template_part('includes/component', 'colorBlockLg');
get_template_part('includes/component', 'profile');
?>
<?php endwhile;
endif; endwhile; endif; ?>
Try to use -
$label = get_sub_field("taxonomy_label",get_the_ID());
var_dump($label);
I guess because you haven't started post loop!
<?php
if ( have_posts() ) {
while ( have_posts() ) {
the_post();
//
// Put your code here //
} // end while
} // end if
?>
``
I'm trying to display all posts from taxonomy. I have posts type(Docs) and taxonomy (type_docs) I'm trying to list all posts from that post type. My code is like this but it is not working
<?php
$custom_terms = get_terms('type_docs');
foreach($custom_terms as $custom_term) {
wp_reset_query();
$args = array('post_type' => 'docs',
'tax_query' => array(
array(
'taxonomy' => 'type_docs',
'field' => 'slug',
'terms' => $custom_term->slug,
),
),
);
$loop = new WP_Query($args);
if($loop->have_posts()) {
echo '<h2>'.$custom_term->name.'</h2>';
while($loop->have_posts()) : $loop->the_post();
echo ''.get_the_title().'
<br>';
endwhile;
}
}
?>
I’m trying to only list all posts from taxonomy, can somebody help with this?
I don't get exactly why you want to do thing like that but here is the solution:
<?php
// Get your custom terms
$custom_terms = get_terms('type_docs');
// Prepare the query
$args = array(
'post_type' => 'docs',
'posts_per_page' => -1,
'tax_query' => array()
);
// Prepare the array to receive terms tax_query
$terms_query = array();
foreach($custom_terms as $custom_term) {
// Add terms to the tax query
$args['tax_query'][] = array(
'taxonomy' => 'type_docs',
'field' => 'slug',
'terms' => $custom_term->slug,
);
}
// Get the posts (or you could do your new WP_Query)
$posts = get_posts($args);
// Display
foreach($posts as $post) : setup_postdata($post); ?>
<?php the_title(); ?><br>
<?php endforeach; ?>
I'm trying to create a loop that loads posts from a custom taxonomy and a specific category , i have used this code below but it doesn't show anything
<ul class="row">
<?php
$latest_apps = new WP_Query(array(
'post_type' => array('product','post'),
'posts_per_page' => 30,
'tax_query' => array(
'relation' => 'AND',
array(
'taxonomy' => 'category',
'field' => 'id',
'terms' => array( get_option("free_apps_category") )
),
array(
'taxonomy' => 'product_cat',
'field' => 'id',
'terms' => array( get_option("premium_apps_category") )
)
)
));
$c = 0;
while ($latest_apps->have_posts()) : $latest_apps->the_post();
$c++;
// post is even
if( $c % 2 == 0) {
?>
<?php the_post_thumbnail("post"); ?>
</li>
<?php
}
// post is odd
else {
?>
<li class="content-box-post">
<?php the_post_thumbnail("post"); ?>
<?php
}
endwhile;
?>
</ul>
i have used static id numbers instead of get_option('free_apps_category') and get_option('premium_apps_category') but it still does not work
please help , thank u so much
regards
If it does not show you nothing, it is because you have no posts that match your condition.
And reading the code fast One can see that your query is for a post either normal or under product post type that is both on the premium_apps_category AND free_apps_category . Are you sure that you actually have one ?