0

Hello i am writing a function to modify the post content and some more information to it. But while doing this it makes the site not to load and throws a 500 Internal server error. Here is my code which i used for the hook.

add_filter("the_content","add_related_pics",1);

function add_related_pics($content){
    $pics = "";
    $pics.= '<ul>';
    $tag = get_post_meta(get_the_ID(), 'highlight-tag', true);
    $original_query = $wp_query;
    $wp_query = null;
    $args=array('posts_per_page'=>5, 'tag' => $tag,'orderby' => 'rand');
    $wp_query = new WP_Query( $args );
    if ( have_posts() ) :
        while (have_posts()) : the_post();
            $pics.= '<li>';
        preg_match('@<img.+src="(.*)".*>@Uims', get_the_content(), $matches);
        $src = $matches[1];
            $pics.='<a href="'.get_permalink().'"><img src="'.$src.'" height="50" width="50"  /></a>';
        $pics.= '</li>';
        endwhile;
    endif;
    $wp_query = null;
    $wp_query = $original_query;
    wp_reset_postdata();
    $pics.='</ul>';
    return $content.$pics;  
}

Can anyone point that what is wrong with this code ?

4

1 回答 1

0

您没有使用该wp_query对象,这就是您出错的原因。

将其添加到您的代码中,您应该没问题。

   if ( $wp_query->have_posts()  ) :
    while ( $wp_query->have_posts() ) :
    $wp_query->the_post();
        $pics.= '<li>';
    preg_match('@<img.+src="(.*)".*>@Uims', get_the_content(), $matches);
    $src = $matches[1];
        $pics.='<a href="'.get_permalink().'"><img src="'.$src.'" height="50" width="50"  /></a>';
    $pics.= '</li>';
    endwhile;
    endif;

并且除非您要使用,否则您$orignal_query不需要将wp_query变量重置为它。

所以在这两种情况下都去掉你的以下代码:

$original_query = $wp_query;
$wp_query = null;
于 2013-03-16T13:05:12.003 回答