方法一:使用文章ID直接调用
在WordPress中,最简单直接调用指定文章的方法是使用文章ID。可以通过以下代码实现:
<?php
$post_id = 123; // 替换为你要调用的文章ID
$post = get_post($post_id);
setup_postdata($post);
?>
<h2><?php the_title(); ?></h2>
<div><?php the_content(); ?></div>
<?php wp_reset_postdata(); ?>
方法二:使用WP_Query类
WP_Query是WordPress中功能强大的查询类,可以更灵活地调用指定文章:
<?php
$args = array(
'p' => 123, // 文章ID
'post_type' => 'post' // 文章类型
);
$query = new WP_Query($args);
if ($query->have_posts()) {
while ($query->have_posts()) {
$query->the_post();
?>
<h2><?php the_title(); ?></h2>
<div><?php the_content(); ?></div>
<?php
}
wp_reset_postdata();
}
?>
方法三:使用文章别名(slug)调用
如果你知道文章的别名(slug),也可以使用以下方式调用:
<?php
$args = array(
'name' => 'your-post-slug', // 替换为你的文章别名
'post_type' => 'post',
'posts_per_page' => 1
);
$query = new WP_Query($args);
if ($query->have_posts()) {
while ($query->have_posts()) {
$query->the_post();
the_title('<h2>', '</h2>');
the_content();
}
wp_reset_postdata();
}
?>
方法四:使用短代码调用
如果你想在文章或页面中方便地调用指定文章,可以创建一个短代码:
// 在functions.php中添加
function display_specific_post($atts) {
$atts = shortcode_atts(array(
'id' => 0,
), $atts);
if (!$atts['id']) return '';
$post = get_post($atts['id']);
if (!$post) return '';
ob_start();
setup_postdata($post);
?>
<div class="specific-post">
<h3><?php the_title(); ?></h3>
<?php the_excerpt(); ?>
<a href="<?php the_permalink(); ?>">阅读更多</a>
</div>
<?php
wp_reset_postdata();
return ob_get_clean();
}
add_shortcode('display_post', 'display_specific_post');
使用方式:在编辑器中插入 [display_post id="123"]
注意事项
- 调用特定文章后,记得使用
wp_reset_postdata()
重置全局$post变量 - 如果是在循环中使用这些方法,可能会影响主循环的正常工作
- 对于性能要求高的场景,建议缓存查询结果
- 文章ID可以在WordPress后台文章列表的”快速编辑”中查看
以上方法可以根据你的具体需求选择使用,每种方法都有其适用场景,选择最适合你项目需求的方式即可。