Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/240.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Php Wordpress,通过其名称或URL获取帖子内容_Php_Wordpress_Custom Post Type - Fatal编程技术网

Php Wordpress,通过其名称或URL获取帖子内容

Php Wordpress,通过其名称或URL获取帖子内容,php,wordpress,custom-post-type,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(']

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

我也想要同样的东西,但是我想通过它的名字来获得这篇文章。

你可以使用

$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\u 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;
}

如果我手动输入帖子名,它就会工作。但如果我希望它是动态的呢。我的意思是,我不懂php,我在问你如果我想把itemtitle作为postname,应该在“yourpostname”中放什么…
postname
这里是post
slug
,它不是title,但是如果你想用title代替,那么你可以使用。