我正在尝试开发一个推荐插件。它不会运行,并给出以下错误消息。
无法激活插件,因为它触发了致命错误。
代码为:
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;
}
}
知道我哪里出错了吗?
函数名称中不能有-
。您的 while 循环两次使用这种格式,我猜你的意思是做$loop->have_posts()
和$loop->the_post()
.
while ($loop-have_posts()) {
$loop-the_post();
$content .= '<li>'
. '<a href="'.get_permalink().'">'
. get_the_title()
. '</a>'
.'</li>'
;
}
看看原文中的这两行:
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;
}
}