我正在开发一个小插件,激活后会创建一个主题页面,然后一个函数会将该页面设置为已发布。这是我发布的代码:
// function that creates the new ads page on plugin install //
function mjj_create_page ()
{
// Create new page object
$ads_page = get_option(\'mjj_smart_ads_page\');
$ads_new_page = array(
\'post_title\' => \'Smart Ads\',
\'post_content\' => \'\',
\'post_status\' => \'publish\',
\'post_type\' => \'page\'
);
// Insert the page into the database
$ads_page = wp_insert_post( $ads_new_page );
update_option(\'mjj_smart_ads_page\', $ads_page);
// now lets give this new page a groovy template
$ads_page_data = get_page_by_title(\'Smart Ads\');
$ads_page_id = $ads_page_data->ID;
update_post_meta($ads_page_id, \'_wp_page_template\',\'tpl-smart-ads.php\');
}
不知道它的语义是否完美,但它似乎工作正常,并满足了我的需要,但现在我正在尝试设置一个功能,将插件停用,将此创建的页面设置为草稿状态,这样它就不会显示在菜单中,但它似乎不想玩,下面是我的工作:
// function that drafts smart ads page on plugin deactivate //
function mjj_unpublish_page ()
{
$old_ads_page = get_option(\'mjj_old_smart_ads_page\');
$ads_old_page = array(
\'post_title\' => \'Smart Ads\',
\'post_content\' => \'\',
\'post_status\' => \'draft\',
\'post_type\' => \'page\'
);
// Insert the page into the database
$old_ads_page = wp_update_post( $ads_old_page );
update_option(\'mjj_old_smart_ads_page\', $old_ads_page);
}
下面是我的钩子
// create the page to get the info for selling ads and posting ads
register_activation_hook($file, array(&$this, \'mjj_create_page\'));
//while in this block i will also add the deactivate function to unpublish the created page
register_deactivation_hook($file, array(&$this, \'mjj_unpublish_page\'));
正如你所见,我认为设置为draft将包括使用wp\\u update\\u post,但它似乎在停用时工作不正常,我最终会发布一个智能广告页面,一个在draft中
最合适的回答,由SO网友:Bainternet 整理而成
我将此发布为您的另一个解决方案,它基于页面id
/*
$post_id - The ID of the post you\'d like to change.
$status - The post status publish|pending|draft|private|static|object|attachment|inherit|future|trash.
*/
function change_post_status($post_id,$status){
$current_post = get_post( $post_id, \'ARRAY_A\' );
$current_post[\'post_status\'] = $status;
return wp_update_post($current_post);
}
因此,一旦拥有此函数,就可以将其与所创建页面的页面id一起使用:
$ads_page = get_option(\'mjj_smart_ads_page\');
$old_ads_page = change_post_status($ads_page,\'draft\');
update_option(\'mjj_old_smart_ads_page\', $old_ads_page);