Archives for September 2012

Prevent WordPress from deleting a post

At first glance it seems as though there are no hooks or filters in WordPress for preventing a post/page deletion. But you can do it by filtering user_has_cap (short for user has capability). This is a very powerful filter, and you can use it to block almost anything in WordPress. It has three parameters:

  • $allcaps (an array of all the capabilities, each one set to true or false)
  • $caps (an array of the capabilities being requested by the current operation)
  • $args (an array of arguments relevant to this operation).
  • When a post is being deleted, $args is set to array ('delete_post', $user_id, $post_id). The capabilities required to allow the deletion are stored in the array $caps, and will vary depending on what type of post is being deleted (e.g. ‘delete_published_posts’). Each capability in $caps corresponds to an item in $allcaps. To prevent the post being deleted, all we need to do is modify $allcaps by setting one of the values listed in $caps to false (e.g. $allcaps[$caps[0]] = false).

    As an example, the following code prevents the last published page of a site being deleted.

    add_filter ('user_has_cap', 'wpcs_prevent_last_page_deletion', 10, 3);
    
    function wpcs_prevent_last_page_deletion ($allcaps, $caps, $args) {
    	global $wpdb;
    	if (isset($args[0]) && isset($args[2]) && $args[0] == 'delete_post') {
    		$post = get_post ($args[2]);
    		if ($post->post_status == 'publish' && $post->post_type == 'page') {
    			$query = "SELECT COUNT(*) FROM {$wpdb->posts} WHERE post_status = 'publish' AND post_type = %s";
    			$num_posts = $wpdb->get_var ($wpdb->prepare ($query, $post->post_type));
    			if ($num_posts < 2)
    				$allcaps[$caps[0]] = false;
    		}
    	}
    	return $allcaps;
    }
    

Using the non-minified version of jQuery in WordPress

If you’re developing in WordPress, you’ll probably have define('SCRIPT_DEBUG', true); in your wp-config.php file, which ensures that WordPress does not load minified javascript files. Unfortunately, because of it’s large size a non-minified version of jQuery is not included in WordPress, which means debugging jQuery related issues can be a real pain. Thankfully, it’s easy to fix, and the code below can be easily be added to your custom developer plugin. The code simply checks which version of jQuery is currently registered, then deregisters it and re-registers Google’s unminified version.

if (defined('SCRIPT_DEBUG') && SCRIPT_DEBUG) {
	add_action ('wp_enqueue_scripts', 'wpcs_init');
	add_action ('admin_enqueue_scripts', 'wpcs_init');
}

function wpcs_init() {
	global $wp_scripts;
	if (isset($wp_scripts->registered['jquery']->ver)) {
		$jquery_version = $wp_scripts->registered['jquery']->ver;
		wp_deregister_script ('jquery');
		wp_register_script ('jquery', "http://ajax.googleapis.com/ajax/libs/jquery/{$jquery_version}/jquery.js");
	}
}