【问题标题】:How to prevent and fix "Undefined offset: 0 in" error message如何防止和修复“未定义的偏移量:0 in”错误消息
【发布时间】:2012-11-06 23:04:00
【问题描述】:

我有一个在 WordPress 插件中运行的函数,当 wp_debug 被激活时,我收到此错误消息。

未定义的偏移量:/…/wp-content/plugins/advanced-widget-pack/lib/advanced_widget_pack.class.php 第 568 行中的 0

这是插件中使用的函数:

/**
 * Retrieves the image for a post
 *
 * Uses the post_thumbnails if available or
 * searches through the post and retrieves the first found image for use as thumbnails
 */
function featured_image_thumb($size = 50) {
    global $post;
    // If a featured image has been set, use the featured-thumbnail size that was set above with the class of 'thumb'
    if(has_post_thumbnail() ) {
        echo '<a href="'.get_permalink().'" title="'.get_the_title().'" >';
        the_post_thumbnail(array($size,$size),array('class' => 'thumb'));
        echo '</a>';
    }
    // If a featured image is not set, get the first image in the post content
    else {
        $first_img = '';
        ob_start();
        ob_end_clean();
        $output = preg_match_all('/<img.+src=[\'"]([^\'"]+)[\'"].*>/i', $post->post_content, $matches);
        $first_img = $matches[1][0];

        // Define a default fallback image in case a featured image is not set and there are no images in the post content
        if(empty($first_img)){
            $first_img = WP_PLUGIN_URL.'/advanced-widget-pack/images/nothumb.png';
        }

        // Generate the HTML code to display the image and resize the image with timthumb.php
        return '<a title="'.get_the_title().'" href="'.get_permalink().'"><img class="thumb" src="'.WP_PLUGIN_URL.'/advanced-widget-pack/timthumb.php?src=' . $first_img .'&w='.$size.'&h='.$size.'" alt="" /></a>';
    }
}

第 568 行或发生错误的地方是这部分代码:

$first_img = $matches[1][0];

我不确定如何防止或修复此错误。

任何帮助或建议将不胜感激。 谢谢

【问题讨论】:

  • $matches 根本没有价值?

标签: wordpress error-handling undefined offset


【解决方案1】:

未定义的偏移量 $X[Y] 表示数组 X 没有键 Y。在您的情况下,$matches[1] 没有第一个元素。

我认为你必须使用条件:

if(preg_match_all('/<img.+src=[\'"]([^\'"]+)[\'"].*>/i', $post->post_content, $matches)){
  $first_img = $matches[1][0];
}

【讨论】:

    【解决方案2】:

    在我的例子中,一个带有条件的拥抱对我来说是这样的:

    if( $output = preg_match_all('/<img.+src=[\'"]([^\'"]+)[\'"].*>/i', $post->post_content, $matches); )
    

    所有通知都消失了! :)

    【讨论】:

      【解决方案3】:

      意味着数组的第一个索引没有定义 prob 因为它上面的 preg_match 找不到任何东西。你不应该真的担心它,但在 ob_end_clean 之后放置以下内容应该会处理它

       $matches[1][0] = '';
      

      【讨论】:

      • 感谢安德鲁的帮助。
      猜你喜欢
      • 1970-01-01
      • 2011-09-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-01-14
      • 2015-12-06
      • 1970-01-01
      • 2020-02-10
      相关资源
      最近更新 更多