Answer the question
In order to leave comments, you need to log in
How to make a dynamic query in WP_Query?
Good evening. It is impossible to create a dynamic request through the $args parameters in any way. Plain SQL is not suitable because the data in the table is serialized.
I also tried to add parameters to tax_query through foreach, but all in vain. WP_QUERY returns nothing.
The essence of the task is that attributes or taxonomies will change or their number will change and for this you need to generate a certain $args.
I've been working on this task all day, but I couldn't do anything sensible, and there is very little information on the Internet about dynamic queries. Who understands, write what to do?
Answer the question
In order to leave comments, you need to log in
Well, in fact - here you can make a shortcode
And squander the shortcode for your purposes - where you will set the post type, number of posts, taxonomy, etc. - everything is possible
// Shortcode for projects [projects-list posts="3"]
function projects_listing_parameters_shortcode( $atts ) {
ob_start();
$args = shortcode_atts( array (
'type' => 'projects',
'posts' => 6,
'cat' => ''
), $atts );
$options = array(
'post_type' => $args['type'],
'posts_per_page' => $args['posts'],
'tax_query' => array(
array (
'taxonomy' => 'project',
'field' => 'slug',
'terms' => $args['cat'],
)
),
);
$query = new WP_Query( $options );
if ( $query->have_posts() ) $item = 0; {
while ( $query->have_posts() ) : $query->the_post(); $item++;
echo '<div class="item item-' . $item . '">';
get_template_part( 'template-parts/project-cards', get_post_format() );
echo '</div>';
endwhile;
wp_reset_postdata();
$myvariable = ob_get_clean();
return $myvariable;
}
}
add_shortcode( 'projects-list', 'projects_listing_parameters_shortcode' );
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question