我犯了一个最奇怪的错误。
尝试显示自定义循环时,出现以下错误:
Fatal error
: Uncaught Error: Call to a member function have_posts() on array in /.../custom-page.php:42 Stack trace: #0 /.../wp-includes/template-loader.php(106): include() #1 /.../wp-blog-header.php(19): require_once(\'/data/sites/web...\') #2 /.../index.php(17): require(\'/data/sites/web...\') #3 {main} thrown in
/.../custom-page.php
on line
42
这太奇怪了,因为我看到了“在null上调用成员函数”或其他错误,但在数组上没有,这通常对这个函数很好。
我的custom-page.php
有如下内容:
<?php get_header(); ?>
<div class="container">
<div class="row">
<div class="col-12">
<h1><?php the_title(); ?></h1>
<div class="grid row">
<?php foreach( $programs as $program ) {
$custom_query = get_posts( [
\'post_type\'=> \'artikel\',
\'post_status\' => \'publish\',
\'posts_per_page\' => 1,
\'order\' => \'DESC\',
\'orderby\' => \'date\',
\'meta_query\' => [
[ \'key\' => \'layout\', \'value\' => \'synopsis\' ],
[ \'key\' => \'programs\', \'value\' => \'"\' . $program . \'"\', \'compare\' => \'LIKE\' ]
]
] );
if( $custom_query->have_posts() ) {
echo \'test\';
}
} ?>
</div>
</div>
</div>
</div>
<?php get_footer(); ?>
最合适的回答,由SO网友:Sally CJ 整理而成
<罢工>好吧,get_posts()
returns an array, 所以你可能(打了个错字)打算new WP_Query
那里:罢工>
get_posts()
默认情况下,返回post对象的数组(请参见WP_Post
), 数组没有方法(PHP类中的函数),因此不能使用;箭头“;这就解释了错误调用成员函数have\\u posts()onarray“引用”;。
$array = array( 1, 2, 3 );
$array->foo(); // error - $array is an array, not an object
class MyClass {
public function foo() {
echo \'it works\';
}
}
$object = new MyClass;
$object->foo(); // works - $object is an object (or a class instance) and the
// method foo() exists and callable/public
以及
have_posts()
问题属于
WP_Query
类,所以您可能想
$custom_query = new WP_Query( [ <args> ] )
而不是
$custom_query = get_posts()
:
$custom_query = new WP_Query( [
// your args here
] );
我希望这会有所帮助,如果您需要进一步的帮助
WP_Query
, 查看
documentation.