WP-Mix

A fresh mix of code snippets and tutorials

Content negotiation for WordPress

Quick PHP script for automatically selecting the best content type based on what the browser accepts. Works as-is for WordPress, or is easily modified to work with any PHP page.

To implement, add the following to your theme’s functions.php file (or plugin file):

function selctype($ctype) {
    if(preg_match("/wp-admin/",$_SERVER["REQUEST_URI"])) {
	    return "text/html";
    }
    $accept=$_SERVER["HTTP_ACCEPT"];
    if(preg_match("|application/xhtml\+xml(;q=0\.([1-9]+))?|i",$accept,$m)) {
		$q1 = $m[2];
		if($q1){
			$q2 = 10;
			if(preg_match("|text/html;q=0\.([1-9]+)?|i",$accept,$m)) {
     			$q2 = $m[1];
     		}
     		if($q1 >= $q2)
				return "application/xhtml+xml";
			else
				return "text/html";
		}
		return "application/xhtml+xml"; 
    } elseif (preg_match("|text/xml(;q=0\.([1-9]+))?|i",$accept,$m)) {
		$q1 = $matches[2];
		if($q1){
			$q2 = 0;
     		if(preg_match("|text/html;q=0(\.[1-9]+)|i",$accept, $m))
     			$q2 = $matches[1];
     		if($q1 >= $q2)
				return "text/xml";
			else
				return "text/html";
		}
	    return "text/xml";
    }
    return $ctype;
}
add_filter('option_html_type','selctype'); ?>

To modify for use outside of WordPress, simply remove or comment out the last line and include in your web pages.

Learn more

Digging Into WordPressWordPress Themes In DepthWizard’s SQL Recipes for WordPress