undefined offset: 0 in wordpress

the code:

function Sail_wp_get_related_posts(){  
    global $wpdb, $post;
    if(!$post->ID){return;}
    $now = current_time('mysql', 1);
    $tags = wp_get_post_tags($post->ID);
    $taglist = "'" . $tags[0]->term_id. "'";
    $tagcount = count($tags);
        $m=1;
    if ($tagcount > 1) {
        for ($i = 1; $i < $tagcount; $i++) {
            $taglist = $taglist . ", '" . $tags[$i]->term_id . "'";
        }
    }

……

Read More

i put the code in functions.php file.the DEBUGGING ISSUES: shows Notice: Undefined offset: 0 .

how to correct it? thank you.

Related posts

Leave a Reply

1 comment

  1. You have this code in that function:

    $taglist = "'" . $tags[0]->term_id. "'";
    

    If the post has no tags, 0 will be an undefined offset into $tags. To fix it, move the $tagcount = count($tags); line up one line and then only construct $taglist if it’s greater than zero. If it’s equal to zero, you’ll probably want to set it to an empty string, but you might want to set it to something else depending on how $taglist is used.