Just wondering how to fetch a page by using 'title contains'. I can retrieve a page by using the following
<?php
$page = get_page_by_title('Restaurants and Pubs');
?>
but how could I do 'page title contains "Pubs"'?
Thanks
You should build a query using the Wordpress database class. Place this in your functions.php file
function get_page_by_title_search($string){
global $wpdb;
$title = esc_sql($string);
if(!$title) return;
$page = $wpdb->get_results("
SELECT *
FROM $wpdb->posts
WHERE post_title LIKE '%$title%'
AND post_type = 'page'
AND post_status = 'publish'
LIMIT 1
");
return $page;
}
Use this in your theme:
$page = get_page_by_title_search('Foo Bar');
echo $page->post_title;
echo $page->post_content;
//etc...
This works pretty well for me. Would love to hear feedback on better ways to do it though. Thanks!
// Get all pages
$my_pages = get_pages();
// Get ID's of pages with "string" in title
foreach ($my_pages as $my_page) {
if ( stristr($my_page->post_title, 'string') ) {
$include_ids .= $my_page->ID . ',';
}
}
// Output only pages with "string" in the title
$args = array(
'include' => $include_ids,
);
wp_list_pages( $args );