How to display current posts custom taxonomy name inside wordpress loop? - php

I am currently building a Wordpress site and I am encountering some difficulty with the following..
I am trying to dynamically add a class to a HTML element by displaying the custom taxonomy name of the current post type, to use as the class name. This is all being done within a Foreach loop.
My code is as follows
<?php
$args = array( 'posts_per_page' => -1, 'post_type' => 'staff', 'orderby' => 'menu_order',
'order' => 'DESC');
$myposts = get_posts( $args );
foreach ( $myposts as $post ) : setup_postdata( $post ); ?>
<?php $terms = wp_get_post_terms( $post_ID, 'department' ); ?>
<?php global $post; $terms = wp_get_post_terms( $post->ID, 'department'); ?>
<div class="grid-item <?php echo $term->slug; ?> ">
<div class="staff-box">
<?php the_post_thumbnail('staff-member'); ?>
<a href="<?php echo the_permalink(); ?>">
<p class="staff-title"><?php the_title(); ?></p>
<p class="staff-job-title"><?php the_field('staff-job-title'); ?></p>
</a>
</div>
</div>
<?php endforeach;
wp_reset_postdata();?>
This is working using slug; ?> to display the class name however it is only displaying "veterinary-surgeons" on every single class name, when it should be displaying the relevant department on each item...
Hope that makes sense.
Many thanks.

To anyone who is interested I have now solved this using:
<?php $term_list = wp_get_post_terms($post->ID, 'department', array("fields" => "all")); ?>
and by using
<?php echo $term_list[0]->slug ; ?>
as class name.
Thanks

You can solve this problem by this code also,
Put this code inside while loop, 'portfolio_category' is custom taxonomy name
$terms = get_the_terms( $post->ID, 'portfolio_category' );
if ( $terms && ! is_wp_error( $terms ) ) :
$links = array();
foreach ( $terms as $term ) {
$links[] = $term->name;
}
$tax_links = join( " ", str_replace(' ', '-', $links));
$tax = strtolower($tax_links);
else :
$tax = '';
endif;

Related

WooCommerce products: Wrong product permalink in custom loop

I'm using a custom loop to show a selection of products.
The loop works fine and shows the products with the correct title, image and the other stuff.
But the permalink is the URL of the current page.
If I add $post inside the permalink, everything works fine: get_permalink($post)
Here's my current code:
<?php $featured_posts = $products_select; if( $products_select ): ?>
<div>
<ul>
<?php foreach( $featured_posts as $post ): setup_postdata($post); ?>
<?php wc_get_template_part( 'content', 'product' ); ?>
<?php endforeach; ?>
</ul>
<?php wp_reset_postdata(); ?>
</div>
I checked the content of $products_select and saw, that there is no link stored.
Could that be the problem? Is there any way to correct the permalink?
The variable $products_select is the output of a custom field based on relationship field from Advanced Custom Fields. It is stored as post object.
Update
Don't use get_posts() function, instead use a real WP_Query like in the following example:
<?php
$loop = new WP_Query( array(
'post_status' => 'publish',
'post_type' => 'product',
'posts_per_page' => 10,
) );
?>
<div>
<ul><?php
if ( $loop->have_posts() ) :
while ( $loop->have_posts() ) : $loop->the_post();
echo '<pre>ID: '.get_the_id().' | Title: '. get_the_title() . ' | Link: ' . get_permalink() . '</pre>';
wc_get_template_part( 'content', 'product' );
endwhile;
wp_reset_postdata();
endif;?>
</ul>
</div>
This time it will works, without any issue.
An alternative: To avoid this problem, you could use instead WooCommerce [products] shortcode as follows:
<?php
$featured_posts = $products_select; if( $products_select ):
// get a comma separated string of product Ids
$post_ids = implode( ',', wp_list_pluck( $featured_posts, 'ID' ) );
// Use [products] shortcode with the comma separated string of product Ids
echo do_shortcode("[products ids='$post_ids']" ); ?>
</div>
Tested and works.
I also found a soultion that will work with Advanced Custom Fields and keeps the custom order of the relationship field:
<?php
$args = array(
'post_type' => 'product',
'post__in' => $products_select,
'posts_per_page' => 4,
'orderby' => 'post__in'
);
$loop = new WP_Query( $args );
if ( $loop->have_posts() ) : ?>
<div>
<ul>
<?php while ( $loop->have_posts() ) : $loop->the_post(); ?>
<?php wc_get_template_part( 'content', 'product' ); ?>
<?php endwhile; ?>
</ul>
</div>
<?php endif; wp_reset_postdata(); ?>

