【问题标题】:Wordpress, get a post content by its name or URLWordpress,通过名称或 URL 获取帖子内容
【发布时间】:2013-02-05 23:57:24
【问题描述】:

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

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

【问题讨论】:

    标签: php wordpress custom-post-type


    【解决方案1】:

    你可以使用

    $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-&gt;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;
    }
    

    【讨论】:

    • 如果我手动输入帖子名称,它会起作用。但是如果我希望它是动态的 item_title); ?>。我的意思是,我不知道 php 如果我想把 itemtitle 作为 postname,我问你在 'yourpostname' 里面放什么...
    • post-name 在这里发布slug,它不是标题,但如果你想使用标题,那么你可以使用get_page_by_title
    猜你喜欢
    • 1970-01-01
    • 2019-10-25
    • 1970-01-01
    • 1970-01-01
    • 2017-04-23
    • 1970-01-01
    • 1970-01-01
    • 2012-05-15
    • 2015-06-10
    相关资源
    最近更新 更多