Filter WP_QUERY by custom taxonomy - php

I'm trying to solve one issue with one of the functions which I've created recently. Below you will find a piece of code which creates a dropdown field in which each represents specific 'partner company'. The code works perfectly.
function fnc_select_1() {
$args = array(
'post_type' => 'freecourses',
'orderby' => 'meta_value',
'status' => 'publish',
'order' => 'DESC',
'meta_key' => 'validation_date',
);
$the_query = new WP_Query($args);
if ($the_query->have_posts()):
while ($the_query->have_posts()) : $the_query->the_post();
if(have_rows('validation_date')):
while (have_rows('validation_date')) : the_row();
if( get_sub_field('company')) {
$firm_array[] = get_sub_field('company');
}
endwhile;
wp_reset_query();
else :
// no rows found
endif;
endwhile;
$firms = array_unique($firm_array);
natsort($firms);
echo '<select type="text" class="form-control" name="company" id="company">';
echo '<option value="">company</option>';
foreach ($firms as $firm) {
echo '<option value="'. $firm .'">';
echo $firm;
echo '</option>';
}
echo '</select>';
endif;
}
add_shortcode( 'select_1', 'fnc_select_1' );
Because of certain reasons I've decided to enhance this function by adding:
extra filtering based on custom taxonomy (called "type")
based on a page in which function will be displayed I wanted to limit / filter those companies by specific terms of this taxonomy.
So I've created this kind of code:
if (is_page(29557) ):
$childno = '205';
elseif (is_page(29640) ):
$childno = '206';
endif;
and simply to my wp_query args I thought I may add:
'tax_query' => array(
'relation' => 'AND',
array(
'taxonomy' => 'type',
'child_of' => $childno
),
),
but it doesn't work. It do not display the dropdown at all..
Where is the issue then?

Related

How to add category option to shortcode

I'm new to creating wordpress shortcodes and have one just about working the way I want. Missing something specific. Currently I am able to put the following on any page - [children] and it pulls a query of all posts from the custom post type "children" I would like to add the option to add the category id within the shortcode - something like [children category="8"] Here is the code I have so far:
add_shortcode( 'children', 'display_custom_post_type' );
function display_custom_post_type(){
$args = array(
'post_type' => 'children',
'post_status' => 'publish',
'orderby' => 'title',
'order' => 'ASC',
);
$string = '';
$query = new WP_Query( $args );
if( $query->have_posts() ){
while( $query->have_posts() ){
$query->the_post();
$string .= '<div id="childWrapper"><div id="childImage">' . get_the_post_thumbnail() . '</div><div style="clear: both;"></div><div id="childName">' . get_the_title() . '</div><div style="clear: both;"></div></div>';
}
}
wp_reset_postdata();
return $string;
}
Secondary - is it possible for it to show posts in multiple categories, but only where the posts are in each of the categories. For example showing a list of children, who fall under a category for critical care and surgery needed.
Any help would be greatly appreciated.
You should refer Shortcode function from WordPress Codex. Assuming your taxonomy name is category, I made some changes in your current code it should work as per your requirements.
/**
* [children category="5,7,8"]
*/
add_shortcode( 'children' , 'display_custom_post_type' );
function display_custom_post_type($atts) {
$atts = shortcode_atts( array(
'category' => ''
), $atts );
//If category is multiple: 8,9,3
$categories = explode(',' , $atts['category']);
$args = array(
'post_type' => 'children',
'post_status' => 'publish',
'orderby' => 'title',
'order' => 'ASC',
'posts_per_page'=> -1,
'tax_query' => array( array(
'taxonomy' => 'category',
'field' => 'term_id',
'terms' => $categories
) )
);
$string = '';
$query = new WP_Query( $args );
if( ! $query->have_posts() ) {
return false;
}
while( $query->have_posts() ){
$query->the_post();
$string .= '<div id="childWrapper"><div id="childImage">' . get_the_post_thumbnail() . '</div><div style="clear: both;"></div><div id="childName">' . get_the_title() . '</div><div style="clear: both;"></div></div>';
}
wp_reset_postdata();
return $string;
}

