Skip to content

Instantly share code, notes, and snippets.

@sudar
Last active February 8, 2019 01:43
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sudar/4154386 to your computer and use it in GitHub Desktop.
Save sudar/4154386 to your computer and use it in GitHub Desktop.
/**
* Retrieve posts ids given their title.
* Use this function if there are more than one post with the same title.
*/
function get_multiple_posts_by_title($title) {
global $wpdb;
$posts_ids = array();
$posts = $wpdb->get_results( $wpdb->prepare( “SELECT ID FROM $wpdb->posts WHERE post_title = %s AND post_type=’post_type’”, $title), OBJECT );
foreach ($posts as $post) {
$posts_ids[] = $post->ID;
}
return $posts_ids;
}
$page = get_page_by_title('post title that we are searching');
// $page is the post array. To just retrieve the id
$id = $page->ID;
/**
* Retrieve a post given its title.
*
* @uses $wpdb
*
* @param string $post_title Page title
* @param string $output Optional. Output type. OBJECT, ARRAY_N, or ARRAY_A.
* @return mixed
*/
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;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment