我正在尝试使用wp\\u insert\\u post在我的模板文件中的当前页面下动态插入一页/多页,但是我需要首先检查当前页面下是否已经存在页面标题,如果不存在,则运行代码并创建页面,但如果标题仅存在于当前页面下,则不希望它在当前页面下创建重复页面。
这个get_page_by_title
似乎要检查整个站点地图中是否存在该页面,如果标题存在,则不会创建该页面,但我只需要检查当前页面下是否存在该页面,因为在其他父页面下会有标题相同的页面
e、 g级
我的网站。com/oneparent/child页面标题
我的网站。com/twoparent/child页面标题
请参阅下面的代码。是否有更好的方法使用get\\u page\\u by\\u title,但只检查当前页面的子页面?还是有更好的方法来做到这一点?
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>\';
}
根据@MMK的建议,我使用了get\\u pages方法,简单地获取现有的post\\u title值作为一个数组,并将当前标题与新页面的标题进行比较
最合适的回答,由SO网友:MMK 整理而成
$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);
}