Wordpress Custom Post Type Archive page with Drop down Taxonomyes

I'm developing a Latin Literature digital library for my thesis.
Right now I'm working on the author's archive page.
Authors is a Custom Post Type registered as 'auctores' with a custom taxonomy assigned to it named 'periodi'.
In the archive page (archive-auctores.php) I'd like to show all the authors listed by a meta field and other three columns: Periods (which refers to the custom taxonomy that I'd like to make a filter), Number of books (there should be the number of books (cpt) assigned to that author) and Gener (where to display all the literary genres of the books assigned to that author and it would be another taxonomy assigned to the book cpt via the cpt-onomies plugin). The number column should be sortable (asc/desc) while i'd like to make a filter for periods and for kinds.
I.E. --> opening the archive page it will show up the complete list of authors. So it should be possible to filter the authors for period and the page should show just the authors "tagged" with that specific taxonomy term.
I thought I had found a solution here, but when I try to select one term in the drop down the list remain the same.
I'm surely missing something.
That's the code of my template right now:
<form method="post" action="<?php the_permalink()?>">
<select name="periodi" id="selectperiodo" class="postform" onchange="submit();">
<option value="">Tutti i periodi</option>
<?php
$args = array(
'orderby' => 'ID',
'order' => 'ASC',
'hide_empty' => false,
'fields' => 'all',
'hierarchical' => true,
'pad_counts' => false,
'get' => '',
'child_of' => 0,
'parent' => '',
'childless' => false,
'cache_domain' => 'core',
'update_term_meta_cache' => true,
'meta_query' => '',
'parent' => 0
);
$terms = get_terms('periodi', $args);
if ( $terms ) {
foreach ( $terms as $term ) {?>
<option <?php if($term->slug == $_POST['periodi']){ echo 'selected="selected"';} ?> value="<?php echo esc_attr( $term->slug )?>"><?php echo esc_html( $term->name ) ?></option>
<?php }
}
?>
</select>
</form>
<table class="dataTable table table-hover">
<tr>
<th>Nome</th>
<th>Periodo</th>
<th>Opere</th>
<th>Genere</th>
</tr>
<?php $auctores_query = new WP_Query(array(
'post_type' => 'auctores',
'posts_per_page' => -1,
'order' => 'ASC',
'meta_key' => 'nome_classico',
'orderby' => 'meta_value',
)
); ?>
<?php $j = 0 ?>
<?php while ($auctores_query->have_posts()) : $auctores_query->the_post(); ?>
<?php $additional_class = (++$j % 2 == 0) ? 'even' : 'odd'; ?>
<tr class="<?php echo $additional_class ?>">
<td><?php the_title( '<h3 class="entry-title">', '</h3>' )?></td>
<td>
<?php
$terms = get_the_terms( $post->ID, 'periodi' );
if ( $terms && ! is_wp_error( $terms ) ) :
$periodi_links = array();
foreach ( $terms as $term ) {
$periodi_links[] = $term->name;
}
$on_draught = join( ", ", $periodi_links );
?>
<?php echo $on_draught; ?>
<?php endif; ?>
</td>
<td><span class="badge"><?php
$args = array('post_type' => 'texti',
'tax_query' => array (
array ( 'taxonomy' => 'auctores',
'field' => 'id',
'terms' => get_the_ID()
)
));
$query = new WP_Query( $args );
// the query
echo $query->found_posts;
?></span></td>
</tr>
<?php endwhile; ?>
</table>
Any help would be really appreciated.
Thanks!
IF you want the list of authors to be limited based on the drop-down selection, then you'll need to modify the query and utilize the Taxonomy Query Parameters:
Modify the code so that it responds to the form post as follows:
// First we have to take the args out into a variable
$args = array(
'post_type' => 'auctores',
'posts_per_page' => -1,
'order' => 'ASC',
'meta_key' => 'nome_classico',
'orderby' => 'meta_value'
);
// Then, we watch for the post and modify the args if appropriate:
if ( ! empty( $_POST['periodi'] ) ) {
$args['tax_query'] = array(
array(
'taxonomy' => 'periodi',
'field' => 'slug',
'terms' => $_POST['periodi']
)
);
}
// Then we can execute the query:
$auctores_query = new WP_Query( $args );

