I am trying to dynamically insert a page/multiple pages as a child under the current page in my template file, using wp_insert_post, however I need to first check if the page title already exists under the current page, and if it doesn't exist then to run the code and create the page(s), but don’t want it to create a duplicate page under the current page if the title already exist under the current page only.
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, but 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);
}
UPDATED WORKING CODE
foreach ($episoderange as $episodelist) {
$episodetitle = 's0' . $season['season_number'] . 'e0' . $episodelist;
$currentID = $post->ID;
$mypages = get_pages( array( 'child_of' => $currentID, 'post_type' => 'page' ) );
$seasonepisode = array(
'post_title' => strtolower($episodetitle),
'post_content' => $output_episode['overview'],
'post_status' => 'publish',
'post_parent' => $currentID,
'post_type' => 'page',
'page_template' => 'template-songlist.php'
);
$titleslist = array_column($mypages, 'post_title');
//If there are subpages under current page
if (!empty($mypages)){
//If the title doesn't already exsist under the current page
if (!in_array($episodetitle, $titleslist)) {
wp_insert_post($seasonepisode);
}
}
//If no subpages exist at all under current page
if (empty($mypages)){
//Probably dont need this, but just to be safe encase of infinate looping issue
if (!in_array($episodetitle, $titleslist)) {
wp_insert_post($seasonepisode);
}
}
wp_reset_postdata();
echo '<li><a href="' . strtolower($episodetitle) . '">' . $episodetitle . ' - ' . $output_episode['name'] . '</a></li>';
}
Based on the suggestion by @MMK, I used the get_pages method and simply fetched the existing post_title values as an array and compared current titles with titles from my new pages