wp plugin - force www. in url

Date: 12th October 2007 at 6:21 pm | Filed under: development, plugins, wordpress | Author: Sam Burdge

This nifty little WordPress plugin will force the url to include the 'www.' part of the url string. Useful if you want your address to be displayed in a particular way regardless of how the user types it in. To see how it works delete the www. from your address bar (i.e. http://samburdge.co.uk) and press return. This type of redirection is usualy done by altering the .htaccess file, which some Wordpress users may not have access to. Using a plugin to do this is an easy solution for WordPress users as the setup process is simple, and will be familiar to most of you.

Instructions:

  1. Download the plugin file here: URL to Full URL Plugin (rar) | URL to Full URL Plugin (zip)
  2. Upload the php file into your plugins folder (/wp-content/plugins/)
  3. Go to your plugins page in WordPress and activate the plugin

here's an example of the code:

/*
Plugin Name: URL to full URL
Plugin URI: http://www.samburdge.co.uk
Description: Adds www. to the URL
Version: 1
Author: Sam Burdge
Author URI: http://www.samburdge.co.uk*/
function url_to_full (){
// read the host from the server environment
$host = $_SERVER["HTTP_HOST"];
$host = strtolower($host);
$host = trim($host);
$host = str_replace(':80', '', $host);
$host = trim($host);
$thesite = get_settings('siteurl');
$myarr = explode('://', $thesite);
$final = explode('/', $myarr[1]);
// if the host is not starting with www. redirect the
// user to the same URL but with www
if ($host != $final[0]){
// You an also change the "!=" to "==", if you want to force
// the user to use the domain name without the www.
// send status header, so that search engines or other services
// detect that this is a permanent redirect and not a temporary
header('HTTP/1.1 301 Moved Permanently');
// read the URL the user requested:
$url = isset($_SERVER["REQUEST_URI"]) ? $_SERVER["REQUEST_URI"] : '';
// redirect the user to the new destination:
header('Location: http://'. $final[0] . '' . $url);
// stop the script execution here
exit;
}
}
add_action('init', 'url_to_full');

The plugin has been tested using various formats of permalink structure. If you notice any bugs or faults with the plugin, please leave a comment on this post, as this is the first release of the plugin.

3 Responses to “wp plugin - force www. in url”

  • Comment by Mr Papa
    Date: January 18th, 2008 at 12:37 am

    This is backwards… you should want to take the www out, not put it in… www is old and antiquated…

  • Comment by Sam Burdge
    Date: January 18th, 2008 at 1:01 am

    Hi Mr Papa,
    I also have a plugin for that. Different strokes for different folks…
    S

  • Comment by Walter
    Date: April 6th, 2008 at 8:32 pm

    This is useful for people that want a correctly formatted URL.  Antiquated because people are lazy.

Leave a Comment