Check to see if page exists problems

I’ve created a class to dynamically create pages. I’m checking to see if the page exists by comparing the new page’s title to post_name. The comparison seems to work ok, but even if there is a match the page is created anyway and I can’t figure out why.

My code looks like this:

class createDynamicPage {

public function __construct( $nameArray ) {
    $this->title = $nameArray['title']; //Title of the page
    $this->slug = $nameArray['slug']; //Page slug
}

public $pageContent="";

public function rps_createPage(){
    $allPages = get_pages();
    $exists = false;
    foreach( $allPages as $page ){
        if( strtolower( $page->post_name ) == strtolower( $this->title ) ){
            $exists = true;
        }
    }
    if( $exisits == false ) {
        $new_page_id = wp_insert_post(
            array(
                'post_title' => $this->title,
                'post_type'     => 'page',
                'post_name'  => $this->slug,
                'comment_status' => 'closed',
                'ping_status' => 'closed',
                'post_content' => $this->pageContent,
                'post_status' => 'publish',
                'post_author' => 1,
                'menu_order' => 0
            )
        );
    }
}

}

$cdArray = array( 'title' => 'Biography', 'slug' => 'concert-diary' );
$pageConcertDiary = new createDynamicPage( $cdArray );
add_action('init', array( &$pageConcertDiary, 'rps_createPage' ));

I assume I’m being very stupid, but I can’t figure it out! Also, being a OOP newbie, I’d happy take criticism/pointers on how I’ve outlined the class.

Cheers

2 Answers
2

Why are you comparing $post->post_name to $this->title? You should be comparing slug to slug.

Try changing your comparison from this:

if( strtolower( $page->post_name ) == strtolower( $this->title ) )

…to this:

if( strtolower( $page->post_name ) == strtolower( $this->slug ) )

Also, I might suggest keeping with the WordPress object conventions with your dynamically created pages, as doing so might help avoid such confusion.

I would change this:

$cdArray = array( 'title' => 'Biography', 'slug' => 'concert-diary' );

…to this:

$cdArray = array( 'title' => 'Biography', 'post_name' => 'concert-diary' );

And then change this:

public function __construct( $nameArray ) {
    $this->title = $nameArray['title']; //Title of the page
    $this->slug = $nameArray['slug']; //Page slug
}

…to this:

public function __construct( $nameArray ) {
    $this->title = $nameArray['title']; //Title of the page
    $this->post_name = $nameArray['post_name']; //Page slug
}

So that your comparison becomes this:

if( strtolower( $page->post_name ) == strtolower( $this->post_name ) )

That might help you avoid some confusion.

Leave a Comment