You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何编写查询语句展示投资网站最新的post和page内容?

WordPress 查询最新的 Post 和 Page 内容

针对你的需求,下面两种方法可以实现查询最新创建的post和page内容:

方法一:使用 WordPress 内置的 WP_Query(推荐)

这是WordPress官方推荐的查询方式,不用直接操作数据库,更安全且符合规范。

// 构建查询参数
$args = array(
    'post_type' => array('post', 'page'), // 指定要查询的内容类型
    'orderby' => 'date', // 按创建日期排序
    'order' => 'DESC', // 降序排列,最新的在前
    'posts_per_page' => 10, // 显示最新的10条,可按需修改
    'post_status' => 'publish' // 只查询已发布的内容
);

// 执行查询
$query = new WP_Query($args);

// 循环输出内容
if ($query->have_posts()) {
    while ($query->have_posts()) {
        $query->the_post();
        // 输出标题和链接,可按需添加其他内容
        echo '<h2><a href="' . get_permalink() . '">' . get_the_title() . '</a></h2>';
        echo '<p>' . get_the_excerpt() . '</p>';
    }
    // 重置查询
    wp_reset_postdata();
} else {
    echo '暂无内容';
}

方法二:直接使用数据库查询(适合自定义复杂逻辑场景)

如果需要直接操作数据库,可使用WordPress提供的$wpdb对象,避免手动拼接SQL导致注入风险:

global $wpdb;

// 执行查询
$results = $wpdb->get_results(
    "SELECT ID, post_title, post_date, guid 
     FROM {$wpdb->posts} 
     WHERE post_type IN ('post', 'page') 
       AND post_status = 'publish' 
     ORDER BY post_date DESC 
     LIMIT 10" // 取最新10条,可修改
);

// 输出结果
if ($results) {
    foreach ($results as $item) {
        echo '<h2><a href="' . get_permalink($item->ID) . '">' . esc_html($item->post_title) . '</a></h2>';
        echo '<p>发布时间:' . date('Y-m-d H:i', strtotime($item->post_date)) . '</p>';
    }
} else {
    echo '暂无内容';
}

内容的提问来源于stack exchange,提问作者Carlos Mora

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.26 16:02:09