在这个问题中,我们要求解的是如何使用 PHP(WordPress)来显示查询结果。以下是一个简单的示例,说明如何在 WordPress 主题中查询数据并将其显示在页面上。
首先,我们需要创建一个自定义页面模板,以便在 WordPress 中执行自定义查询。在你的主题文件夹中创建一个名为 custom-query-template.php
的文件,并将以下代码粘贴到其中:
<?php
/*
Template Name: Custom Query Template
*/
get_header(); ?>
<main>
<section>
<?php
// 自定义查询
$args = array(
'post_type' => 'post',
'posts_per_page' => 10,
'orderby' => 'date',
'order' => 'DESC'
);
$custom_query = new WP_Query($args);
// 检查查询是否有结果
if ($custom_query->have_posts()) :
// 开始循环
while ($custom_query->have_posts()) : $custom_query->the_post();
// 显示查询结果
the_title('<h2><a href="' . get_permalink() . '">', '</a></h2>');
the_excerpt();
endwhile;
// 结束循环
else :
// 如果没有结果
echo '<p>没有找到任何内容</p>';
endif;
// 重置查询
wp_reset_postdata();
?>
</section>
</main>
<?php get_footer(); ?>
这个模板将执行一个自定义查询,检索最近的 10 篇文章,并按照日期降序排列。然后,它将在页面上显示这些文章的标题和摘要。
接下来,我们需要在 WordPress 后台创建一个新页面,并将我们刚刚创建的模板分配给它。
现在,你应该能够在网站上看到一个新页面,其中包含按照我们的自定义查询检索到的文章标题和摘要。
这个示例仅仅是一个起点,你可以根据你的需求修改查询参数以及显示的内容。
领取专属 10元无门槛券
手把手带您无忧上云