How To Display Categories and the posts inside of a Custom Post Type

I need some help here as I've exhausted every place I can trying to find information. This is what I'm trying to do:
I have created a custom Post type in my admin called "Classes"
That works fine, the data works great and it's inputting in the admin.
I want to make a custom template to show this custom post type. However, everything I try it's not displaying properly. I've tried many code variations.
I know someones already done this and has the block of code to display this. This is what I need the code to do:
List All categories in my custom post type 'classes'
List all posts (show all content, not a link or excerpt) inside of each category.
Display it as such (I'm using Jquery Accordion)
the_category()
the_title()
the_content()
========================================================
By the way, Here is the block of code I'm currently using. It does work, but it ONLY shows the posts, all of them. It does not show the category with posts inside of them.
<?php
$type = 'classes';
$args = array (
'post_type' => $type,
'post_status' => 'publish',
'paged' => $paged,
'posts_per_page' => 10,
'ignore_sticky_posts'=> 1
);
$temp = $wp_query; // assign ordinal query to temp variable for later use
$wp_query = null;
$wp_query = new WP_Query($args);
if ( $wp_query->have_posts() ) :
while ( $wp_query->have_posts() ) : $wp_query->the_post();
echo '<h3 class="acc1">';
the_title();
echo '</h3>';
echo '<div class="sc"><div class="vs">View Schedule</div>';
the_content();
echo '</div>';
endwhile;
else :
echo '<h2>Not Found</h2>';
get_search_form();
endif;
$wp_query = $temp;
?>
Community, I need you. Please give your feedback!
What you want to do is actually start with a category query. You have to make sure you query all your categories with your custom post type:
Then for each category you would do pretty much what you have above.
$taxonomy = 'classes';
$args = array('hide_empty' => false,);
$terms = get_terms( $taxonomy, $args );
foreach($terms as $val) {
$term_id = $val->term_id;
$term_name = $val->name;
// now do post query
}
You most likely would have to display the category name as a header for your accordion as well.
Here's all the args for get_terms:
http://codex.wordpress.org/Function_Reference/get_terms
For that query you also most likely have to use a Simple Taxonomy Query (search for that on the page).
http://codex.wordpress.org/Class_Reference/WP_Query
By adding this arg to your above query:
'tax_query' =>
array(
'taxonomy' => 'category',
'field' => 'slug',
'terms' => array( $term_name )
)
Is that what you were looking for?
There might be a better way to do this but I just had to recently do this and did pretty much what I just outlined here.
I should have been more clear and said to put the posts query within the foreach of the terms query.
Here's the updated answer based on your last reply (I have not tested this).
<?php
$taxonomy = 'classes';
$args = array('hide_empty' => false,);
$terms = get_terms( $taxonomy, $args );
foreach($terms as $val) {
$term_id = $val->term_id;
$term_name = $val->name;
$type = 'classes';
$args = array (
'post_type' => $type,
'post_status' => 'publish',
'paged' => $paged,
'posts_per_page' => 10,
'ignore_sticky_posts'=> 1,
'tax_query' =>
array(
'taxonomy' => 'category',
'field' => 'slug',
'terms' => array( $term_name )
)
);
$temp = $wp_query; // assign ordinal query to temp variable for later use
$wp_query = null;
$wp_query = new WP_Query($args);
if ( $wp_query->have_posts() ) :
while ( $wp_query->have_posts() ) : $wp_query->the_post();
echo '<h3 class="acc1">';
the_title();
echo '</h3>';
echo '<div class="sc"><div class="vs">View Schedule</div>';
the_content();
echo '</div>';
endwhile;
else :
echo '<h2>Not Found</h2>';
get_search_form();
endif;
$wp_query = $temp;
}
?>

Having trouble with wordpress custom taxonomy archive

I'm having a little trouble with a custom taxonomy template. I inherited a site that was developed by someone else and they use "Types" plugin to add some custom taxonomies.
Goal:
to have an archive template that shows only posts with a certain taxonomy term in it at example-domain.com/people/harrison-ford
Problem:
This code is bringing in posts that do not have the taxonomy selected.
Here's my full code:
<?php
$year = get_post_meta($post->ID, 'year', true);
$post_type = 'post';
$tax = 'people';
$tax_terms = get_terms( $tax );
if ($tax_terms) {
$args = array(
'post_type' => $post_type,
'people' => 'harrison-ford',
"$tax" => $tax_term->slug,
'post_status' => 'publish',
'posts_per_page' => -1,
'caller_get_posts'=> 1,
'orderby' => 'date',
'order' => DESC
);
$my_query = null;
$my_query = new WP_Query($args);
if( $my_query->have_posts() ) : ?>
<h2 class="wwNews"><?php echo $tax_term->name; ?> News</h2>
<?php while ( $my_query->have_posts() ) : $my_query->the_post(); ?>
<-- display stuff -->
<?php endwhile; // end of loop ?>
<?php endif; // if have_posts()
wp_reset_query();
}
?>
What are you expecting here? "$tax" is going to to be 'people' =>, which is going to overwrite 'harrison-ford' to the value of $tax_term->slug.
'people' => 'harrison-ford',
"$tax" => $tax_term->slug,
Furthermore, I don't know of any custom argument called people, I'm pretty sure that you want tax_query:
'tax_query' => array(
'taxonomy' => 'people',
'terms' => array('harrison-ford', $tax_term->slug)
)
Which will give you the results of all people matching harrison-ford and the value of $tax_term->slug within the taxonomy of people

WordPress Custom Taxonomies WP_Query

I'm trying to create a query where I create multiple categories (taxonomies) in a custom post type, and then on the homepage query based on specific which is working fine. Currently I have 3 taxonomies:
current-specials
meineke-difference
featured
I have already written code that pulls these. The problem I'm running into is that on the homepage it needs to only pull these posts when they are also attached to the "featured" taxonomy. So an example of standard logic for this would be:
if taxonomy = current-specials AND featured then success else fail
But what it's doing is pulling them all because the current code is OR, and I need AND
Thoughts? (code below)
<?php
$post_type = 'coupons';
$tax = 'coupons_category';
$tax_terms = get_terms($tax);
if ($tax_terms):
foreach ($tax_terms as $tax_term):
echo '<div id="'.$tax_term->slug.'" class="coupon-box '.$tax_term->slug.'">';
$args = array(
'post_type' => $post_type,
"$tax" => array($tax_term->slug, 'featured'),
'post_status' => 'publish',
'posts_per_page' => -1,
'caller_get_posts' => 1
);
$myQuery = null;
$myQuery = new WP_Query($args);
if($myQuery->have_posts()):
while ($myQuery->have_posts()) : $myQuery->the_post();
$price = get_field('price_image', $myQuery->ID);
$print = get_field('print', $myQuery->ID);
$product = get_field('product_box_image', $myQuery->ID);
$title = get_the_title();
$content = get_the_content();
echo '<div class="fourty9 left box center">';
echo '<h1>'.$title.'</h1>';
echo '<p class="center"><img src="'.$price.'" /></p>';
echo '<p>'.$content.'</p>';
echo '<p class="center">Print Coupon</p>';
echo '<p class="center"><img src="'.$product.'" alt="Filter"></p>';
echo '</div>';
endwhile;
endif;
echo '</div>';
wp_reset_query();
endforeach;
endif;
?>
You may try this (tax - use taxonomy slug. Deprecated as of Version 3.1 in favor of 'tax_query')
$args = array(
'post_type' => 'coupons',
'posts_per_page' => -1,
'caller_get_posts' => 1,
'tax_query' => array(
array(
'taxonomy' => 'coupons_category',
'field' => 'slug',
'terms' => array( 'current-specials', 'featured' ),
'operator' => 'AND'
)
)
);
$query = new WP_Query( $args );

Categories