Separate categories by "," [duplicate] - php

This question already has answers here:
Removing last comma from a foreach loop
(9 answers)
Closed 17 days ago.
When separating the categories, the "," appears in the last category. e.g
Category1, Category2,
I am using this function.
// MultiNetwork
function MultiNetwork() {
global $post;
$terms = get_the_terms( $post->ID, 'networks');
$count = 0;
foreach ( $terms as $term ){
if ($count <= 1) {
$firstTerm = $term;
$term_link = get_category_link($firstTerm->term_id);
echo '<span class="network">' . $firstTerm->name . '</span>',',';
$count++;
}
}
}
I would like it to stay
Category1, Category2
Intente usando explode e implode.

For your case, simply only echo the "," if that is not the last item.
For example, remove ,',' and then add the following line:
if ($count < count($terms)) { echo "," ;}
So Change these two lines:
echo '<span class="network">' . $firstTerm->name . '</span>',',';
$count++;
to
echo '<span class="network">' . $firstTerm->name . '</span>';
$count++;
if ($count < count($terms)) { echo "," ;}

You can you use below code to resolve ", " problem.
$terms = get_terms([
'taxonomy' => 'networks',
'hide_empty' => false,
]);
$count = 0;
foreach ( $terms as $term ){
if ($count <= 1) {
$cat[] = $term->name;
$count++;
}
}
$data = implode(', ', $cat);
I have tried this code for the same. please look for the screenshot I'm attaching below.
Screen shot of result

Related

Changing Wordpress function

I'm using a Wordpress function to enter the word 'and' before the last term in calling a term list, like this:
function TermList($taxonomy = 'markup') {
global $post;
$term_list = '';
$terms = get_the_terms($post->ID, $taxonomy);
$n = 1;
if ($terms) {
foreach($terms as $term) {
if ($n < count($terms)) {
$term_list .= $term->name . ', ';
} else {
$term_list = rtrim($term_list, ', ') . ' and ' . $term->name;
}
++$n;
}
}
$term_list = rtrim($term_list, ', ');
return $term_list;
}
I want to change this function so it only displays 5 terms and chooses those 5 terms randomly from all available terms. I don't know where to start. Who can point me in the right direction?
Using array_rand
You could use array_rand in php to select a random element from an array, here is the official documentation from php.net
and your code will be something like:
for($i=0 ; $i<5 ; $i++){
$term_list .= $terms [array_rand($terms )] . ', ';
}
$term_list = rtrim($term_list, ', ');
// replace the last comma with 'and'
$portion = strrchr($term_list , ',');
$term_list = str_replace($portion, (" and" . substr($portion, 1, -1)), $term_list );
Using shuffle and array_slice
Another solution to pick up random elements from an array could be using shuffle to randomly shuffle the elements of an array and then using array_slice to pick up certain elements.
Here is an example of code:
shuffle($terms );
print_r(array_slice($terms , 0, 3));

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

Need help adjusting PHP code, need commas after all terms except the last

I don't understand PHP very well but I'm trying to adjust this code below. I want the terms to all have a comma after them except for the last one. Right now the output looks like this:
Audience: Pre-School, High School, Adult,
However I need it to look like this:
Audience: Pre-School, High School, Adult
I realize there are similar questions out there that already answer this question, but since I am clueless when it comes to PHP I don't know how to incorporate those solutions with this code I already have. Can anyone help?
Thanks in advance!
<?php
$terms = get_terms( 'Audience' );
if ( ! empty( $terms ) && ! is_wp_error( $terms ) ){
echo '<p><strong>Audience:</strong> ';
foreach ( $terms as $term ) {
echo '' . $term->name . ', ';
}
echo '</p>';
}
?>
You can do this with the amazingly convenient function implode:
echo implode(", ", $terms);
You can either count during the foreach loop;
$i = 1;
foreach ( $terms as $term ) {
echo '' . $term->name;
if ($i < count($terms)) {
echo ', ';
}
$i++;
}
Or you can simply load it all into a variable and then crop the last comma and space off.
$output = '';
foreach ( $terms as $term ) {
$output .= $term->name . ', ';
}
echo substr($output,0,-2);
Save the line to a variable during the loop and then remove the last character before printing it. Not the most elegant solution but it works
<?php
$terms = get_terms( 'Audience' );
if ( ! empty( $terms ) && ! is_wp_error( $terms ) ){
echo '<p><strong>Audience:</strong> ';
$len = count($terms);
$i = 0;
foreach ( $terms as $term ) {
i++;
echo '' . $term->name . ($i < $len ? ', ' : '');
}
echo '</p>';
}
?>
You can use trim() http://ar2.php.net/trim
$string = '';
$terms = get_terms( 'Audience' );
if ( ! empty( $terms ) && ! is_wp_error( $terms ) ){
$string .= '<p><strong>Audience:</strong> ';
foreach ( $terms as $term ) {
$string .= '' . $term->name . ', ';
}
$string .= "</p>";
echo trim($string, ',');
}
?>
You can use it to remove strings from the start and end of your whole string.

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;
?>

Get Children Terms from an Array of ID's?

I am using this code to post a list of all children terms for my taxonomy called 'location'
<?php
$termID = 10;
$taxonomyName = "location";
$termchildren = get_term_children( $termID, $taxonomyName );
echo '<ul>';
foreach ($termchildren as $child) {
$term = get_term_by( 'id', $child, $taxonomyName );
echo '<li>' . $term->name . '</li>';
}
echo '</ul>';
?>
Currently the code is using term id 10 and getting the children for that and displaying in a list.
However I want to add multiple term id's and display a list of all the children of the id's I add.
My id's are 4,6,8,10,14,18,22
Looking for some help to figure out how to do this?
Cheers
I figured out the answer to my own question. using get_terms will get all the terms retured, so there is no need to specify individual id's of my terms.
My code is
<?php
$args = array( 'taxonomy' => 'location' );
$terms = get_terms('location', $args);
$count = count($terms); $i=0;
if ($count > 0) {
$cape_list = '<p class="location-archive">';
foreach ($terms as $term) {
$i++;
$term_list .= '<li><span class="feature">' . $term->name . '</li>';
if ($count != $i) $term_list .= ' ยท '; else $term_list .= '</p>';
}
echo '<ul class="list">';
echo $term_list;
echo '</ul>';
}
?>

Categories