【问题标题】:undefined offset: 0 in wordpress未定义的偏移量:wordpress 中的 0
【发布时间】:2011-09-18 00:09:39
【问题描述】:

代码:

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 . "'";
        }
    }

......

我将代码放在functions.php 文件中。调试问题:显示Notice: Undefined offset: 0

如何纠正?谢谢。

【问题讨论】:

    标签: php wordpress wordpress-theming


    【解决方案1】:

    你在那个函数中有这段代码:

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

    如果帖子没有标签,0 将是$tags 的未定义偏移量。要修复它,请将$tagcount = count($tags); 线向上移动一行,然后仅在大于零时构造$taglist。如果它等于 0,您可能希望将其设置为空字符串,但您可能希望将其设置为其他值,具体取决于 $taglist 的使用方式。

    【讨论】:

    • 太复杂了。我可以在 $taglist = "'" 之前做一个条件吗? $tags[0]->term_id。 "'";比如 if($tags)
    • @enjoylife:我确实提出了一个条件。我只是说您需要在该行之前检查$tags 的长度。
    • 是的,我也怀疑你的 for 循环 for ($i = 1; $i &lt; $tagcount; $i++) { 需要是 for ($i = 0; $i &lt; $tagcount; $i++) {
    • @drew010:不,它没有。如果您查看逻辑,它以$tags[0] 开头(这是问题所在)。然后for 循环将所有其他项目附加到$tags 中,并在它们前面加上逗号。
    猜你喜欢
    • 1970-01-01
    • 2014-06-25
    • 2013-09-23
    • 1970-01-01
    • 1970-01-01
    • 2012-02-08
    • 2020-01-02
    • 2021-07-06
    相关资源
    最近更新 更多