wp insert post – wp_insert_post if page doesn’t exist under current page

Question

I am trying to dynamically insert a page as a child under the current page using wp_insert_post, however I need to first check if the page title exists under the current page, and if it doesn’t exist then to run the code and create the page.

The get_page_by_title seems to check if the page exists in the entire sitemap, and if the title exists it will not create the page, So I only need to check if it exists under the current page as there will be pages with the same title under other parent pages

e.g

mywebsite.com/oneparent/child-page-title

mywebsite.com/twoparent/child-page-title

Please see my code below. Is there a better way to use get_page_by_title but to only check the child pages for the current page? Or is there a better method to do this?

if (get_page_by_title($episodetitle)==NULL) {
$seasonepisode = array(
    'post_title'    => $episodetitle,
    'post_content'  => 'Some Content',                     
    'post_status'   => 'publish',
    'post_parent'   => $post->ID,
    'post_type'     => 'page',
    'page_template' => 'template-songlist.php'
);

wp_insert_post($seasonepisode);
}

in progress 0
Daryl Roberts 2 months 2021-04-27T03:29:56-05:00 0 Answer 0 views 0

Answer ( 1 )

    0
    2021-04-28T14:00:21-05:00
    
    $args = array(
            'post_type'      => 'page',
            'posts_per_page' => -1,
            'post_parent'    => $post->ID,
    );
        
    $children= new WP_Query( $args );
     $seasonepisode = array(
                'post_title'    => $episodetitle,
                'post_content'  => 'Some Content',                     
                'post_status'   => 'publish',
                'post_parent'   => $post->ID,
                'post_type'     => 'page',
                'page_template' => 'template-songlist.php'
               );
    if ( $children->have_posts() ){
        while ( $children->have_posts() ) { 
            $children->the_post();
            if(get_the_title() != $episodetitle){
               
                wp_insert_post($seasonepisode);
                exit;
             }
        }//end of while
    }else{wp_insert_post($seasonepisode);}//end have posts
    wp_reset_postdata(); 
    

    Alternatively

    
    $query = new WP_Query();
    $all_wp_pages = $query->query(array('post_type' => 'page'));
     
    //$assuimg $post is current page
        $children = get_page_children( $post->ID, $all_wp_pages );
    $flag=true;
    foreach($children as $child){
        if($episodetitle == get_the_title($child))
            $flag=false;
    }
    if($flag){
        wp_insert_post($seasonepisode);
    }
    

Leave an answer

Browse
Browse