假设要快速发布8篇文章。(文章内容暂时为空)。标题分别为:

要求:

代码如下:

function create_wordpress_post_with_code()
{
    $words = array(
        'Download',
        'Upload',
        'Data Structure',
        'Database',
        'Run',
        'Schedule',
        'Engineer',
        'Engineering',
        'Download', // 特意加的,为了下面体现一下小细节
        'Upload', // 特意加的,为了下面体现一下小细节
    );

    $words = array_unique($words); //删除重复项
    sort($words); //按首字母A~Z排序
    foreach ($words as $word) {
        $key_words = strtolower($word); //小写化
        $slug = urlencode(preg_replace("/ /", "-", $key_words)); //URL化
        $post_id = -1;
        $author_id = 1;
        $title = $word;
        $content = ''; //文章内容为空
        $tags = preg_split("/-/", $slug); //如果是单词组,通过“-”拆分

        if (!post_exists_by_slug($slug)) { //判断文章是否存在
            $post_id = wp_insert_post(
                array(
                    'comment_status' => 'closed',
                    'ping_status' => 'closed',
                    'post_author' => $author_id,
                    'post_name' => $slug,
                    'post_title' => $title,
                    'post_content' => $content,
                    'post_status' => 'publish',
                    'post_type' => 'post',
                    'tax_input' => array(
                        "category" => 1, //设置分类
                    ),
                    'meta_input' => array(
                        '_terms_keywords' => $key_words, //设置meta
                    ),
                )
            );
            wp_set_post_tags($post_id, $tags); // 设置标签
        } else {
            $post_id = -2;
        }
    }
}
add_filter('after_setup_theme', 'create_wordpress_post_with_code'); // 触发函数

function post_exists_by_slug($post_slug)
{
    $args_posts = array(
        'post_type' => 'post',
        'post_status' => 'any',
        'name' => $post_slug,
        'posts_per_page' => 1,
    );
    $loop_posts = new WP_Query($args_posts);
    if (!$loop_posts->have_posts()) {
        return false;
    } else {
        $loop_posts->the_post();
        return $loop_posts->post->ID;
    }
}