我想我遗漏了一些明显的东西!我正在基于WordPress TwentyTwentyOne主题创建我的第一个子主题。我想在我的主页上显示来自特定类别(例如“新闻”)的帖子。我创建了一个特定的页面模板" page -home.php",这是来自父主题的"page-php“的副本,但添加了以下代码:
$args = array(
'category_name' => 'news',
'posts_per_page' => 3
);
$my_query = new WP_Query( $args );
if ( $my_query->have_posts() ) {
while ( $my_query->have_posts() ) {
$my_query->the_post();
}
}
wp_reset_postdata();这不起作用。Eclipse IDE在"new ()“上显示错误:"WP_Query无法解析为类型”,这是可以理解的,因为项目不包含wp-WP_Query目录。然而,我本以为WordPress环境会添加这个,但事实似乎并非如此。
然后我添加了以下令人费解的代码
$filename = $_SERVER["SCRIPT_FILENAME"];
$dir = substr($filename,0, strrpos($filename,"/"));
$incPath = $dir."/wp-includes";
$incPath = str_replace("/", DIRECTORY_SEPARATOR, $incPath);
set_include_path(get_include_path() . PATH_SEPARATOR . $incPath);
require_once 'class-wp-query.php';这也无济于事。
我有种感觉,我明显漏掉了一些东西,不应该这么复杂。
我在Windows10.0.19041和Apache2.4和PHP 7.4上运行Wordpress 5.7。
发布于 2021-04-08 21:32:05
它对我来说很好用:
<?php
$args = array(
'posts_per_page' => 3,
);
$the_query = new WP_Query($args);
if ($the_query->have_posts()) {
echo '<ul>';
while ($the_query->have_posts()) {
$the_query->the_post();
echo '<li>' . get_the_title() . '</li>';
}
echo '</ul>';
} else {
// no posts found
}
wp_reset_postdata();
?>发布于 2021-04-08 23:13:57
我已经添加了这行
echo '<li>' . get_the_title() . '</li>';根据Aleksandr的建议,页面现在输出所需的标题。
https://stackoverflow.com/questions/67002788
复制相似问题