Showing list of posts including custom taxonomy terms - php

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?

Related

Wordpress ajax filter posts by combining multiple taxonomies

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']
);
}

Display posts in the order of their selection

I've offert the possibility to my client to choose one by one the related post for each post. I've set up a custom field with ACF and use this to display the choosen posts or random posts :
<?php $terms = get_the_terms( $post->ID , 'custom-taxonomy1' ); if ( !empty( $terms ) ) :?>
<?php
$related_acf = get_field('related_group');
$rel_posts = $related_acf["related posts"];
$related_ids = array();
foreach ( $rel_posts as $rel_post) {
array_push($related_ids, $rel_post['post']);
}
global $post;
$current_post_type = get_post_type( $post );
$terms = get_the_terms( $post->ID , 'custom-taxonomy1' );
$term_ids = array_values( wp_list_pluck( $terms,'term_id' ) );
$post_count_skrn = get_theme_mod('progression_studios_media_more_like_post_count', '3');
if ( count($related_ids) > 0 ) {
$args=array(
'post_type' => array('custompost1', 'custompost2', 'post'),
'post__in' => $related_ids
);
} else {
$args=array(
'post_type' => $current_post_type,
'posts_per_page'=> $post_count_skrn,
'orderby'=>'rand', // Randomize the posts
'post__not_in' => array( $post->ID ),
'tax_query' => array(
array(
'taxonomy' => 'video-genres',
'terms' => $term_ids,
'field' => 'id',
'operator' => 'IN'
)
),
);
}
So I wonder if I can add something like :
if ( count($related_ids) > 0 ) {
$args=array(
'post_type' => array('custompost1', 'custompost2', 'post'),
'orderby'=>'XXXXX', // Ordering the posts with the order of selection
'post__in' => $related_ids
);
Best regards,
Clément
Wordpress have 'orderby'=>'post__in'
Posts will now be displayed according to their position in the $related_ids array
$args=array(
'post_type' => array('custompost1', 'custompost2', 'post'),
'orderby'=>'post__in', // Ordering the posts with the order of selection
'post__in' => $related_ids
);

Filter WooCommerce related products by Polylang language

I'm using polylang plugin to having multi-languages website.
Using WooCommerce with polylang demands duplicating each product for each language, so assuming I have Hebrew and English, that means 2 duplications for each products.
It works fine with WooCommerce plugin, but when I'm displaying "related products" at the end of the product page, it's mixing products in English and Hebrew together.
I expect to filter the related product by website current language (if(get_locale() == 'en_US') - to check website current locale state, else will represent Hebrew).
Polylang functions
Here is what I have tried, but I got stuck on the part of filtering the product by language:
add_filter( 'woocommerce_product_related_posts', 'custom_related_products' );
function custom_related_products($product){
global $woocommerce;
// Meta query
$meta_query = array();
$meta_query[] = $woocommerce->query->visibility_meta_query();
$meta_query[] = $woocommerce->query->stock_status_meta_query();
$meta_query = array_filter( $meta_query );
// Get the posts
$related_posts = get_posts( array(
'orderby' => 'rand',
'posts_per_page' => '4',
'post_type' => 'product',
'fields' => 'ids',
'meta_query' => $meta_query
) );
if ( $related_posts->have_posts() ) {
while ( $related_posts->have_posts() ) : $related_posts->the_post();
if(pll_get_post_language(get_the_ID())){
//Not sure its the right approach for this..
}
endwhile;
}
$related_posts = array_diff( $related_posts, array( $product->id ), $product->get_upsells() );
return $related_posts;
}
How can I filter Woocommerce related product section by language?
Edit
So after a little bit of research and help in the comments I found out that 'lang' => 'en' argument does exist, but even when I use it, there is no change on related products language display.
Any ideas?
add_filter( 'woocommerce_product_related_posts', 'custom_related_products' );
function custom_related_products($product){
global $woocommerce;
// Meta query
$meta_query = array();
$meta_query[] = $woocommerce->query->visibility_meta_query();
$meta_query[] = $woocommerce->query->stock_status_meta_query();
$meta_query = array_filter( $meta_query );
// Get the posts
$related_posts = get_posts( array(
'orderby' => 'rand',
'posts_per_page' => '4',
'post_type' => 'product',
'fields' => 'ids',
'meta_query' => $meta_query,
'suppress_filters' => false
) );
if ( $related_posts->have_posts() ) {
while ( $related_posts->have_posts() ) : $related_posts->the_post();
if(pll_get_post_language(get_the_ID())){
//Not sure its the right approach for this..
}
endwhile;
}
$related_posts = array_diff( $related_posts, array( $product->id ), $product->get_upsells() );
return $related_posts;
}
suppress_filters There is a way to make get_posts cache the results however, the suppress_filters option is true by default, but if you set it to false, the caching mechanisms inside WordPress will do their work, and results will be saved for later.
You can try this code:
$related_posts = get_posts( array(
'orderby' => 'rand',
'posts_per_page' => '4',
'post_type' => 'product',
'meta_query' => $meta_query,
'lang' => 'en'
) );
if ($related_posts) {
foreach ($related_posts as $post) {
setup_postdata($post);
// something like <li><?php the_title(); ?></li>
}
}
wp_reset_postdata();
This code correctly returns code in selected language on my site
While working on a custom WordPress REST Api end point to fetch post by selected language or device language, this worked. See if it can help you out.
function mycustomplugin_posts($params) {
// get the url params
$page = $params->get_param('page') ? $params->get_param('page') : 0;
$per_page = $params->get_param('per_page') ? $params->get_param('per_page') : 10;
$offset = $params->get_param('offset') ? $params->get_param('offset') : 0;
$order = $params->get_param('order') ? $params->get_param('order') : 'desc';
$order_by = $params->get_param('order_by') ? $params->get_param('order_by') : 'date';
$lang = array_search($params->get_param('lang'),polylang_json_api_languages(), true) ? $params->get_param('lang') : pll_default_language();
$args = [
'post_type' => 'post',
'page' => $page,
'numberposts' => $per_page,
'offset' => $offset,
'order' => $order,
'orderby' => $order_by,
'tax_query' => [
[
'taxonomy' => 'language',
'field' => 'slug',
'terms' => $lang
]
]
];
$posts = get_posts($args);
$data = [];
$i = 0;
foreach($posts as $post) {
// Extract the post data
$data[$i]['id'] = $post->ID;
$data[$i]['title'] = $post->post_title;
$data[$i]['content'] = $post->post_content;
$data[$i]['excerpt'] = e42_the_short_content($post->post_content, 300);
$data[$i]['slug'] = $post->post_name;
$data[$i]['date'] = $post->post_date;
$data[$i]['link'] = get_permalink($post->ID);
$data[$i]['author'] = get_the_author_meta('display_name', $post->post_author);
$data[$i]['categories'] = array();
$data[$i]['featured_image']['thumbnail'] = get_the_post_thumbnail_url($post->ID, 'thumbnail');
$data[$i]['featured_image']['medium'] = get_the_post_thumbnail_url($post->ID, 'medium');
$data[$i]['featured_image']['large'] = get_the_post_thumbnail_url($post->ID, 'large');
foreach(get_the_category($post->ID) as $category){
array_push($data[$i]['categories'],$category->term_id);
}
$i++;
}
// Create the response object
$response = new WP_REST_Response( $data );
// Add a custom status code
$response->set_status( 200 );
return $response;
}
/plugins/woocommerce/templates/single-product/related.php
Move this to child theme
yourtheme/woocommerce/single-product/related.php
And add the following line to the foreach loop
if (pll_current_language()!=pll_get_post_language($post_object->ID)) {
continue;
}
Basically if current language does not match product language we skip over it.

Retrieve posts by custom taxonomy child on parent taxonomy page

So from the parent taxonomy view:
Child 1
post
post
post
Child 2
post
post
post
post
Child 3
post
post
post
post
I've scoured the internet for a solution to this, but nothing seems to be working. I'm able to successfully echo the term ID, but when I pass that into the query it returns nothing.
<?php
$terms = get_terms( 'ht_kb_category' );
if ( ! empty( $terms ) && ! is_wp_error( $terms ) ){
echo '<ul>';
foreach ( $terms as $term ) {
if ($term->parent != 0) {
echo '<li><h1>' . $term->name . '</h1></li>';
$the_query = new WP_Query( array(
'post_type' => 'post',
'tax_query' => array(
array (
'taxonomy' => 'ht_kb_category',
'field' => 'slug',
'terms' => $term->slug,
)
),
) );
while ( $the_query->have_posts() ) :
echo '<p>'. the_title() .'</p>';
endwhile;
/* Restore original Post Data
* NB: Because we are using new WP_Query we aren't stomping on the
* original $wp_query and it does not need to be reset.
*/
wp_reset_postdata();
}
}
echo '</ul>';
} ?>
Finally found the solution after some detective work using the custom taxonomy URL. I was missing the 'post_type' and needed to query 'tag_id' instead of 'term_id'.
<?php $current_term_id = $hkb_current_term_id ?>
<?php
$myposts = get_posts(array(
'showposts' => -1,
'post_type' => 'ht_kb',
'tax_query' => array(
array(
'taxonomy' => 'ht_kb_category',
'field' => 'tag_id',
'terms' => $current_term_id)
))
);
echo '<ul>';
foreach ($myposts as $mypost) { ?>
<li><?php echo $mypost->post_title ?></li>
<?php }
echo '</ul>';
?>

Custom taxonomy and custom post type with custom pagination 404 not found

My pagination is throwing a 404 error when the posts from General -> Reading are smaller than my custom number of posts on my custom taxonomy cities (custom post type city). From what I saw on SO this issue can be fixed usually by using a filter of pre_get_posts, but don't know how to apply it on my case.
I want to mention that in the taxonomy-cities.php I am getting posts of a category of a custom taxonomy of a custom post type.
taxonomy-cities.php
$cat_ID = get_query_var('cities');
$custom_id = get_term_by('slug', $cat_ID, 'cities');
add_filter('posts_orderby', 'edit_posts_orderby');
function edit_posts_orderby($orderby_statement) {
global $aPostsIDs;
$orderby_statement = 'FIELD(ID, '.implode(',',$_SESSION['saved_city_ids']).')';
return $orderby_statement;
}
$offset = ($paged - 1) * $num_city_guides_post;
$args['post_type'] = 'city';
$args['posts_per_page'] = $num_city_guides_post; // 5
$args['orderby'] = $orderby; // rand
$args['order'] = $order; // DESC
$args['paged'] = $paged; // 1
$args['tax_query'] = array(
array(
'taxonomy' => 'cities',
'field' => 'id',
'terms' => array($custom_id->term_id) // 3742
)
);
}
$wp_query = new WP_Query($args);
if ( $wp_query->have_posts() ) :
while ( $wp_query->have_posts() ) : $wp_query->the_post();
// some code here
endwhile;
else: echo 'No Posts';
endif;
wp_reset_postdata();
For archive-city.php I am using this filter in the functions.php and it works fine, but it doesn't get applied to the taxonomy-cities.php so I get 404:
function portfolio_posts_per_page_city( $query ) {
if (array_key_exists('post_type', $query->query_vars)) {
if ( $query->query_vars['post_type'] == 'city' )
$num_city_guides_post = get_option('num_city_post');
if( empty( $num_city_guides_post ) )
$num_city_guides_post = 9;
$query->query_vars['posts_per_page'] = $num_city_guides_post;
return $query;
}
}
if ( !is_admin() ) add_filter( 'pre_get_posts', 'portfolio_posts_per_page_city' );
This is an old question however i recently had the same issue. The following Snippet is in fact the contents of my taxonomy-template.php using the standard WP_Query, example here.
How to properly paginate custom post type taxonomy
The Query
Firstly because it's a taxonomy template, the first line declares $term allowing me to access the term array and therefore the taxonomy id, name url etc.
Secondly i'm setting the term id as a variable to be used in the tax_query parameter. This is used to query my custom post type videos and then get the taxonomy (category) for the loop, stored in $term_id.
The Fix
Because i'm looping through the posts and limiting the results, we effectively need to search for our remaining posts while excluding the previous results and results thereafter. What this means is quite simple:
You must make your custom post types searchable in order for pagination to work:
Important:
'exclude_from_search' => false,
Example taxonomy-template.php
<?php $term = get_term_by( 'slug', get_query_var( 'term' ), get_query_var( 'taxonomy' ) ); ?>
<?php
$term_id = $term->term_id;
$paged = ( get_query_var('paged') ) ? get_query_var('paged') : 1;
$args = array(
'post_type' => 'videos',
'posts_per_page' => 4,
'paged' => $paged,
'tax_query' => array(
array(
'taxonomy' => $term->taxonomy,
'field' => 'term_id',
'terms' => $term_id
)
)
);
$the_query = new WP_Query( $args );
?>
<?php if ( $the_query->have_posts() ) : while ( $the_query->have_posts() ) : $the_query->the_post(); ?>
<!-- Loop -->
<?php endwhile; ?>
<?php if ($the_query->max_num_pages > 1) : ?>
<?php endif; ?>
<?php else: ?>
<!-- Nothing Found -->
<?php endif; ?>
Maybe u can solve this without filters.
It`s work for pagination my custom posts types
$paged = get_query_var('paged') ? get_query_var('paged') : 1;
$args = array( 'post_type' =>'cities', 'posts_per_page' => 0, 'paged' => $paged );
$query = query_posts( $args );
if ( have_posts() ) : while ( have_posts() ) : the_post(); ?>
//Do wordpress Loop
<?php endwhile; else: include( get_404_template() ); ?>
<?php endif; wp_reset_postdata(); ?>
I had the same problem with my custom post taxonomies pagination. Older posts page was coming with a 404 page not found. This issue is related to WP taxonomy slug so you have to rewrite rules for your custom post type taxonomies like this below:
function generate_taxonomy_rewrite_rules( $wp_rewrite ) {
$rules = array();
$post_types = get_post_types( array( 'public' => true, '_builtin' => false ), 'objects' );
$taxonomies = get_taxonomies( array( 'public' => true, '_builtin' => false ), 'objects' );
foreach ( $post_types as $post_type ) {
$post_type_name = $post_type->name;
$post_type_slug = $post_type->rewrite['slug'];
foreach ( $taxonomies as $taxonomy ) {
if ( $taxonomy->object_type[0] == $post_type_name ) {
$terms = get_categories( array( 'type' => $post_type_name, 'taxonomy' => $taxonomy->name, 'hide_empty' => 0 ) );
foreach ( $terms as $term ) {
$rules[$post_type_slug . '/' . $term->slug . '/?$'] = 'index.php?' . $term->taxonomy . '=' . $term->slug;
$rules[$post_type_slug . '/' . $term->slug . '/page/?([0-9]{1,})/?$'] = 'index.php?' . $term->taxonomy . '=' . $term->slug . '&paged=' . $wp_rewrite->preg_index( 1 );
}
}
}
}
$wp_rewrite->rules = $rules + $wp_rewrite->rules;
}
add_action('generate_rewrite_rules', 'generate_taxonomy_rewrite_rules');
This should work for all custom post type taxonomies and if you want to be more specific then you can try updating these two variables like this:
$post_types = get_post_types( array( 'name' => 'city', 'public' => true, '_builtin' => false ), 'objects' );
$taxonomies = get_taxonomies( array( 'name' => 'cities', 'public' => true, '_builtin' => false ), 'objects' );
Finally, just use your default query loop without passing any arguments. Pages will be generated based on General -> Reading.

Categories