0

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

2 Answers 2

1

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...
6
  • Actually I'm just looking to pull a page into my template. For example, this drags in the 'Restaurants and Pubs' page... <?php function callpage($page) { $my_id = $page; $post_id = get_post($my_id, ARRAY_A); $content = $post_id['post_content']; return $content; } ?> <div id='somediv'> <?php
    – SparrwHawk
    Commented Sep 18, 2011 at 20:52
  • Then this would be your answer. I updated the answer to show you how to use this. Commented Sep 18, 2011 at 20:55
  • Sorry, I only managed to half write my answer, and it won't format my code in the comments (grrr). What I was meant to say is that this works perfectly... jsfiddle.net/NnaqM/1 , but I want to drag in a page by just typing in pub i.e. not type out the whole title, so something like this $page = get_page_by_title(contains 'Pubs');
    – SparrwHawk
    Commented Sep 18, 2011 at 21:02
  • When I say 'typing' I mean all in the backend template, nothing to do with the search box in the interface.
    – SparrwHawk
    Commented Sep 18, 2011 at 21:05
  • 1
    @BrianFegter Do $page->page_title and $page->page_content really exist, or you would rather need to use $page->post_title and $page->post_content? Commented Nov 27, 2018 at 21:44
0

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 );

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.