通过ID获取帖子内容


10

如何通过帖子ID获取帖子的内容?我试图get_page('ID');显示内容,但是它不起作用。


1
请投下反对票,因为您甚至都没有尝试阅读中的文档get_page()。很久以前就弃用了它。另外,关于此问题,网站上有无限数量的资源,即使Google对此也有大量信息
Pieter Goosen 2016年

Answers:


17

您可以通过多种方式进行操作。以下是最好的两种方法。

$post_id = 5// example post id
$post_content = get_post($post_id);
$content = $post_content->post_content;
echo do_shortcode( $content );//executing shortcodes

另一种方法

$content = get_post_field('post_content', $post_id);
echo do_shortcode( $content );//executing shortcodes

在Pieter Goosen提出意见之后apply_filters

apply_filters如果您希望内容被其他插件过滤,则可以使用。因此,这消除了使用的需要do_shortcode

$post_id = 5// example post id
$post_content = get_post($post_id);
$content = $post_content->post_content;
echo apply_filters('the_content',$content);
 //no need to use do_shortcode, but content might be filtered by other plugins.

如果您不想允许其他插件过滤此内容并需要简码功能,请使用do_shortcode

如果您也不想使用简码,请使用post_content


只想知道为什么要使用do_shortcode
Pieter Goosen

嗨,谢谢你的提问。@PieterGoosen我们正在获得raw content职位。帖子中嵌入的任何短代码都不会被处理。因此,我们将通过do_shortcode
WPTC-Troop

2
更好的方法是使用apply_filters( 'the_content', $content );,将所有应用于the_content()like wpautop和shortcode处理程序的过滤器应用于$content。;-)。请注意复数filters
Pieter Goosen

1
是的,使用apply_filters而不是do_shortcode有意义。但是使用apply_filter纯粹是基于他们的环境决定。让我也更新我的答案。非常感谢您对社区@PieterGoosen的关心
-Troop

0

我将在这里留下另一种难看的丑陋方法,您有时可能会发现它有用。当然,总是首选使用API​​调用的方法(get_post(),get_the_content(),...)。

global $wpdb;
$post_id = 123; // fill in your desired post ID
$post_content_raw = $wpdb->get_var(
    $wpdb->prepare(
        "select post_content from $wpdb->posts where ID = %d",
        $post_id
    )
);

0
$id = 23; // add the ID of the page where the zero is
$p = get_page($id);
$t = $p->post_title;
echo '<h3>'.apply_filters('post_title', $t).'</h3>'; // the title is here wrapped with h3
echo apply_filters('the_content', $p->post_content);

1
编辑您的答案,并添加解释:为什么这可以解决问题?
fuxia

-1

通过使用get_page('ID')

$page_id = 123;  //Page ID
$page_data = get_page($page_id); 
$title = $page_data->post_title; 
$content = $page_data->post_content;

1
由于您实际上根本没有尝试阅读文档,因此投票否决了。get_page()已贬值
Pieter Goosen
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.