Wordpress,按名称或网址获取帖子内容

时间:2013-02-20 20:14:55

标签: php wordpress custom-post-type

我在这里看到我可以使用帖子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;?>

我想要同样的事情,但要以它的名字命名。

1 个答案:

答案 0 :(得分:3)

您可以使用

执行此操作
$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;
}