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;
    }
    

How to make sure the correct domain is used in WPML

If you use the WPML multilingual plugin for WordPress, and have each language on a different domain, you may have noticed that WPML does not ensure that all URLs in your page point to the correct domain. You might notice, for example, that images are pulled from the main domain, even when you’re accessing a page on another language’s domain. It’s rare that this causes problems for your site, (although it theoretically could if you have .htaccess rules in place to stop hot-linking, or if you have enabled https for one domain and not for the others), but it’s likely to have a small negative impact on your SEO.

If you want to fix this, you need to filter all of the WordPress functions that return a URL. There are lots of them, and I haven’t collected them all together. But there’s enough here to give you the picture, and if you find something is not being filtered it should be easy enough to find the appropriate function and add it to the code.

//Add all the necessary filters. There are a LOT of WordPress functions, and you may need to add more filters for your site.
add_filter ('site_url', 'wpcs_correct_domain_in_url');
add_filter ('get_option_siteurl', 'wpcs_correct_domain_in_url');
add_filter ('stylesheet_directory_uri', 'wpcs_correct_domain_in_url');
add_filter ('template_directory_uri', 'wpcs_correct_domain_in_url');
add_filter ('post_thumbnail_html', 'wpcs_correct_domain_in_url');
add_filter ('plugins_url', 'wpcs_correct_domain_in_url');

/**
* Changes the domain for a URL so it has the correct domain for the current language
* Designed to be used by various filters
* 
* @param string $url
* @return string
*/
function wpcs_correct_domain_in_url($url){
    if (function_exists('icl_get_home_url')) {
        // Use the language switcher object, because that contains WPML settings, and it's available globally
        global $icl_language_switcher;
        // Only make the change if we're using the languages-per-domain option
        if (isset($icl_language_switcher->settings['language_negotiation_type']) && $icl_language_switcher->settings['language_negotiation_type'] == 2)
            return str_replace(untrailingslashit(get_option('home')), untrailingslashit(icl_get_home_url()), $url);
    }
    return $url;
}

Don’t edit child themes – use grandchild themes!

Child themes are the easiest way to style WordPress sites. Rather than create a site from scratch, you can create a theme that shares most of its code and styling with a parent theme. The benefits of creating a child theme instead of editing the main theme is that if the main theme gets updates, none of your changes are lost.

But what if you need to modify a child theme? If you’re working with a Framework, like Genesis, it’s very likely you are already using a child theme – and editing that brings about all the disadvantages of editing a parent theme – you lose your changes if the theme is ever updated.

The solution is surprisingly simple. Instead of editing the child theme, create a grandchild theme. It’s very similar to creating a child theme, except you do it via a plugin. You add your custom functions to the plugin, just as you normally would in functions.php (though remember your plugin will be called much earlier than functions.php, so you’ll need to make sure that any code in your plugin only runs when an action is fired). Use the wp_register_style and wp_enqueue_style functions to add your CSS (by default a grandchild theme will add your CSS to the CSS of the parent or child theme, but you can change this behaviour by using the wp_dequeue_style function). Finally filter the result of the get_query_template function to control which PHP files are executed when a page is requested.

A typical grandchild theme might look like this:

/*
Plugin Name: Grandchild Theme
Plugin URI: https://www.wp-code.com/
Description: A WordPress Grandchild Theme (as a plugin)
Author: Mark Barnes
Version: 0.1
Author URI: https://www.wp-code.com/
*/

// These two lines ensure that your CSS is loaded alongside the parent or child theme's CSS
add_action('wp_head', 'wpc_theme_add_headers', 0);
add_action('init', 'wpc_theme_add_css');

// This filter replaces a complete file from the parent theme or child theme with your file (in this case the archive page).
// Whenever the archive is requested, it will use YOUR archive.php instead of that of the parent or child theme.
add_filter ('archive_template', create_function ('', 'return plugin_dir_path(__FILE__)."archive.php";'));

function wpc_theme_add_headers () {
	wp_enqueue_style('grandchild_style');
}

function wpc_theme_add_css() {
	$timestamp = @filemtime(plugin_dir_path(__FILE__).'/style.css');
	wp_register_style ('grandchild_style', plugins_url('style.css', __FILE__).'', array(), $timestamp);
}

// In the rest of your plugin, add your normal actions and filters, just as you would in functions.php in a child theme.

The two actions to add the CSS should be familiar to you (although you may also want to read this post). The filter is the important function. You can create as many of these as you wish, for different pages. Supported pages include:

  • index
  • 404
  • archive
  • author
  • category
  • tag
  • taxonomy
  • date
  • home
  • front_page
  • page
  • paged
  • search
  • single
  • attachment

If you want more control before deciding which template file to give to WordPress, create a proper function and insert your logic code into it:

add_filter ('archive_template', 'emw_archive_template', 10, 1);

function wpc_archive_template ($suggested_templates) {
	// Your logic here
	if ($test_passed)
		return $template_file;
	else
		return $alternative_template_file;
}

Automatically add Lorem Ipsum text to blank WordPress pages

If you’re creating a new WordPress theme, it can be helpful to have some filler text in your pages. The snippet below adds a few paragraphs of lorem ipsum text to any blank post or page by filtering the_content. The text is retrieved from the www.lipsum.com site, and is cached, site-wide, for one hour using the set_transient and get_transient functions.

add_filter ('the_content', 'emw_custom_filter_the_content');

/**
* Returns Lorem Ipsum text for blank pages
* 
* @param string $content - the page's current contents
* @return string
*/
function emw_custom_filter_the_content ($content) {
	if ($content == '') {
		if ($c = get_transient ('lipsum'))
			return $c;
		$content = wp_remote_get ('http://www.lipsum.com/feed/json');
		if (!is_wp_error($content)) {
			$content = json_decode (str_replace ("\n", '</p><p>', $content['body']));
			$content = '<p>'.$content->feed->lipsum.'</p>';
			set_transient ('lipsum', $content, 3600); // Cache the text for one hour
			return $content;
		}
	} else
		return $content;
}