嗨:)我正在研究我的第一个插件.. 我已经注册了我的自定义帖子类型,其元框和分类。 一切似乎都运行正常,除了当我卸载插件时,我的uninstall.php中的函数不会删除帖子。
这是我的 uninstall.php
// If uninstall not called from WordPress, then exit.
if ( ! defined( 'WP_UNINSTALL_PLUGIN' ) ) {
exit;
}
global $wpdb;
// Delete All Custom Type Posts
$posts = get_posts( array(
'numberposts' => -1,
'post_type' => 'my-custom-post', // $post_type
'post_status' => 'any' ) );
foreach ( $posts as $post ) {
wp_delete_post( $post->ID, true );
}
我到处寻找 - 甚至在其他插件中 - 似乎这是正确的方法...有人可以告诉我为什么它不起作用?或者即使还有其他方式?
答案 0 :(得分:0)
来自codex,
register_uninstall_hook
注册将在用户单击要求插件自行卸载的卸载链接时调用的卸载挂钩。
register_uninstall_hook($file, $callback)
答案 1 :(得分:0)
好的,我调查了一下...... 在这里阅读: https://wordpress.stackexchange.com/questions/98965/get-posts-from-sites-in-multisite
然后我暂时用新的WP_Query(),相同的参数替换了get_posts(),然后用这种方式打印了查询:
$args = array(
'numberposts' => -1,
'post_type' => 'my-custom-post',
'post_status' => 'any'
);
$posts = new WP_Query( $args );
wp_die( sprintf( '<pre><code>%s</code></pre>', print_r( $posts->request, true ) ) );
有了这个结果:
SELECT SQL_CALC_FOUND_ROWS _wpposts.ID FROM _wpposts WHERE 1=1 AND _wpposts.post_type = 'my-custom-post' AND (_wpposts.post_status = 'publish' OR _wpposts.post_status = 'future' OR _wpposts.post_status = 'draft' OR _wpposts.post_status = 'pending' OR _wpposts.post_status = 'private') ORDER BY _wpposts.post_date DESC LIMIT 0, 10
我认为这里的问题是该插件在多站点网络上是活动的,但只在其中一个站点(ID为2)中有我的$ post_type的帖子...
所以我尝试使用switch_to_blog()
使用此函数循环浏览博客:
function my_uninstall_plugin() {
global $wpdb;
if ( function_exists( 'is_multisite' ) && is_multisite() ) {
$blog_sql = "SELECT blog_id FROM $wpdb->blogs WHERE archived = '0' AND spam = '0' AND deleted = '0'";
$blog_ids = $wpdb->get_col( $blog_sql );
if ( $blog_ids ) {
foreach ( $blog_ids as $blog_id ) {
switch_to_blog( $blog_id );
global $post;
$args = array(
'numberposts' => -1,
'post_type' => 'un-custom-post',
'post_status' => 'any'
);
$blog_posts = get_posts( $args );
if($blog_posts) {
foreach ($blog_posts as $blog_post) {
wp_delete_post( $blog_post->ID, true );
}
}
}
restore_current_blog();
}
}
}
现在似乎有效...... 感谢Vidhu Nair和brasofilo的帮助! :)