Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get WordPress Post ID from Post title

Tags:

php

wordpress

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.

like image 401
Aaron Avatar asked Oct 08 '09 09:10

Aaron


People also ask

How do I find post ID in WordPress?

How to Find a Post ID in WordPress. For me, the quickest and easiest way to find a post ID is done from the All Posts screen — found by logging into the WordPress dashboard and clicking Posts > All Posts. From here, simply hover your mouse over the post you want to find the ID for.

How do I get the current post name in WordPress?

This did the trick for me: $pagename = $wp_query->queried_object->post_name; , just don't forget to set global $wp_query; before!


2 Answers

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.

like image 180
Michal Mau Avatar answered Sep 28 '22 07:09

Michal Mau


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

like image 36
Aaron Avatar answered Sep 28 '22 06:09

Aaron