我正在使用wp_insert_posts
以编程方式创建帖子,但它会不断生成相同的帖子。我正在使用一个名为irl-today
. 如果我使用page
自定义帖子类型,但在“irl today”自定义帖子类型上无休止地生成帖子。
有没有办法只生成一次帖子?这就是我的功能。php:
<?php
if ( !is_admin() ) { /* Main site*/
} else { /* Admin */
if( ! get_page_by_title(\'Archive\') ) {
$my_post = array( \'post_title\' => \'Archive\',
\'import_id\' => \'1041\',
\'post_type\' => \'irl-today\',
\'post_name\' => \'archives\',
\'post_content\' => \'All of DailyBayou publications.\',
\'post_status\' => \'publish\',
\'comment_status\' => \'closed\',
\'ping_status\' => \'closed\',
\'post_author\' => 1,
\'menu_order\' => 0,
\'guid\' => site_url() . \'/archives\' );
$PageID = wp_insert_post( $my_post, FALSE ); // Get Post ID - FALSE to return 0 instead of wp_error.
}
};?>
即使在
if { } else { };
最合适的回答,由SO网友:Jacob Peattie 整理而成
如果要一次性创建特定页面,则可以在创建页面后将选项保存到数据库中,然后在尝试重新创建之前检查该值是否存在。如果存储了页面的ID,还可以检查帖子是否仍然存在,如果不存在,则重新创建帖子。
add_action(
\'admin_init\',
function() {
// Check if there\'s a record of the page.
$archives_page_id = get_option( \'dailybayou_archives_page_id\' );
// If the page hasn\'t been created yet, or doesn\'t exist anymore...
if ( ! $archives_page_id || ! get_post( $archives_page_id ) ) {
// ...create the page.
$archives_page_id = wp_insert_post(
[
\'post_title\' => \'Archive\',
\'import_id\' => \'1041\',
\'post_type\' => \'irl-today\',
\'post_name\' => \'archives\',
\'post_content\' => \'All of DailyBayou publications.\',
\'post_status\' => \'publish\',
\'comment_status\' => \'closed\',
\'ping_status\' => \'closed\',
],
false
);
// Save a record of the page.
update_option( \'dailybayou_archives_page_id\', $archives_page_id );
}
}
);