WordPress.org

Ready to get started?Download WordPress

Forums

How to check if Page exists? (8 posts)

  1. Miroslav
    Member
    Posted 8 years ago #

    I am using a page as the front page with query_posts as follows:

    <?php
    query_posts('pagename=home');
    ?>

    It works great, but I want the blog to revert back to the default 10 posts display automatically, in case there is no Page called home (i.e., the page doesn't exist).

    Is there any way --- using conditional tags, or something else --- to check if the Page called "Home" exists first and then, if TRUE = serve the query_posts command, if FALSE = serve the default setting?

    Hope I am clear about what I want. Thanks in advance! :)

  2. TwoMotifs
    Member
    Posted 8 years ago #

    You can use condition tags:

    http://codex.wordpress.org/Conditional_Tags

    The one that will interest you the most is the following one:

    is_page('About Me')

  3. Miroslav
    Member
    Posted 8 years ago #

    Thanks, TwoMotifs, but that's not what I need (at least, I think it's not).

    I don't want to serve template-specific content based on the template file being called (which is what is_page() would be useful for)...

    Instead, I want to insert contents of a particular Page in my template file using query_posts(), provided that the Page exists in the database. If the Page doesn't exist, I want to serve the template without the 'query_posts()'. Along the lines of...

    1. Does the page 'pagename' exist?
    2. If yes, run template with query_posts().
    3. If not, run template without query_posts().

    Anybody?

  4. Miroslav
    Member
    Posted 8 years ago #

    Bump :)

  5. Miroslav
    Member
    Posted 8 years ago #

    Last bump... :(

    Nobody knows the answer to this question???

  6. pcarlow
    Member
    Posted 8 years ago #

    Just came here looking for the answer to this same question. Had to figure it out myself. Hope this helps:

    <?php $name = $wpdb->get_var("SELECT ID FROM $wpdb->posts WHERE post_name='your-page-name'"); ?>
    <?php if ($name != '') { ?>
    Do this
    <?php } else { ?>
    It doesn't exist
    <?php } ?>

  7. Samuel Wood (Otto)
    Tech Ninja
    Posted 8 years ago #

    Create this function somewhere (like functions.php of your theme)

    function get_page_by_name($pagename)
    {
    $pages = get_pages();
    foreach ($pages as $page) if ($page->post_name == $pagename) return $page;
    return false;
    }

    Usage:
    $page = get_page_by_name('MYPAGE');
    if (!empty($page)) {
    // page exists and is in $page
    } else {
    // page does not exist
    }

  8. Miroslav
    Member
    Posted 8 years ago #

    Sounds promising. Will give it a try. Thanks! :)

Topic Closed

This topic has been closed to new replies.

About this Topic