How to add "else" to "foreach"? - php

i don't know how to add else to foreach!
here is my code:
<?php $terms = get_the_terms( $post->ID , 'actor' );
foreach ( $terms as $term ) {
$term_link = get_term_link( $term, 'actor' );
if( is_wp_error( $term_link ) )
continue;
echo '' . $term->name . '';
}
?>

You could try something similar:
<?php
$terms = get_the_terms( $post->ID , 'actor' );
if ($terms) {
foreach ( $terms as $term ) {
$term_link = get_term_link( $term, 'actor' );
if ( is_wp_error( $term_link ) )
continue;
echo '' . $term->name . '';
}
} else {
// do the work for else
}
?>

For sake of completeness, there is an old RFC (10 years old) that proposes loop+else:
https://wiki.php.net/rfc/loop_else

foreach is a loop. else is part of a conditional statement. It looks like you just want a conditional inside your loop. This would just be a standard conditional.
if ($a > $b) {
echo "a is greater than b";
} else {
echo "a is NOT greater than b";
}
I assume you want to break the loop in that case.

Related

PHP: count(): Parameter must be an array or an object that implements Countable

I am new to php. I have these errors appearing on some Wordpress pages.
Warning: count(): Parameter must be an array or an object that implements Countable in /www/tastingvictoria_289/public/wp-content/themes/astra-child/template-parts/content-single.php on line 38
Warning: Invalid argument supplied for foreach() in /www/tastingvictoria_289/public/wp-content/themes/astra-child/template-parts/content-single.php on line 40
This is the related code.
<?php $terms = get_the_terms( $post->ID , 'category' );
$total = count($terms); // 38
$i=0;
foreach ( $terms as $term ) {
if($term->slug != "featured-post"){
$i++;
$term_link = get_term_link( $term, 'category' );
if( is_wp_error( $term_link ) )
continue;
echo '<p class="category"><span><a class="" href="' . $term_link . '">' . $term->name . '</a></span></p>';
if ($i != $total) echo ' ';
}
}
?>
Any explanation?
As the error message, the $term parameter that you pass into count() function is not countable (in some case - eg, the post id is not exit).
To fix this, please change your code into:
<?php $terms = get_the_terms( $post->ID , 'category' );
if(is_array($terms)){
$total = count($terms); // 38
$i=0;
foreach ( $terms as $term ) {
if($term->slug != "featured-post"){
$i++;
$term_link = get_term_link( $term, 'category' );
if( is_wp_error( $term_link ) )
continue;
echo '<p class="category"><span><a class="" href="' . $term_link . '">' . $term->name . '</a></span></p>';
if ($i != $total) echo ' ';
}
}
}
?>
Convert the $terms to an array for getting valid result of count($terms).
get_the_terms() returns Array of WP_Term objects on success, false if there are no terms or the post does not exist, WP_Error on failure.
May be the terms not exists. Try following:
$terms = get_the_terms( $post->ID , 'category' );
if ( $terms && ! is_wp_error( $terms ) ) :
$total = count($terms);
$i=0;
foreach ( $terms as $term ) {
if($term->slug != "featured-post"){
$i++;
$term_link = get_term_link( $term, 'category' );
if( is_wp_error( $term_link ) )
continue;
echo '<p class="category"><span><a class="" href="' . $term_link . '">' . $term->name . '</a></span></p>';
if ($i != $total) echo ' ';
}
}
endif;
Mainly the get_the_terms() function behind code like this
function get_the_terms( $post, $taxonomy ) {
$post = get_post( $post );
if ( ! $post ) {
return false;
}
$terms = get_object_term_cache( $post->ID, $taxonomy );
if ( false === $terms ) {
$terms = wp_get_object_terms( $post->ID, $taxonomy );
if ( ! is_wp_error( $terms ) ) {
$term_ids = wp_list_pluck( $terms, 'term_id' );
wp_cache_add( $post->ID, $term_ids, $taxonomy . '_relationships' );
}
}
/**
* Filters the list of terms attached to the given post.
*
* #since 3.1.0
*
* #param WP_Term[]|WP_Error $terms Array of attached terms, or WP_Error on failure.
* #param int $post_id Post ID.
* #param string $taxonomy Name of the taxonomy.
*/
$terms = apply_filters( 'get_the_terms', $terms, $post->ID, $taxonomy );
if ( empty( $terms ) ) {
return false;
}
return $terms;
}
In this case, you can see if there is no post then it'll return false, and if the function returns false then your code will be like this:
<?php $terms = get_the_terms( $post->ID , 'category' );
$total = count($terms = false); // if there is no post
$i=0;
foreach ( false as $term ) { //if there is no post
if($term->slug != "featured-post"){
$i++;
$term_link = get_term_link( $term, 'category' );
if( is_wp_error( $term_link ) )
continue;
echo '<p class="category"><span><a class="" href="' . $term_link . '">' . $term->name . '</a></span></p>';
if ($i != $total) echo ' ';
}
}
?>
Note: the count() function accept an array or object and the foreach() function accept iterable_expression as well. That is why you're getting the warnings.
So, in that case, you can check the return output of the get_the_terms() function like this:
<?php $terms = get_the_terms( $post->ID , 'category' );
if(is_iterable($terms)){
$total = count($terms); // 38
$i=0;
foreach ( $terms as $term ) {
if($term->slug != "featured-post"){
$i++;
$term_link = get_term_link( $term, 'category' );
if( is_wp_error( $term_link ) )
continue;
echo '<p class="category"><span><a class="" href="' . $term_link . '">' . $term->name . '</a></span></p>';
if ($i != $total) echo ' ';
}
}
}else{
//do something
}
?>
Thank you