How to fix: custom categories navigation shows duplicate items

I have a category menu that filters the posts shown in the page. My problem is that instead of having an item per category in the menu, I see duplicates of the same Item. It seems like I have as much duplicates as the number of the posts under that category.
Link to the page where the navigation is: http://www.confesercenti.pistoia.it/connessioni/
You can see it under "Filtra le aziende per settore economico". For example, you will notice "COMUNICAZIONE" is repeated five times.
This is the code:
<div id="filters" class="settore_dropdown_wrapper button-group">
<p>Filtra le aziende per settore economico</p>
<ul id="port-list" class="port-filter">
<li><a class="active" data-filter="*">Tutti</a></li>
<?php
$main_convenzione = new WP_Query(array(
'post_type' => 'azienda',
'meta_key' => 'convenzioni_attive',
'meta_value' => 1
));
if ($main_convenzione->have_posts()) : while($main_convenzione->have_posts()) : $main_convenzione->the_post();
// while($main->have_posts()) : $main->the_post();
global $post;
$post_id = $post->ID;
// $terms_list = get_the_terms( get_the_ID(), 'settore' );
$terms_list = get_the_terms( $post_id, 'settore');
// $args = array(
// 'post_type' => 'azienda', // filter by the post type progetto
// 'taxonomy' => 'settore',
// 'hide_empty' => true
// );
// $terms = get_terms($args); // Get all terms of a taxonomy
foreach ( $terms_list as $term_single ) {
$term_name = $term_single->name;
$term_slug = $term_single->slug; ?>
<li><a data-filter=".<?php echo strtolower(preg_replace('/[^a-zA-Z]+/', '-', $term_name)); ?>">
<?php echo esc_attr($term_name); ?></a></li>
<?php }
endwhile; endif; wp_reset_postdata(); ?>
</ul><!--port-list-->
</div><!--filters-->
As stated above it seems like it shows as much duplicates as the number of the posts under that category. My goal is to have one item per category instead of having a al those duplicates
You need to save the filters you need instead of showing them directly. You can use in_array to check if a value is in your array. Something like would work:
<div id="filters" class="settore_dropdown_wrapper button-group">
<p>Filtra le aziende per settore economico</p>
<ul id="port-list" class="port-filter">
<li><a class="active" data-filter="*">Tutti</a></li>
<?php
$main_convenzione = new WP_Query(array(
'post_type' => 'azienda',
'meta_key' => 'convenzioni_attive',
'meta_value' => 1
));
if ($main_convenzione->have_posts()) : while($main_convenzione->have_posts()) : $main_convenzione->the_post();
global $post;
$terms_list = get_the_terms( $post->ID, 'settore');
$terms = [];
foreach ( $terms_list as $term_single ) {
if(!in_array($term_single->name, $terms)) {
$terms[] = $term_single->name;
};
};
endif;
?>
<?php foreach($terms as $term): ?>
<li><a data-filter=".<?php echo strtolower(preg_replace('/[^a-zA-Z]+/', '-', $term)); ?>"><?php echo esc_attr($term); ?></a></li>
<?php endforeach; wp_reset_postdata(); ?>
</ul><!--port-list-->
</div><!--filters-->

Get the current post category name inside while loop

