Skip to content

Instantly share code, notes, and snippets.

@RevConcept
Last active August 29, 2015 14:13
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save RevConcept/211559c4b8cfb6278078 to your computer and use it in GitHub Desktop.
Save RevConcept/211559c4b8cfb6278078 to your computer and use it in GitHub Desktop.
Conditional Query for Recipe Archive
<?php // DEFAULT LOOP
if( (!isset($_POST['product_selection']) || '' == $_POST['product_selection']) && (!isset($_POST['cat_selection']) || '' == $_POST['cat_selection'] )) { ?>
<?php
$paged = (get_query_var('paged')) ? get_query_var('paged') : 1;
$query = new WP_Query( array(
'post_type' => 'recipes', // your CPT
'post_status' => 'publish',
'paged' => $paged
) );
// Loop
if($query->have_posts()):
while( $query->have_posts() ): $query->the_post(); ?>
<?php get_template_part( 'parts/recipes', 'post' ); ?>
<?php endwhile;
bones_page_navi();
wp_reset_postdata();
endif;
}
// LOOP FILTERED BY PRODUCT
if( $_POST['product_selection'] ) {
$recipe_product = $_POST['product_selection'];
$paged = (get_query_var('paged')) ? get_query_var('paged') : 1;
// Create new query
$query = new WP_Query( array(
'post_type' => 'recipes', // your CPT
'post_status' => 'publish',
'paged' => $paged,
'meta_query' => array(
array(
'key' => 'recipe_products', // name of custom field
'value' => '"' . $recipe_product . '"', // ID - matches exaclty "123", not just 123. This prevents a match for "1234"
'compare' => 'LIKE'
)
),
) );
// Loop
if($query->have_posts()): ?>
<div class="secondary breadcrumbs">
<p><span class="icon-search"></span>Results are currently filtered by the product: <a href="<?php echo get_permalink($recipe_product); ?>"><?php echo get_the_title( $recipe_product ); ?></a></p>
</div>
<?php while( $query->have_posts() ): $query->the_post();
get_template_part( 'parts/recipes', 'post' );
endwhile;
wp_reset_postdata();
endif;
}
// LOOP FILTERED BY CATEGORY
if( $_POST['cat_selection'] ) {
$recipe_cat = $_POST['cat_selection'];
$paged = (get_query_var('paged')) ? get_query_var('paged') : 1;
// Create new query
$query = new WP_Query( array(
'post_type' => 'recipes', // your CPT
'post_status' => 'publish',
'paged' => $paged,
'tax_query' => array(
array(
'taxonomy' => 'recipe-cats',
'field' => 'slug',
'terms' => $recipe_cat
),
),
) );
// Loop
if($query->have_posts()): ?>
<div class="secondary breadcrumbs">
<p><span class="icon-search"></span>Results are currently filtered by the category: <strong><?php echo $recipe_cat; ?></strong></p>
</div>
<?php while( $query->have_posts() ): $query->the_post();
get_template_part( 'parts/recipes', 'post' );
endwhile;
wp_reset_postdata();
endif;
} ?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment