Get WordPress Post ID from Post title

2019-01-30 18:05发布

I have an issue with a custom WordPress theme I'm developing. It's a bit convoluted, but essentially, what I need to do is get a Post Id by it's Post Title. In pseudo-code it would ideally be something like:

title = "foo";
post_id = get_post_id_where_title_is(title);

The title mentioned is a static reference not being pulled in from WordPress, it's already present on the page.

Thanks in advance.

标签: php wordpress
9条回答
做个烂人
2楼-- · 2019-01-30 18:18

Like Michal Mau mentioned:

Use

$my_post = get_page_by_title( 'My Title', OBJECT, 'post' );
echo $my_post->post_content;

It's ( $page_title, $output, $post_type ) to easily receive a post instead of a page.

查看更多
何必那么认真
3楼-- · 2019-01-30 18:25

Found a solution if anyone else struggles with this. Only posted the question out of desperation after 4 hours testing/Googling!

function get_post_by_title($page_title, $output = OBJECT) {
    global $wpdb;
        $post = $wpdb->get_var( $wpdb->prepare( "SELECT ID FROM $wpdb->posts WHERE post_title = %s AND post_type='post'", $page_title ));
        if ( $post )
            return get_post($post, $output);

    return null;
}

Found at: http://sudarmuthu.com/blog/2009/09/18/retrieving-posts-and-pages-based-on-title-in-wordpress.html

查看更多
叼着烟拽天下
4楼-- · 2019-01-30 18:25

1) differ post_title and post_name from each other. post_name maybe is the slug. post_title is the title of post.

2)

$titlee = "yourtitle";
echo $id = $wpdb->get_var("SELECT ID FROM $GLOBALS['wpdb']->posts WHERE post_name = $titlee");
查看更多
疯言疯语
5楼-- · 2019-01-30 18:28

Just a quick note for anyone who stumbles across this:
get_page_by_title() can now handle any post type.
The $post_type parameter has been added in WP 3.0.

查看更多
做个烂人
6楼-- · 2019-01-30 18:29

you can use the following code as per [a link][http://codex.wordpress.org/Function_Reference/get_page_by_title]1 )!

<?php 
$page = get_page_by_title( 'About' );
wp_list_pages( 'exclude=' . $page->ID );
?>
查看更多
孤傲高冷的网名
7楼-- · 2019-01-30 18:31

No need to use any type of SQL querys or plugin, use Wordpress standard functions for this

$page = get_page_by_title( 'Home' );
$page_id = $page->ID;
查看更多
登录 后发表回答