I created a custom post type "stm_media_gallery"
And three category inside this custom post type.
I want to display category name associated with each post.
<?php $gallery_query = new WP_Query( array('post_type' =>
'stm_media_gallery', 'posts_per_page' => -1) );
if( $gallery_query->have_posts() ) :
while( $gallery_query->have_posts() ) : $gallery_query->the_post(); ?>
--Display post name and its category name
<?php endif; ?>
<?php endwhile; ?>
You just need to put following code inside loop :
<div>
<?php
foreach((get_the_category()) as $category){
echo $category->name."<br>";
echo category_description($category);
}
?>
</div>
Update in existing code
<?php $gallery_query = new WP_Query(
array('post_type' => 'stm_media_gallery',
'posts_per_page' => -1) );
if( $gallery_query->have_posts() ) :
while( $gallery_query->have_posts() ) : $gallery_query->the_post();
$gallery_category = get_the_category( get_the_ID() );
the_title( '<h3>', '</h3>' );
echo "<br>";
<?php foreach ( $gallery_category as $key => $value) { echo $value->category_nicename; } ?>
<?php endif; ?>
<?php endwhile; ?>
You can use the pre-made WordPress function the_category( $separator, $parents, $post_id ) to print the post categories as links.
Further information on the WordPress Codex: Function Reference: the_category
Edit: Print only the names:
$categories = get_the_category();
if ( ! empty( $categories ) ) {
echo esc_html( $categories->name );
}
Put this inside While Loop
global $post;
$postcat = get_the_category( $post->ID );

Wordpress Product-Filter with CPT & Custom Taxonomy

I'm building a Site with Wordpress link to site It's a Site with Custom Post Types (product) and Custom Post Taxonomies (product_category).
On the Category page I have to filter the products by Subcategories.
I found the filterable.js with a tutorial.
My Problem: If I click on any subcategory (Filter-Item) the browser (Chrome and Filezilla) doesn't work anymore.
If I click on the filter the browser says "processing request"
after a long loading time the browser gives me an error.
Here's a screenshot of the Browser error:
http://farbstrakt.com/screenshot.png
I think the problem is about how I change the URL.
I'm searching days for any solution but nothing.
I can't find the error
here's my taxonomy-product_category.php
<div class="container middler" id="demo">
<ul class="filter-wrapper clearfix" id="portfolio-filter">
<?php
$args = array(
'show_count' => false,
'child_of' => get_queried_object()->term_id,
'taxonomy' => 'product_category',
'title_li' =>'',
);
$terms = get_categories($args);
$count = count($terms);
if ( $count > 0 ){
echo '<li class="cl-effect-2"><div><span data-hover="Alle">Alle</span></div></li>';
foreach ( $terms as $term ) {
$termname = strtolower($term->name);
$termname = str_replace(' ', '-', $termname);
$termname = strtolower($term->name);
$termname = str_replace(' ', '-', $termname);
echo '<li class="cl-effect-2">
<div>
<a href="#'.$termname.'">
<span data-hover="'.$term->name.'">'.$term->name.'</span>
</a>
</div>
</li>';
}
}
?>
</ul>
<?php
$loop = new WP_Query(array('post_type' => 'product', 'posts_per_page' => -1));
$count =0;
?>
<div id="portfolio-wrapper">
<ul class="grid effect-2 item-wrapper clearfix filter-all" id="grid">
<?php if ( $loop ) :
while ( $loop->have_posts() ) : $loop->the_post(); ?>
<?php
$terms = get_the_terms( $post->ID, 'product_category' );
if ( $terms && ! is_wp_error( $terms ) ) :
$links = array();
foreach ( $terms as $term )
{
$links[] = $term->name;
}
$links = str_replace(' ', '-', $links);
$tax = join( " ", $links );
else :
$tax = '';
endif;
?>
<?php $infos = get_post_custom_values('_url'); ?>
<li class="<?php echo strtolower($tax); ?> all ">
<div>
<figure>
<?php the_post_thumbnail( array(400, 160) ); ?>
<figcaption><?php the_title(); ?></figcpation>
</figure>
</div>
</li>
<?php endwhile; else: ?>
<p class="no-products">NO products
</p>
</ul>
<?php endif; ?>
and thats the short snippet from the code above where i think there must be the error.
<?php
$terms = get_the_terms( $post->ID, 'product_category' );
if ( $terms && ! is_wp_error( $terms ) ) :
$links = array();
foreach ( $terms as $term )
{
$links[] = $term->name;
}
$links = str_replace(' ', '-', $links);
$tax = join( " ", $links );
else :
$tax = '';
endif;
?>
<?php $infos = get_post_custom_values('_url'); ?>
<li class="<?php echo strtolower($tax); ?> all ">
Would be grateful if you could help me. I have searched a lot and didn't found any solution. I'm a PHP-Newbie. Of course I could use another filter plugin but I want to figure out where's the problem
Thanks
The issue is appending a url with #all means that the browser will look for a element with a id of all . It cant find it on your page, because no element exists with this id.Hence the browser crashes after a few links have been clicked on.
just for reference, a element with a id looks like this:
<div id="someelement" class="not the same thing as id" >content</div>
<div id="anotherelement" class="someelement" >content</div>
In this case, if you append the url of the page with this element on it with #someelement the browser will focus on the first element. This does not look for elements with the class 'someelement'.
If you want to pass query args, you need to use the ?products=all&etc format. But what i think you want to do is actually redirect to a page displaying only the selected term? use /term instead in your href.
Also you are getting a 404 on product_category and any of the terms you had on the page. Part of the issue is you are using $term->name instead of $term->slug which may be different. Did you reset the permalinks when you created the taxonomy?
Also check the settings as described here:
https://codex.wordpress.org/Function_Reference/register_taxonomy
By default WP will create a loop on taxonomy-term.php and archive pages, the loop you run is a second db request and loop so thats extra time added to your server response time. Use the pre_get_posts hook
https://codex.wordpress.org/Plugin_API/Action_Reference/pre_get_posts

