2013-02-20 52 views
1

我在这里看到,我可以使用帖子ID在WordPress中获得帖子的内容。就像:WordPress的,通过它的名字或URL获得帖子内容

<?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;?> 

我想要的是同样的东西,但得到其名称的职位。

回答

2

您可以用做

$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; 
} 
+0

它的工作原理,如果我手动将岗位名称。但是,如果我希望它是动态的<?php echo($ item-> item_title); ?>。我的意思是,我不知道PHP我问你要在'yourpostname'里面放什么,如果我想把itemtitle作为postname ... – 2013-02-20 20:59:48

+0

'post-name'是post'slug'在这里,它不是标题,但是如果你想使用标题,那么你可以使用[get_page_by_title](http://codex.wordpress.org/Function_Reference/get_page_by_title)。 – 2013-02-20 21:04:56

+1

非常感谢!伟大的工程,你救了我:) – 2013-02-20 23:35:09

相关问题