现在WordPress主题功能是越来越强大,都会创建很多辅助页面,当页面过多的时候,手动创建就会很麻烦,所以需要自动创建页面,那么WordPress启用主题后如何自动创建页面?
废话不多说了,下面是WordPress启用主题自动创建页面的代码,加在functions.php中就行了。
//WordPress启用主题自动创建页面
function ashu_add_page($title,$slug,$parent_slug,$page_template=”){
$allPages = get_pages();//获取所有页面
$post_parent=0;
$exists = false;
foreach( $allPages as $page ){
//通过页面别名来判断页面是否已经存在
if( strtolower( $page->post_n**e ) == strtolower( $slug ) ){
$exists = true;
}
//获取父页面ID
if($parent_slug!=””){
if(strtolower( $page->post_n**e ) == strtolower( $parent_slug ) ){
$post_parent=$page->ID;
}
}
}
if( $exists == false ) {
if($post_parent!=0){
$par**= array(
‘post_title’ => $title,
‘post_type’ => ‘page’,
‘post_n**e’ => $slug,
‘comment_status’ => ‘closed’,
‘ping_status’ => ‘closed’,
‘post_content’ => ”,
‘post_status’ => ‘publish’,
‘post_parent’=>$post_parent,
‘post_author’ => 1,
‘menu_order’ => 0
);
}else{
$par**= array(
‘post_title’ => $title,
‘post_type’ => ‘page’,
‘post_n**e’ => $slug,
‘comment_status’ => ‘closed’,
‘ping_status’ => ‘closed’,
‘post_content’ => ”,
‘post_status’ => ‘publish’,
‘post_author’ => 1,
‘menu_order’ => 0
);
}
$new_page_id = wp_insert_post($par**);
//如果插入成功 且设置了模板
if($new_page_id &**p;&**p; $page_template!=”){
//保存页面模板信息
update_post_meta($new_page_id, ‘_wp_page_template’, $page_template);
}
}
}
简单使用
在切换主题时自动检查创建页面,代码如下:
//WordPress启用主题自动创建页面
add_action( ‘after_switch_theme’, ‘create_tb_page’ );
function create_tb_page(){
ashu_add_page(“用户中心”,”member”,””,”pages/member.php”);
ashu_add_page(“修改**”,”password”,”member”,”pages/member-password.php”);
ashu_add_page(“修改资料”,”info”,”member”,”pages/member-info.php”);
ashu_add_page(“积分”,”level”,”member”,”pages/member-level.php”);
}
暂无评论内容