Wordpress:通过数据库创建页面?

时间:2011-12-22 13:40:21

标签: database wordpress

目前我正在开设一个新的旅游网站,但我遇到了一件事:

我列出了我要发布的所有国家/地区,地区和城市。如何快速为所有这些页面创建一个页面:

  • 每个页面都应该是一个子页面,如:country / region / city
  • 每个页面都应该有一个特定的页面模板

请让我知道,提前感谢您的时间和信息!

1 个答案:

答案 0 :(得分:3)

你可以这样做。

<?php
    // $country_list = get_country_list(); // returns list, of the format eg. array('India' => 'Content for the country India', 'Australia' => 'Content for the country Australia')
    // $region_list = get_region_list($country); // Get the list of regions for given country, Assuming similar format as country.
    // $city_list = get_city_list($region); // Get the list of cities for given region, Assuming similar format as country

    /* Code starts here...*/
    $country_list = get_country_list();
    foreach($country_list as $country_title => $country_content) {
        $country_template = 'template_country.php';
        $country_page_id = add_new_page($country_title, $country_content, $country_template);
        // validate if id is not 0 and break loop or take needed action.

        $region_list = get_region_list($country_title);
        foreach($region_list as $region_title => $region_content) {
            $region_template = 'template_region.php';
            $region_page_id = add_new_page($region_title, $region_content, $region_template, $country_page_id);
            // validate if id is not 0 and break loop or take needed action.

            $city_list = get_city_list($region_title);                                       
            foreach($city_list as $city_title => $city_content) {
                $city_template = 'template_city.php';
                add_new_page($city_title, $city_content, $city_template, $region_page_id); 
            }                                                            
        }                                                                
    }                                                                    

    function add_new_page($title, $content, $template_file, $post_parent = 0) {
        $post = array();                                                 
        $post['post_title'] = $title;                                    
        $post['post_content'] = $content;                                
        $post['post_parent'] = $post_parent;                             
        $post['post_status'] = 'publish'; // Can be 'draft' / 'private' / 'pending' / 'future'
        $post['post_author'] = 1; // This should be the id of the author.
        $post['post_type'] = 'page';
        $post_id = wp_insert_post($post);

        // check if wp_insert_post is successful
        if(0 != $post_id) {    
            // Set the page template
            update_post_meta($post_id, '_wp_page_template', $template_file); // Change the default template to custom template
        }                                                
        return $post_id;
    }

警告:确保只执行一次或添加任何验证以避免重复的网页。