方法一:使用文章ID直接調(diào)用
在WordPress中,最簡(jiǎn)單直接調(diào)用指定文章的方法是使用文章ID??梢酝ㄟ^(guò)以下代碼實(shí)現(xiàn):
<?php
$post_id = 123; // 替換為你要調(diào)用的文章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類(lèi)
WP_Query是WordPress中功能強(qiáng)大的查詢(xún)類(lèi),可以更靈活地調(diào)用指定文章:
<?php
$args = array(
'p' => 123, // 文章ID
'post_type' => 'post' // 文章類(lèi)型
);
$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)調(diào)用
如果你知道文章的別名(slug),也可以使用以下方式調(diào)用:
<?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();
}
?>
方法四:使用短代碼調(diào)用
如果你想在文章或頁(yè)面中方便地調(diào)用指定文章,可以創(chuàng)建一個(gè)短代碼:
// 在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"]
注意事項(xiàng)
- 調(diào)用特定文章后,記得使用
wp_reset_postdata()
重置全局$post變量 - 如果是在循環(huán)中使用這些方法,可能會(huì)影響主循環(huán)的正常工作
- 對(duì)于性能要求高的場(chǎng)景,建議緩存查詢(xún)結(jié)果
- 文章ID可以在WordPress后臺(tái)文章列表的”快速編輯”中查看
以上方法可以根據(jù)你的具體需求選擇使用,每種方法都有其適用場(chǎng)景,選擇最適合你項(xiàng)目需求的方式即可。