Word "Array" is Appearing on Blog Posts Page

I'm getting the word "Array" coming up on my blog POSTS page when I use the below code. I have a feeling that it relates to this line:
I am using a similar template for my PORTFOLIO and NEWS pages where the wording is slightly different on this line ("showportcat" and "shownewscat" instead of "get_the_category") and it should be displaying the categories but instead, the word 'array' is in it's place.
I've tried "showpostcat" but that didnt' work so I wonder if I need to be re-wording it? Or maybe the problem is on another part of the code which I've included below?
<div class="greyblock">
<h4 class="nomar"><?php echo the_title(); ?></h4>
<div class="sep"></div>
<?php echo get_the_category(get_the_ID()); ?>
<div class="clear"></div>
<ul class="blogpost_list columns2">
<?php
$temp = $wp_query;
$wp_query = null;
$wp_query = new WP_Query();
$args = array(
'post_type' => 'post',
'paged' => $paged,
'posts_per_page' => get_option("posts_per_page"),
);
if (isset($_GET['slug'])) {
$args['tax_query']=array(
array(
'taxonomy' => 'postcat',
'field' => 'slug',
'terms' => $_GET['slug']
)
);
}
$wp_query->query($args);
?>
<?php while ( $wp_query->have_posts() ) : $wp_query->the_post();
#We have:
#get_permalink() - Full url to post;
#get_the_title() - Post title;
#get_the_content() - Post text;
#get_post_time('U', true) - unix timestamp
$featured_image = wp_get_attachment_image_src( get_post_thumbnail_id( $post->ID ), 'single-post-thumbnail' );
echo "
<li class='pc'>
<img alt='".get_the_title()."' src='".TIMTHUMBURL."?w=400&h=400&src=".$featured_image[0]."'>
<h4>".get_the_title()."</h4>";
$terms = get_the_terms($post->ID, 'postcat');
if ( $terms && ! is_wp_error( $terms ) ) {
$draught_links = array();
foreach ( $terms as $term ) {
$draught_links[] = $term->name;
}
$on_draught = join( ", ", $draught_links );
}
echo "
<p>".get_the_excerpt()."</p>
<a href='".get_permalink()."' class='read'>Read more</a>
<br class='clear' />
</li>
";
endwhile; ?>
</ul>
</div>
<?php get_pagination() ?>
<?php $wp_query = null; $wp_query = $temp; ?>
How about:
$categories = get_the_category(get_the_ID());
foreach ($categories as $category) {
echo $category;
}
The problem is still there. I'm guessing it relates to the way I am wording one of the below two lines as it is 'showportcat' for portfolios and 'shownewscat' for news but 'showpostcat' doesn't work for posts so I just can't figure it out:
<?php echo get_the_category(get_the_ID()); ?>
**OR**
'taxonomy' => 'postcat',

Categories