print a term but without linking it - php

I am trying to print a nodes term, the code below works and it specifies which vocab ID. But I don't want the term to link to the term list. How do I remove the link. And can this be simplified and without the ul list?
<?php if ( arg(0) == 'node' && is_numeric(arg(1)) ) {
$node = node_load(arg(1));
$vid = 7;
$terms = taxonomy_node_get_terms_by_vocabulary($node, $vid);
if ($terms) {print '<ul>'; foreach ($terms as $term)
{print '<li>'.l($term->name,'taxonomy/term'.$term->tid).'</li>'; }
print '</ul>';
}}?>

simply remove l() function
<?php if ( arg(0) == 'node' && is_numeric(arg(1)) ) {
$node = node_load(arg(1));
$vid = 7;
$terms = taxonomy_node_get_terms_by_vocabulary($node, $vid);
if ($terms) {print '<ul>'; foreach ($terms as $term)
{print '<li>'.$term->name.'</li>'; }
print '</ul>';
}}?>

Related

implode terms to class

I'm stuck getting terms into a list and class at the same time. I can return the list no problem, but I need the slug to also be the class.
Here is my code
$terms = get_the_terms($post->ID, 'events17groups' );
if ($terms && ! is_wp_error($terms)) :
$tslugs_arr = array();
foreach ($terms as $term) {
$tslugs_arr[] = $term->slug;
}
endif;
$listclass = implode(" ", $tslugs_arr);
$listgroup = "<li class='$listclass'>" . implode("</li><li
class='$listclass'>", $tslugs_arr) . "</li>";
echo "<ul class='eventgroup'>$listgroup</ul>";
This produces the following HTML
<ul class="eventgroup"><li class="exhibitions home">exhibitions</li><li
class="exhibitions home">home</li></ul>
So what I want is
<ul class="eventgroup"><li class="exhibitions">exhibitions</li><li
class="home">home</li></ul>
Any suggestions?
Why not use a simple readable foreach:
$listgroup = '';
foreach ($tslugs_arr as $item) {
$listgroup .= '<li class="' . $item . '">' . $item . '</li>';
}
echo "<ul class='eventgroup'>$listgroup</ul>";
Have you tried like this?
$terms = get_the_terms($post->ID, 'events17groups' );
if ($terms && ! is_wp_error($terms)) :
$tslugs_arr = array();
foreach ($terms as $term) {
$tslugs_arr[] = $term->slug;
}
endif;
$listclass = implode(" ", $tslugs_arr);
$listgroup = "<li class='".tslugs_arr[0]."'>" . implode("</li><li
class='".tslugs_arr[1]."'>", $tslugs_arr) . "</li>";
echo "<ul class='eventgroup'>$listgroup</ul>";
If you want to do a fancy one-liner then try out:
<?php
$terms = get_the_terms($post->ID, 'events17groups' );
if ($terms && ! is_wp_error($terms)) :
$tslugs_arr = array();
foreach ($terms as $term) {
$tslugs_arr[] = $term->slug;
}
endif;
echo "<ul class='eventgroup'>".implode('', array_map( function( $tslug ){ return "<li class='$tslug'>$tslug</li>"; }, $tslugs_arr ) )."</ul>";

Wordpress: How to add commas in this get_the_terms function

I am using this function:
// Get terms for post
$terms = get_the_terms($post->ID, 'skills');
if($terms != null) {
foreach($terms as $term) {
echo $term->name . ", ";
unset($term);
}
}
However I see the terms as term1, term2, term3, (with also a comma at the end), how can I show the terms with commas but without that comma when is not necessary?
Instead of echoing all the variables during your loop, you should store them all to an array and then use the implode() function to echo them all with the formatting you desire.
// Get terms for post
$terms = get_the_terms($post->ID, 'skills');
if($terms != null) {
$output = array();
foreach($terms as $term) {
$output[] = $term->name;
unset($term);
}
echo implode(", ", $output)
}
Don't want to use an array or variable? There is another solution. Just check if you are currently on the very last element in the array during your loop.
// Get terms for post
$terms = get_the_terms($post->ID, 'skills');
if($terms != null) {
end($terms);
$endKey = key($terms);
foreach($terms as $key => $term) {
echo $key != $endKey? $term->name.", " : $term->name;
unset($term);
}
}
I added $key to the foreach loop so you can compare against that. You can get the final key of the array by doing end($array) and then using key() to get the actual key.
If you dont want to use array use following:
$terms = get_the_terms($post->ID, 'skills');
$string = "";
if($terms != null) {
foreach($terms as $term) {
$string .= $term->name . ", ";
unset($term);
}
}
echo trim($string, ", ");
You can use rtrim. (from php.net : Strip whitespace (or other characters) from the end of a string)
// Get terms for post
$terms = get_the_terms($post->ID, 'skills');
if($terms != null) {
$stringFinal = "";
foreach($terms as $term) {
$stringFinal = $term->name . ", ";
}
$stringFinal = rtrim($stringFinal, ', ')
}
echo $stringFinal;
Omitting all checks, this can be reduced to one line.
// Get terms for post
$terms = get_the_terms($post->ID, 'skills');
echo implode(", ", array_map(function($T) {return is_a($T, 'WP_Term') ? $T->name : false; }, $terms ))
Works like array_column but with object

Woocommerce breadcrumbs multiple categories

I have e commerce website in wordpress. There are lot of product in it & many product comes under multiple categories like 600 mah Power bank is comes under automobile, IT, media etc. My problem is when i go to the detail of a product there it by default pick up only one category no matter if go through IT category at the end it shows me automobile like this Home / Shop / industry / Automobile / 600 mah Power Bank. But i went to this product via IT so it should show me like this Home / Shop / industry / IT / 600 mah Power Bank.
How can iget path where i come from previous page?
if you are using Woocommerce you can use the following directly, if not it will need adapting but you get the idea:
if (get_post_type() == 'product' && is_single() && ! is_attachment()) {
echo $prepend;
if ($terms = get_the_terms($post->ID, 'product_cat')) {
$referer = wp_get_referer();
foreach ($terms as $term) {
$referer_slug = (strpos($referer, $term->slug));
if ($referer_slug == true) {
$category_name = $term->name;
$ancestors = get_ancestors($term->term_id, 'product_cat');
$ancestors = array_reverse($ancestors);
foreach ($ancestors as $ancestor) {
$ancestor = get_term($ancestor, 'product_cat');
if (! is_wp_error($ancestor) && $ancestor) {
echo $before . '' . $ancestor->name . '' . $after . $delimiter;
}
}
echo $before . '' . $category_name . '' . $after . $delimiter;
}
}
}
echo $before . get_the_title() . $after;
}
The main bulk of the work here is done by wp_get_referer which gets the referring URL of the product your visitor has navigated to. The rest of the code checks if a valid category is contained within the URL and uses it in the breadcrumb.
See Jonathon Js post here for more information http://www.cryoutcreations.eu/forums/t/wrong-breadcrumbs-displayed
Updated answer for anyone still encountering this issue on a newer version of WooCommerce, this solution worked for me on WooCommerce 3.5.4.
This code should be placed inside the following file path (i.e. a child theme)
/wp-content/themes/your-child-theme/woocommerce/global/breadcrumb.php
It will override the default WooCommerce breadcrumb code.
http://pastebin.com/raw/bemM8ZNF
/**
* Shop breadcrumb
*
* This template can be overridden by copying it to yourtheme/woocommerce/global/breadcrumb.php.
*
* HOWEVER, on occasion WooCommerce will need to update template files and you
* (the theme developer) will need to copy the new files to your theme to
* maintain compatibility. We try to do this as little as possible, but it does
* happen. When this occurs the version of the template file will be bumped and
* the readme will list any important changes.
*
* #see https://docs.woocommerce.com/document/template-structure/
* #author WooThemes
* #package WooCommerce/Templates
* #version 2.3.0
* #see woocommerce_breadcrumb()
if ( ! defined( 'ABSPATH' ) ) {
exit;
}
if ( $breadcrumb ) {
echo $wrap_before;
if ( is_single() && get_post_type() == 'product' ) {
echo $prepend;
if ( $terms = get_the_terms( $post->ID, 'product_cat' ) ) {
$referer = wp_get_referer();
$printed = array();
foreach( $terms as $term){
if(in_array($term->id, $printed)) continue;
$referer_slug = (strpos($referer, '/'.$term->slug.'/'));
if(!$referer_slug==false){
$printed[] = $term->id;
$category_name = $term->name;
$ancestors = get_ancestors( $term->term_id, 'product_cat' );
$ancestors = array_reverse( $ancestors );
foreach ( $ancestors as $ancestor ) {
$ancestor = get_term( $ancestor, 'product_cat' );
if ( ! is_wp_error( $ancestor ) && $ancestor )
echo $before . '' . $ancestor->name . '' . $after . $delimiter;
}
echo $before . '' . $category_name . '' . $after . $delimiter;
}
}
}
echo $before . get_the_title() . $after;
} else {
foreach ( $breadcrumb as $key => $crumb ) {
echo $before;
if ( ! empty( $crumb[1] ) && sizeof( $breadcrumb ) !== $key + 1 ) {
echo '' . esc_html( $crumb[0] ) . '';
} else {
echo esc_html( $crumb[0] );
}
echo $after;
if ( sizeof( $breadcrumb ) !== $key + 1 ) {
echo $delimiter;
}
}
}
echo $wrap_after;
}
C/O: Joris Witteman
I reworked the code a little bit to account for a primary category and a referred one, having infinite parents.
I used the breadcrumb filter as it is quite clean, directly in the single product template, but in case you need it elsewhere you can use the single conditional.
function breadcumbs_referred_or_primary ($main, $terms)
{
// Our primary term is 520 (hardcoded)
$referer = wp_get_referer();
$referredTerm = -1;
$referredTermIndex = -1;
$primaryTermId = 520; // hardcoded
$primaryTermIndex = -1;
foreach($terms as $key => $term) {
if ($referredTerm != -1) break; // we found it in a previous iteration!
$ancestors = get_ancestors( $term->term_id, 'product_cat');
array_unshift($ancestors, $term->term_id);
if ($primaryTermIndex == -1 && in_array($primaryTermId, $ancestors)) $primaryTermIndex = $key;
foreach ($ancestors as $ancestor) {
if($referredTerm != -1) break 2; // we found it in a previous iteration!
$ancestor = get_term( $ancestor, 'product_cat' );
$referer_slug = (strpos($referer, '/'.$ancestor->slug.'/'));
if (!$referer_slug==false) { // it's found in the current level
$referredTerm = $term->term_id;
$referredTermIndex = $key;
}
}
}
// we return either the browsed terms or the primary term
if ($referredTermIndex != -1) {
return $terms[$referredTermIndex];
} else {
return $terms[$primaryTermIndex];
}
}
add_filter('woocommerce_breadcrumb_main_term', 'breadcumbs_referred_or_primary', 10, 2);
My solution is:
if (!empty($breadcrumb)) {
echo $wrap_before;
if (is_single() && get_post_type() == 'product') {
$breadcrumb_diff = [];
$breadcrumb_diff[] = $breadcrumb[0];
if ($terms = get_the_terms($post->ID, 'product_cat')) {
$referer = wp_get_referer();
$site_url = site_url();
$referer = str_replace($site_url . '/zoomagazin/', '', $referer);
$referer_array = explode('/', $referer);
foreach ($referer_array as $term_slug) {
$get_term_by_slug = get_term_by('slug', $term_slug, 'product_cat');
$breadcrumb_diff[] = [$get_term_by_slug->name, get_term_link($term_slug, 'product_cat')];
}
$breadcrumb_diff[]= $breadcrumb[count($breadcrumb) - 1];
foreach ($breadcrumb_diff as $key => $crumb) {
echo $before;
if (!empty($crumb[1]) && sizeof($breadcrumb_diff) !== $key + 1) {
echo '' . esc_html($crumb[0]) . '';
} else {
echo esc_html($crumb[0]);
}
echo $after;
if (sizeof($breadcrumb) !== $key + 1) {
echo $delimiter;
}
}
}
} else {
foreach ($breadcrumb as $key => $crumb) {
echo $before;
if (!empty($crumb[1]) && sizeof($breadcrumb) !== $key + 1) {
echo '' . esc_html($crumb[0]) . '';
} else {
echo esc_html($crumb[0]);
}
echo $after;
if (sizeof($breadcrumb) !== $key + 1) {
echo $delimiter;
}
}
}
echo $wrap_after;
}

Getting no more than 2 categories shown and last one to remove ending slash

I am trying to show at most 2 categories per post in wordpress and managed to do so, just that don't know how could I detect the second one.
<?php
while ( have_posts() ) : the_post();
$terms = get_terms( 'directory_categories', 'orderby=name&hide_empty=1&hierarchical=0' );
// I am getting the categories
$i = 0;
$len = count($terms); // counting the categories
foreach($terms as $term) {
// terms is an array of objects (http://codex.wordpress.org/Function_Reference/get_terms)
$i++;
if ($i < 3) {
//if it reached second loop then displays with '/'
$array[] = $term->name;
$limit = count($array);
?>
<?php echo $term->name; ?>/
<?php
// else if it reached second loop and second loop is 2 then it should omit the slash
} elseif($i < 3 && i == 2) { ?>
<?php echo $term->name; ?>
<?php } else { } ?>
<?php } ?> <!-- end foreach -->
endwhile;
?>
CURRENT OUTPUT is
Category 1 / Category 2/
EXPECTED OUTPUT is without the ending slash
Category 1 / Category 2
I am very sure that logic is wrong, please let me know where am I mistaking.
Use this code instead (i've put comments so you can easily maintain it):
<?php
while ( have_posts() ) : the_post();
$tax = 'directory_categories'; // your taxonomy
$total = 2; // number of categories to show for each post
$sep = ' / '; // separator you want to use
$terms = get_the_terms(get_the_ID(), $tax);
if ($terms && !is_wp_error($terms)) {
$terms = array_values($terms);
foreach ($terms as $key => $term) {
echo '' . $term->name . '';
if ($key < $total - 1 && count($terms) >= $total) {
echo $sep;
}
if ($key == $total - 1) {
break;
}
}
}
endwhile;
?>

Loop through and compare

I have this code here the product tags can be animals, life or market. What I am trying to do is separate their list, but this code creates a new ul for every tag after animals and I do not know why, can anyone help?:
<?php
$versionvalues = get_the_terms( $product->id, 'product_tag');
if($versionvalues){
$previousTag = 'animals';
foreach ( $versionvalues as $versionvalue ) {
$currentTag = $versionvalue->name;
if($currentTag != $previousTag){
echo '</ul><ul class="products" style="text-align:center;">';
$previousTag = $currentTag;
}else{
$previousTag = $currentTag;
}
}
}
?>
Maybe wordpress doesn't allow me to put get_the_terms values into a variable. I did an echo of the $previousTag in the loop is keeps returning animals.
I have realized that is code is inside my woocommerce loop for my products, so $versionvales gets updated for each product and $previousTag will also reset to animals for each product.
You need to initialize $previousTag = 'animals' before entering the foreach loop, otherwise it will be reinitialized to equal 'animals' at the start of each iteration:
if($versionvalues){
$previousTag = 'animals';
foreach ( $versionvalues as $versionvalue ) {
.....
}
}
You reinitialized the $previousTag in each loop.
<?php
$versionvalues = get_the_terms( $product->id, 'product_tag');
if($versionvalues){
$previousTag = 'animals';
foreach ( $versionvalues as $versionvalue ) {
$currentTag = $versionvalue->name;
if($currentTag != $previousTag){
echo '</ul><ul class="products" style="text-align:center;">';
$previousTag = $currentTag;
} else {
$previousTag = $currentTag;
}
}
}
?>
just do not overwrite the variable each time
$versionvalues = get_the_terms( $product->id, 'product_tag');
if($versionvalues){
$previousTag = 'animals';
foreach ( $versionvalues as $versionvalue ) {
$currentTag = $versionvalue->name;
if($currentTag != $previousTag){
echo '</ul><ul class="products" style="text-align:center;">';
$previousTag = $currentTag;
}else{
$previousTag = $currentTag;
}
}
}
?>

Categories