$page = get_page_by_title CONTAINS

admin2025-06-06  2

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

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

Share Improve this question asked Sep 18, 2011 at 20:26 SparrwHawkSparrwHawk 1634 silver badges11 bronze badges
Add a comment  | 

2 Answers 2

Reset to default 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...

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 );
转载请注明原文地址:http://conceptsofalgorithm.com/Algorithm/1749144562a316745.html

最新回复(0)