3

我在这里看到我可以使用帖子 ID 在 WordPress 中获取帖子的内容。就像是:

<?php $my_postid = 83;//This is page id or post id
$content_post = get_post($my_postid);
$content = $content_post->post_content;
$content = apply_filters('the_content', $content);
$content = str_replace(']]>', ']]&gt;', $content);
echo $content;?>

我想要同样的东西,但要按其名称获取帖子。

4

1 回答 1

5

您可以使用

$content_post = get_posts( array( 'name' => 'yourpostname' ) ); // i.e. hello-world
if( count($content_post) )
{
    $content = $content_post[0]->post_content;
    // do whatever you want
    echo $content;
}

更新:您也可以在您的中添加此功能,functions.php并可以从任何地方调用它

function get_post_by_name($post_name, $post_type = 'post', $output = OBJECT) {
    global $wpdb;
    $post = $wpdb->get_var( $wpdb->prepare( "SELECT ID FROM $wpdb->posts WHERE post_name = %s AND post_type= %s", $post_name, $post_type ));
    if ( $post ) return get_post($post, $output);
    return null;
}

// call the function "get_post_by_name"
$content_post = get_post_by_name('hello-world');
if($content_post)
{
    $content = $content_post->post_content;
    // do whatever you want
    echo $content;
}

更新:要按标题获取帖子,您可以使用

// 'Hello World!' is post title here
$content_post = get_page_by_title( 'Hello World!', OBJECT, 'post' );

或者你可以使用你的$item->item_title变量

$content_post = get_page_by_title( $item->item_title, OBJECT, 'post' );
if($content_post)
{
    $content = $content_post->post_content;
    // do whatever you want
    echo $content;
}
于 2013-02-20T20:36:36.343 回答