【问题标题】:Wordpress plugin not activated because it gives a fatal error for custom wp queryWordpress 插件未激活,因为它为自定义 wp 查询提供了致命错误
【发布时间】:2014-04-02 18:03:19
【问题描述】:

我正在尝试开发推荐插件。但它没有运行并给出以下错误消息..

插件无法激活,因为它触发了致命错误。

代码是:

add_filter('the_content','Recommender_function');


function Recommender_function(){
$id=get_the_id();
if(!is_singular('post')){
return $content;
}
$terms=get_the_terms($id,'category');
$categoriesarr=array();
foreach($terms as $term)
{
$categoriesarr[]=$term->cat_ID;
}

$loop=new WP_Query(
array('posts_per_page'=>4,'category__in'=>$categoriesarr));
if($loop->have_posts()){
$content.='<h2>I say, you should also try</h2>
<ul class ="Recommendation">';
while($loop-have_posts()){
$loop-the_post();
$content.='<li>
<a href="'.get_permalink().'">'.get_the_title().'</a></li>';
}
$content.='</ul>';
WP_reset_Query();
return $content;
}
}

知道我哪里出错了吗?

【问题讨论】:

  • 正确的缩进和格式对故障排除有很大帮助。

标签: php wordpress


【解决方案1】:

你不能在函数名中包含-。你的 while 循环两次使用这种格式,我猜你打算做 $loop-&gt;have_posts() 和 $loop-&gt;the_post()。

while ($loop-have_posts()) {
    $loop-the_post();
    $content .= '<li>'
              . '<a href="'.get_permalink().'">'
              . get_the_title()
              . '</a>'
              .'</li>'
              ;
}

【讨论】:

  • 会建议相同的
【解决方案2】:

看看你原来的这两行:

while($loop-have_posts()){
$loop-the_post();

您正在调用实例化为$loop 的类中的函数,而不是名为$loop-have_posts() 或$loop-the_post() 的函数。所以这两行应该是这样的:

while($loop->have_posts()){
$loop->the_post();

我注意到的另一件事是您正在通过.= 连接$content 字符串,但您在任何时候都没有初始化字符串。所以我在if() 循环之前添加了一个$content = '';。希望这会奏效。

另外,我要说的是:您确实需要养成格式化代码以提高可读性的习惯。当您在编写代码时,这似乎很痛苦,但实际上您的代码越难阅读,调试它的时间就越困难。而且它也让其他人更难帮助您调试它。

也就是说,我在下面重新格式化了你的函数:

add_filter('the_content','Recommender_function');

function Recommender_function() {

  $id=get_the_id();

  if (!is_singular('post')) {
    return $content;
  }

  $terms = get_the_terms($id,'category');
  $categoriesarr = array();

  foreach ($terms as $term) {
    $categoriesarr[] = $term->cat_ID;
  }

  $loop = new WP_Query (array('posts_per_page'=>4,'category__in'=>$categoriesarr));

  $content = ''; 

  if ($loop->have_posts()) {

    $content .= '<h2>I say, you should also try</h2>'
              . '<ul class ="Recommendation">'
              ;

    while ($loop->have_posts()) {
        $loop->the_post();
        $content .= '<li>'
                  . '<a href="'.get_permalink().'">'
                  . get_the_title()
                  . '</a>'
                  .'</li>'
                  ;
    }

    $content .= '</ul>';

    WP_reset_Query();

    return $content;

  }

}

【讨论】:

    猜你喜欢
    • 2020-09-13
    • 2014-04-09
    • 2015-11-18
    • 2019-04-27
    • 2021-12-31
    • 2015-09-06
    • 2017-09-04
    • 2014-11-05
    相关资源
    最近更新 更多