开发者

How can I get a post by title in Wordpress?

Wordpress 3.0

I want to have the contents of a specific post into a page by us开发者_开发问答ing the title of the post. As far as I can tell, I can't do it directly with get_post().

I can assume what the brute force way might be, but I suspect there's a more elegant way?


get_page_by_title($id, OBJECT, 'post');

There ye go.


<!--1.Get post ID by post title if you know the title or the title variable-->
<?php
$posttitle = 'post_title';
$postid = $wpdb->get_var( "SELECT ID FROM $wpdb->posts WHERE post_title = '" . $posttitle . "'" );
echo $postid;
?>

<!--2.use get_post($post_id) to get whatever you want to echo-->
<?php
$getpost= get_post($postid);
$postcontent= $getpost->post_content;
echo $postcontent;
?>


No need to SQL query's when you can use wordpress own functions for this.

$page = get_page_by_title( 'Startsida' );
$page_id = $page->ID;


post_exists is a good function for that :

https://developer.wordpress.org/reference/functions/post_exists/

<?php

$post_id = post_exists('Your title');
// return id or 0 if post doesn't exists.

if($post_id>0)
    get_post($post_id);


See my answer on a very similar question. Do not query the data base with an unescaped string.


You can use this:

1)

global $wpdb;
$your_title = "yourtitle";
$id = $wpdb->get_var("SELECT ID FROM $wpdb->posts WHERE post_name = $your_title");
echo $id;

or 2)

    $slug_to_get = 'my_title_or_slug';
    // you can use custom post type too
    $posttypee='post';

    $args=array(
      'title' => $slug_to_get,
      'post_type' => $posttypee,
      'post_status' => 'publish'
      );
    $my_posts = get_posts($args);
    if( $my_posts ) {
    echo 'ID on the first post found '.$my_posts[0]->ID;
    }
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