Created
June 25, 2023 23:39
-
-
Save awps/1ec1c4d91e8ce6ddd3810e67b2f9a9d2 to your computer and use it in GitHub Desktop.
Alternative to the deprecated `get_page_by_title`, using WP_Query
This file contains 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
<?php | |
function get_page_by_title( $page_title, $output = OBJECT, $post_type = 'page' ) { | |
$query = new WP_Query( | |
array( | |
'post_type' => $post_type, | |
'title' => $page_title, | |
'post_status' => 'all', | |
'posts_per_page' => 1, | |
'no_found_rows' => true, | |
'ignore_sticky_posts' => true, | |
'update_post_term_cache' => false, | |
'update_post_meta_cache' => false, | |
'orderby' => 'date', | |
'order' => 'ASC', | |
) | |
); | |
if ( ! empty( $query->post ) ) { | |
$_post = $query->post; | |
if ( ARRAY_A === $output ) { | |
return $_post->to_array(); | |
} elseif ( ARRAY_N === $output ) { | |
return array_values( $_post->to_array() ); | |
} | |
return $_post; | |
} | |
return null; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment