Last active
February 8, 2019 01:43
-
-
Save sudar/4154386 to your computer and use it in GitHub Desktop.
Get Page by Title in WordPress. More details at http://sudarmuthu.com/blog/retrieving-posts-and-pages-based-on-title-in-wordpress
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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; | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
$page = get_page_by_title('post title that we are searching'); | |
// $page is the post array. To just retrieve the id | |
$id = $page->ID; |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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