adding comma if more than one item value from custom tag

Here is my code - I would to modify. i added "echo ".&nbsp";" which adds a space and full stop after every value. However it will be added even if a value is not more than one. I would like modify code to put a comma and space only if the value is more than one. Thanks
$terms = get_the_terms( $post->ID , 'book-author' );
foreach ( $terms as $term ) {
$term_link = get_term_link( $term, 'book-author' );
if( is_wp_error( $term_link ) )
continue;
echo '' . $term->name . '';
echo ".&nbsp";
}
?>
Put all your strings in an array, then use implode() to combine them with a delimiter.
$terms = get_the_terms( $post->ID , 'book-author' );
$links = [];
foreach ( $terms as $term ) {
$term_link = get_term_link( $term, 'book-author' );
if( !is_wp_error( $term_link ) ) {
$links[] = '' . $term->name . '';
}
}
echo implode('. ', $links);

Show Woocommerce subcategories on single page by their parents slug or ID

I am trying to add Publisher, Topic and Author to a Single Product with help of categories/subcategories. This is how it looks after hours of coding/and copying (very fresh with WooCommerce tbh)
This is what I am getting, but it shows ALL subcategories, not only the ones associated to the Product, this is the code I am using
function get_product_subcategories_list( $category_slug ){
$terms_html = array();
$taxonomy = 'product_cat';
// Get the product category (parent) WP_Term object
$parent = get_term_by( 'slug', $category_slug, $taxonomy );
// Get an array of the subcategories IDs (children IDs)
$children_ids = get_term_children( $parent->term_id, $taxonomy );
// Loop through each children IDs
foreach($children_ids as $children_id){
$term = get_term( $children_id, $taxonomy ); // WP_Term object
$term_link = get_term_link( $term, $taxonomy ); // The term link
if ( is_wp_error( $term_link ) ) $term_link = '';
// Set in an array the html formated subcategory name/link
$terms_html[] = '' . $term->name . '';
}
return '<span class="subcategories-' . $category_slug . '">' . implode( ', ', $terms_html ) . '</span>';
}
add_action('woocommerce_single_product_summary','monolith_cat_scan', 31);
function monolith_cat_scan() {
echo '<p>Topic : ';
echo get_product_subcategories_list( 'topics' );
echo '</p>';
echo '<p>Publisher : ';
echo get_product_subcategories_list( 'publishers' );
echo '</p>';
echo '<p>Author: ';
echo get_product_subcategories_list( 'authors' );
echo '</p>';
}
But I can't get the whole thing to work like I want to and get the subcategories of the Single Product, in this example only Spirituality, SOUNDS TRUE INC (only sub cat in Publishers), and Allan Watts should be there.
I'd appreciate every help!
I got a working code (it doesn't look beautiful I know but it's the best I could do and it does the trick.
add_action('woocommerce_single_product_summary','monolith_cat_scan', 31);
function monolith_cat_scan() {
global $post;
$cats = get_the_terms( $post->ID, 'product_cat' );
if ( ! empty( $cats ) ) {
foreach ( $cats as $term ) {
if( $term->parent == 30 ) {
echo '<p>Topic : ' . $term->name . '';
}
}
}
}
add_action('woocommerce_single_product_summary','monolith_cat_scan2', 32);
function monolith_cat_scan2() {
global $post;
$cats = get_the_terms( $post->ID, 'product_cat' );
if ( ! empty( $cats ) ) {
foreach ( $cats as $term ) {
if( $term->parent == 31 ) {
echo '<p>Author : ' . $term->name . '';
}
}
}
}
add_action('woocommerce_single_product_summary','monolith_cat_scan3', 33);
function monolith_cat_scan3() {
global $post;
$cats = get_the_terms( $post->ID, 'product_cat' );
if ( ! empty( $cats ) ) {
foreach ( $cats as $term ) {
// If parent cat ID = 116 echo subcat name...
if( $term->parent == 32 ) {
echo '<p>Publisher : ' . $term->name . '';
}
}
}
}

Current taxonomy item in custom taxonomy term page

I've got a custom taxonomy called trailer_type with terms long and short. When visiting my_site/trailers/short (a page powered by template taxonomy-trailer_type.php) I display my taxonomy terms this way:
$terms = get_terms( 'trailer_type' );
if ( ! empty( $terms ) && ! is_wp_error( $terms ) ) {
echo '<ul>';
foreach ( $terms as $term ) {
echo '<li>' . $term->name . '</li>';
}
echo '</ul>';
}
Works well but is there a simple way to add a "current" class? For example if I'm on the "long" page, I'd need "long" to have "current" class in this menu.
You need to look at the queried object. There's several ways to do it, here's what I tend to use: $wp_query->queried_object - this returns, as the name implies, the queried object.
In your case, something like this should work:
$curTerm = $wp_query->queried_object;
$terms = get_terms( 'trailer_type' );
if ( ! empty( $terms ) && ! is_wp_error( $terms ) ) {
echo '<ul>';
foreach ( $terms as $term ) {
$classes = array();
if ($term->name == $curTerm->name)
$classes[] = 'current';
echo '<li class="'. implode(' ',$classes) .'">' . $term->name . '</li>';
}
echo '</ul>';
}
I'm setting the classes to an array simply for future expansion. You could set it to a string right away as well.
Try using
get_query_var( 'term' )
and check
if ($term->name == get_query_var( 'term' )){
//make something
}

Getting Wordpress category name from post ID not working

The problem is that I cannot display the category of a post:
http://screencast.com/t/hdQjpSV0Q
I have the following code in a function.php file:
// GET FEATURED IMAGE
function ST4_get_featured_image($post_ID) {
$custom_meta = get_post_custom(get_the_ID());
return $custom_meta["lumen_portfolio_preview_image_image"][0];
}
add_filter('manage_posts_columns', 'ST4_columns_head');
add_action('manage_posts_custom_column', ('ST4_columns_content'), 10, 2);
// ADD NEW COLUMN
function ST4_columns_head($defaults) {
$defaults['featured_image'] = 'Featured Image';
$defaults['categories_portfolio'] = 'Category';
return $defaults;
}
// SHOW THE FEATURED IMAGE
function ST4_columns_content($column_name, $post_ID) {
if ($column_name == 'featured_image') {
$post_featured_image = ST4_get_featured_image($post_ID);
if ($post_featured_image) {
echo '<img style="width:300px;height:200px;" src="' . $post_featured_image . '" />';
}
}
elseif ($column_name == 'categories_portfolio') {
$terms = get_the_terms( $post->ID , 'category' );
foreach ( $terms as $term ) {
$term_link = get_term_link( $term, 'category' );
if( is_wp_error( $term_link ) )
continue;
echo '' . $term->name . '';
}
}
}
I have empty results, NULL, but I want to have the post category field. I used many wordpress functions, but no success.
I've noticed that your using the $post->ID as your parameter in your get_the_terms function, anyways I assume that the problem is you can't retrieve the category of the post, I would recommend using the get_the_category function in place of the get_the_terms in your code:
// SHOW THE FEATURED IMAGE
function ST4_columns_content($column_name, $post_ID) {
if ($column_name == 'featured_image') {
$post_featured_image = ST4_get_featured_image($post_ID);
if ($post_featured_image) {
echo '<img style="width:300px;height:200px;" src="' . $post_featured_image . '" />';
}
}
elseif ($column_name == 'categories_portfolio') {
//replace this $terms = get_the_terms( $post->ID , 'category' );
$terms = get_the_category($post_ID); //should you be using this instead of $post->ID?
foreach ( $terms as $term ) {
//replace this $term_link = get_term_link( $term, 'category' );
$term_link = get_category_link($term->term_id);
if( is_wp_error( $term_link ) )
continue;
echo '' . $term->name . '';
}
}
}
You can do a var_dump($terms) to further see the values being returned by this function, hope it helps, cheers!
I think you are using custom post type "Portfolio" as shown in attached screenshot.
Use wp_get_post_terms rather than get_the_terms
Update following code:
$terms = get_the_terms( $post->ID , 'category' );
to
$terms = wp_get_post_terms( $post->ID , 'category', array("fields" => "all") );
Note that 2nd parameter is the taxonomy name you are using while registering taxonomy.
See an example below where 'testimonials-cat' is used to register taxonomy.
register_taxonomy('testimonials-cat', 'testimonials', $args);
Your code for above taxonomy will be:
$terms = wp_get_post_terms($post->id, 'testimonials-cat', array("fields" => "all"));

Categories