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));
Related
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
I'm trying to create a shortcode that outputs my custom taxonomies, separated by a comma, but i want the last comma to be "en" instead of a comma. So like this:
taxonomy, taxonomy, taxonomy en taxonomy
So far i have this:
// Assortiment shortcode
function verlichting_type( ){
$terms = get_the_terms( $post->ID, 'verlichting_type' );
foreach($terms as $term) {
$entry_terms .= $term->name . ', ';
}
$entry_terms = rtrim( $entry_terms, ', ' );
return '<span class="verlichting__type"> ' . $entry_terms . ' </span>';
}
add_shortcode( 'verlichting_type', 'verlichting_type' );
WordPress already have custom printf function with localize the output
So if your site language is Francais means
wp_sprintf_l( '%l', ['Hello', 'world', 'never', 'give', 'up'] )
The above code will output
Hello, world, never, give, et up
For Espanol:
Hello, world, never, give y up
As you noted based on the language the last comma will be added/removed
As I dont have an example of the $terms or $entry_terms variable I had to make up some dummy data, but I think you should be able to extract my example and place it into your code.
I made use of the ternary operator (https://www.php.net/manual/en/language.operators.comparison.php) to determine whether or not the final comma should be ',' or 'en':
<?php
function verlichting_type() {
$entry_terms = "";
$terms = [
(object)['name' => 'taxonomy'],
(object)['name' => 'taxonomy'],
(object)['name' => 'taxonomy'],
(object)['name' => 'taxonomy']
];
echo '<span class="verlichting__type">';
foreach ( $terms as $index => $term) {
$enIndex = sizeof($terms) - 2;
$end = (isset($terms[$enIndex]) && $index == $enIndex ? ' en ' : ', ');
$entry_terms .= $term->name . $end;
}
$entry_terms = rtrim( $entry_terms, ', ' );
return $entry_terms . '</span>';
}
This outputs:
<span class="verlichting__type">taxonomy, taxonomy, taxonomy en taxonomy</span>
This should work with any array length, e.g. if $terms only has 2 elements:
<span class="verlichting__type">taxonomy en taxonomy</span>
Or 1 element:
<span class="verlichting__type">taxonomy</span>
I'm trying to sort names in alphabetical order after a reverse array.
It's a code done for ordering last name/first name in right order.
A few bugs, (like with names with middle names) but it works except the sorting.
Here is the code:
<?php
$terms = get_terms( 'pa_artist' );
if ( ! empty( $terms ) && ! is_wp_error( $terms ) ){
echo '<ul class="artists">';
foreach ( $terms as $term ) {
$array = explode(" ", $term->name);
if ($array[3]) {
$array[3] = strtoupper($array[3]);
$array[3] = "<strong>".$array[3]."</strong>";
}
elseif ($array[2]) {
$array[2] = strtoupper($array[2]);
$array[2] = "<strong>".$array[2]."</strong>";
} elseif ($array[1]) {
$array[1] = strtoupper($array[1]);
$array[1] = "<strong>".$array[1]."</strong>";
} else {
$array[0] = strtoupper($array[0]);
$array[0] = "<strong>".$array[0]."</strong>";
}
$rarray = array_reverse($array);
sort($rarray);
echo '<li>' . implode(" ", $rarray) . '</li>';
}
echo '</ul>';
}
For now the names are ordered as if the reverse was never done.
Some examples, at first it showed like this:
Auguste Renoir
Pablo Picasso
Paul Gauguin
After the reverse and If strings, it's like this:
RENOIR Auguste
PICASSO Pablo
GAUGUIN Paul
When i need it:
GAUGUIN Paul
PICASSO Pablo
RENOIR Auguste
I tried every sort fonction, can't make it work… I can't find a way to sort after a reverse array, is it even possible?
It's for a list of names builded with attributes on wordpress/woocommerce.
I already asked that question, got answers that didn't work unfortunately…
There is Something like 150 names that needs ordering.
I'm willing to pay for this, but no-one is interested because it doesn't require much time so won't pay much! (Only got request to redo the whole website…)
Try the following:
$terms = get_terms( [ 'taxonomy' => 'pa_artist', 'hide_empty' => false ] );
$names_html = $terms_data = [];
if ( ! empty( $terms ) && ! is_wp_error( $terms ) ){
// 1st Loop: Loop through the terms
foreach ( $terms as $term ) {
$fragments = explode( ' ', $term->name );
if( sizeof($fragments) > 1 ) {
// Manipulate and format the term name
$fragment = '<strong>' . strtoupper($fragments[1]) .'</strong>';
$new_term = $fragment . ' ' . $fragments[0];
// 1st array: We set each formatted term name
$names_html[] = $new_term;
// 2nd array: We set the related data as the Url and the original term name
$terms_data[$new_term] = array(
'link' => get_term_link( $term ),
'name' => $term->name,
);
}
}
// Sort the formatted term names
sort($names_html);
// Output
echo '<ul class="artists">';
// 2nd Loop: Loop through the sorted formatted term names
foreach ( $names_html as $name_html ) {
$link = $terms_data[$name_html]['link'];
$title = sprintf( __( 'View all post filed under %s', 'my_localization_domain' ), $terms_data[$name_html]['name'] );
echo '<li>' . $name_html . '</li>';
}
echo '</ul>';
}
Tested and works.
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
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.