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
Why are you comparing
$post->post_name
to$this->title
? You should be comparing slug to slug.Try changing your comparison from this:
…to this:
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:
…to this:
And then change this:
…to this:
So that your comparison becomes this:
That might help you avoid some confusion.
At first, you may need to include wp-blog-header.
then use this, to check if post already exist ( you can modify it to fit pages):