<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Konstantin Kovshenin &#187; tricks</title>
	<atom:link href="http://kovshenin.com/tag/tricks/feed/" rel="self" type="application/rss+xml" />
	<link>http://kovshenin.com</link>
	<description>WordPress, Automattic and Open Source</description>
	<lastBuildDate>Mon, 21 May 2012 15:59:33 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.3.2</generator>
<xhtml:meta xmlns:xhtml="http://www.w3.org/1999/xhtml" name="robots" content="noindex" />
		<item>
		<title>Extending Custom Post Types in WordPress 3.0</title>
		<link>http://kovshenin.com/2010/extending-custom-post-types-in-wordpress-3-0/</link>
		<comments>http://kovshenin.com/2010/extending-custom-post-types-in-wordpress-3-0/#comments</comments>
		<pubDate>Mon, 29 Mar 2010 08:31:28 +0000</pubDate>
		<dc:creator>Konstantin Kovshenin</dc:creator>
				<category><![CDATA[WordPress]]></category>
		<category><![CDATA[customization]]></category>
		<category><![CDATA[snippets]]></category>
		<category><![CDATA[tips]]></category>
		<category><![CDATA[tricks]]></category>
		<category><![CDATA[wordpress 3.0]]></category>

		<guid isPermaLink="false">http://kovshenin.com/?p=2119</guid>
		<description><![CDATA[In a previous article about Custom Post Types in WordPress 3.0 I outlined one of the most exciting features coming up in 3.0 and I noticed that people have already started building websites upon these new features. It&#8217;s not a secret that I&#8217;m working on a project myself which involves 3.0 so just like everybody [...]]]></description>
			<content:encoded><![CDATA[<p>In a previous article about <a href="http://kovshenin.com/2010/custom-post-types-in-wordpress-3-0/">Custom Post Types in WordPress 3.0</a> I outlined one of the most exciting features coming up in 3.0 and I noticed that people have already started building websites upon these new features. It&#8217;s not a secret that I&#8217;m working on a project myself which involves 3.0 so just like everybody else, I can&#8217;t wait to see it being released!</p>
<p><span id="more-2119"></span></p>
<p>My project involves a custom post type for real estate and in this post I&#8217;d like to show you some tricks on:</p>
<ul>
<li>Working with custom post types and permalinks (a.k.a the 404 issue)</li>
<li>Using WP_Query to find your custom-typed post</li>
<li>Adding custom meta boxes to your edit post screen</li>
</ul>
<p>We&#8217;ll deal with more code than images today so get a clean copy of <a href="http://wordpress.org/download/nightly/">WordPress 3.0 (Nightly build)</a> to experiment upon. We&#8217;ve seen the <a href="http://codex.wordpress.org/Function_Reference/register_post_type">register_post_type</a> function already which is clearly explained in the Codex and even more clearly in the source code so I expect you read those bits if you haven&#8217;t.</p>
<h2>Permalinks with Custom Post Types</h2>
<p>This is one side of the feature which is not thoroughly explained in the source code, and I&#8217;ve seen many people end up with 404 pages while their permalinks point correctly. The trick here is in the <strong>rewrite</strong> and <strong>_builtin</strong> part. The _builtin parameter simply tells WordPress that the new post type we&#8217;re registering is built in. Most of us specified it as <em>true</em> (and I did too in my previous post) as part of the code was just copied from the core part where Posts, Pages and Attachments were being registered, and those <strong>are built-in</strong>. Built-in post types are handled differently by the core, so make sure you switch that option to <em>false</em>.</p>
<p>The <strong>rewrite</strong> parameter is not too tricky if you went through the sources, it&#8217;s simply an array to specify how would you like your permalinks to look like for this specific custom post type. Let&#8217;s look at an example:</p>
<pre>register_post_type('property', array(
	'label' =&gt; __('Real Estate'),
	'singular_label' =&gt; __('Property'),
	'public' =&gt; true,
	'show_ui' =&gt; true, // UI in admin panel
	'capability_type' =&gt; 'post',
	'hierarchical' =&gt; false,
	'rewrite' =&gt; array("slug" =&gt; "property"), // Permalinks format
	'supports' =&gt; array('title','author')
));</pre>
<p>Straightforward. Now if you registered your custom post type this way, your edit post screen should show you the correct permalink, i.e. /property/post-name which now gets handled by the core rewrite module so you&#8217;ll be able to see the contents of your post if you click on View Page. There, no more 404 errors!</p>
<p>One other way around this would be to use the add_permastruct function of the $wp_rewrite object and manually define what kind of permalink structure you would like to use for your custom type posts. Don&#8217;t forget to filter <strong>post_type_link</strong> if you do.</p>
<p>So how about using different templates for custom post types? Well, you could do that somewhere inside your theme, but I like to hook to the template_redirect action, so here it goes:</p>
<pre>add_action("template_redirect", 'my_template_redirect');

// Template selection
function my_template_redirect()
{
	global $wp;
	global $wp_query;
	if ($wp-&gt;query_vars["post_type"] == "property")
	{
		// Let's look for the property.php template file in the current theme
		if (have_posts())
		{
			include(TEMPLATEPATH . '/property.php');
			die();
		}
		else
		{
			$wp_query-&gt;is_404 = true;
		}
	}
}</pre>
<p><strong>Note:</strong> It has become much easier to use templates with custom post types with WordPress 3.1 and especially 3.2. Take a good look at the new Template Hierarchy ;)</p>
<p>What we did here is looked for our custom post type and redirected it to property.php located in the currently active theme (assuming it&#8217;s there of course). This part may be done in several different ways and mine&#8217;s not the best, but it gives you an idea of how to capture custom posts requests. Let&#8217;s move on to querying.</p>
<h2>WP_Query and Custom Post Types</h2>
<p>This is easier than you think, there&#8217;s absolutely no tricks in here, and it&#8217;s all straight forward. Just like you used to search for posts and pages, you search for your custom post name, in my case it&#8217;s property:</p>
<pre>global $wp_query;
$wp_query = new WP_Query("post_type=property&amp;post_status=publish&amp;posts_per_page=5");</pre>
<p>That&#8217;s it. Custom post types are handled pretty much the same way in WordPress loops, this means that you&#8217;re free to use template tags such as the_title(), the_permalink() and so on.</p>
<h2>Metaboxes for Custom Post Types</h2>
<p>Metaboxes are just as easy as queries. Just take a look at the $page parameter of <a href="http://codex.wordpress.org/Function_Reference/add_meta_box">add_meta_box</a>. That&#8217;s where you have to clearly state which screen should hold your metabox. In my case it&#8217;s property, so here&#8217;s what I got:</p>
<pre>add_meta_box("my-property-meta", "Property Options", "my_property_meta",
    "property", "side", "low");

function my_property_meta() { echo "Boo!"; }</pre>
<p>Awesome, isn&#8217;t it! It&#8217;s also a good idea to fire add_meta_box in the admin_init hook ;) Here&#8217;s a sneak preview of what we&#8217;ve got:</p>
<p><img class="size-full wp-image-2122 alignnone" src="http://kovshenin.com/files/2010/03/custom-post-types-3.png" alt="Extending Custom Post Types in WordPress 3.0" width="680" height="392" /></p>
<p>I&#8217;m not sure where all this is going, but I see people getting excited about this. I see other people who don&#8217;t care and say they could do all the same stuff in the edit post page, then extend all the stuff using custom fields. That&#8217;s true, until you got a say not very computer literate client. I&#8217;d like to see somebody explain custom fields to those types ;) I didn&#8217;t manage to, maybe I haven&#8217;t got the skills, but hey, isn&#8217;t it easier to click, drag &amp; drop, etc? I mean you do use your mouse, don&#8217;t you?</p>
<p>Anyways, let&#8217;s see where this goes. I&#8217;ll be working on the real estate type for some time but I&#8217;d like to hear out your ideas and perhaps some written examples of how we (the themes and plugins developers) could benefit from custom post types and make our clients a tiny bit more happy. Cheers!</p>
<h2>Working Example: Podcast 3.0</h2>
<p>Here&#8217;s something I&#8217;m working at and will hopefully finish this in time for WordPress 3.0. You can look through the source code to see how the Podcast custom post type is registered, the way a meta box is added to it, and the way custom taxonomy is used together with the custom columns in the edit post screen.</p>
<p>There&#8217;s a template_redirect action which fires a theme file called podcast.php which would be the template used to display podcasts so you&#8217;ll get an error if you don&#8217;t create such a file in your theme. Feel free to use the standard template tags inside the file, it goes as an ordinary WordPress loop.</p>
<p><strong>Download:</strong> <a href="http://kovshenin.com/files/2010/03/podcast-30.zip">Podcast 3.0</a> (<strong>update:</strong>outdated) for WordPress.</p>
]]></content:encoded>
			<wfw:commentRss>http://kovshenin.com/2010/extending-custom-post-types-in-wordpress-3-0/feed/</wfw:commentRss>
		<slash:comments>361</slash:comments>
		</item>
		<item>
		<title>Adding mod_rewrite Rules to .htaccess in WordPress</title>
		<link>http://kovshenin.com/2009/adding-mod_rewrite-rules-to-htaccess-in-wordpress/</link>
		<comments>http://kovshenin.com/2009/adding-mod_rewrite-rules-to-htaccess-in-wordpress/#comments</comments>
		<pubDate>Mon, 02 Nov 2009 06:58:34 +0000</pubDate>
		<dc:creator>Konstantin Kovshenin</dc:creator>
				<category><![CDATA[WordPress]]></category>
		<category><![CDATA[actions]]></category>
		<category><![CDATA[filters]]></category>
		<category><![CDATA[hooks]]></category>
		<category><![CDATA[mod_rewrite]]></category>
		<category><![CDATA[plugins]]></category>
		<category><![CDATA[tips]]></category>
		<category><![CDATA[tricks]]></category>

		<guid isPermaLink="false">http://kovshenin.com/?p=1548</guid>
		<description><![CDATA[This is all about the Twitter Friendly Links plugin I&#8217;ve been working on lately. You might have noticed some 404 issues in the comments section on the plugin page, this in most cases is due to caching fail. I wrote about this a while ago when I was working on W3 Total Cache compatibility where [...]]]></description>
			<content:encoded><![CDATA[<p>This is all about the <a href="http://kovshenin.com/wordpress/plugins/twitter-friendly-links/">Twitter Friendly Links</a> plugin I&#8217;ve been working on lately. You might have noticed some 404 issues in the comments section on the plugin page, this in most cases is due to caching fail. I wrote about this a while ago when I was working on <a href="http://wordpress.org/extend/plugins/w3-total-cache/">W3 Total Cache</a> compatibility where all I had to do is set the wp_query object&#8217;s is_404 variable to false. Then again, the other caching plugins didn&#8217;t understand that, so I came up with my own links caching mechanism &#8211; direct cache with .htaccess ;)</p>
<p>The <a href="http://codex.wordpress.org/Function_Reference/WP_Rewrite">WP_Rewrite article</a> in the Codex pretty much explains everything, except that it&#8217;s pretty difficult to add custom rewrite rules to .htaccess via WordPress, as even wp_query object&#8217;s non_wp_rules is handled like this:</p>
<pre>RewriteRule ^Pattern /Substitution [QSA,L]
</pre>
<p>With the trailing slash and &#8220;Query String Append + Last Rule&#8221; hard-coded in the WordPress core. Well here&#8217;s how I managed to do Permanent 301 redirects to absolute URLs.</p>
<p>First of all add an action and a filter. My plugin code is wrapped up in a class (and I encourage you to do the same for maximum compatibility):</p>
<pre>add_action('generate_rewrite_rules', array(&amp;$this, 'generate_rewrite_rules'));
add_filter('mod_rewrite_rules', array(&amp;$this, 'mod_rewrite_rules'));
</pre>
<p>The generate_rewrite_rules action is the place where we will add some rules to non_wp_rules, then modify (or customize) in the mod_rewrite_rules filter. Here&#8217;s the generate_rewrite_rules function which I&#8217;m hooking to:</p>
<pre>function generate_rewrite_rules() {
	global $wp_rewrite;
	$non_wp_rules = array(
		'simple-redirect/?$plugin_name' =&gt; 'http://google.com',
		'one-more-redirect/?$plugin_name' =&gt; 'http://yahoo.com'
	);

	$wp_rewrite-&gt;non_wp_rules = $non_wp_rules + $wp_rewrite-&gt;non_wp_rules;
}
</pre>
<p>I used the string &#8216;plugin_name&#8217; in every rule just to make sure that I don&#8217;t edit anyone else&#8217;s rewrite rules further on. You&#8217;ll understand what I mean once you read the next part of the code. Also make sure you use single quotes as double quotes would make $plugin_name a variable.</p>
<pre>function mod_rewrite_rules($rules) {
	$rules = preg_replace('/^(RewriteRule ^.*+/?$)plugin_name (/)(.*) ([QSA,L])$/im', '1 3 [R=301,L]', $rules);
	return $rules;
}
</pre>
<p>There you go, so the rules are modified using a simple regular expression, which in .htaccess will turn out to be:</p>
<pre>RewriteRule ^simple-redirect/?$ http://google.com [R=301,L]
RewriteRule ^one-more-redirect/?$ http://yahoo.com [R=301,L]
</pre>
<p>The regex is not perfect though, just a sketch. I believe it will not work if the RewriteBase is not set to / but you get my point ;) The rules are written to .htaccess when you access or save changes in the Permalinks section in the admin panel or whenever wp_rewrite object&#8217;s flush_rules is called. Now be careful, you cannot call flush_rules anywhere outside the admin panel (although you may try to link with a few includes &#8211; wp-admin/includes/misc.php and wp-admin/includes/files.php before flushing) but in my case I&#8217;ll just go with the publish_post hook.</p>
]]></content:encoded>
			<wfw:commentRss>http://kovshenin.com/2009/adding-mod_rewrite-rules-to-htaccess-in-wordpress/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>WordPress: The template_redirect Hook Returns 404</title>
		<link>http://kovshenin.com/2009/wordpress-template-redirect-hook-404/</link>
		<comments>http://kovshenin.com/2009/wordpress-template-redirect-hook-404/#comments</comments>
		<pubDate>Fri, 16 Oct 2009 08:04:39 +0000</pubDate>
		<dc:creator>Konstantin Kovshenin</dc:creator>
				<category><![CDATA[WordPress]]></category>
		<category><![CDATA[actions]]></category>
		<category><![CDATA[cache]]></category>
		<category><![CDATA[hacks]]></category>
		<category><![CDATA[hooks]]></category>
		<category><![CDATA[plugins]]></category>
		<category><![CDATA[s3]]></category>
		<category><![CDATA[tricks]]></category>
		<category><![CDATA[wp_query]]></category>

		<guid isPermaLink="false">http://kovshenin.com/?p=1412</guid>
		<description><![CDATA[This is a real quick one. I&#8217;ve started using the W3 Total Cache plugin a few days ago which I&#8217;m totally satisfied with. Unlike the WP Super Cache plugin, W3TC can keep the caches in memory via memcached, serve the static content through CDNs. The guys at W3 Edge promised to add Amazon CloudFront compatibility [...]]]></description>
			<content:encoded><![CDATA[<p>This is a real quick one. I&#8217;ve started using the <a href="http://wordpress.org/extend/plugins/w3-total-cache/">W3 Total Cache</a> plugin a few days ago which I&#8217;m totally satisfied with. Unlike the WP Super Cache plugin, W3TC can keep the caches in memory via memcached, serve the static content through CDNs. The guys at W3 Edge promised to add Amazon CloudFront compatibility which I&#8217;m very excited about. As we all know (I guess) Mashable is running WordPress, and guess what! They&#8217;re using W3 Total Cache too, so if they could trust those guys, then I&#8217;m totally in. Their support over Twitter is awesome, you don&#8217;t even have to look for them! Just tweet your problem mentioning &#8220;W3 Total Cache&#8221; or &#8220;W3TC&#8221; &#8211; they&#8217;ll find you via search and help you solve whatever your issue is.</p>
<p>Anyways, that being said, after writing my post announcements to Twitter via <a href="http://kovshenin.com/wordpress/plugins/twitter-friendly-links/">Twitter Friendly Links</a> some peeps shouted out that I was returning 404 errors on all of my short links. Strange, thought I, as I was able to see everything fine. Looking at the settings of the plugin I realized that I, as a logged in user, weren&#8217;t looking at cached pages, so I turned that off and guess what! I got those 404s. Creepy! After a little talk over Twitter and IM with the guys at W3 Edge, I started to look through the caching plugin code. It&#8217;s so well-written and I&#8217;ve actually learned a couple of techniques out there! Anyways, the reason I was getting 404s was because W3 TC looked at the $wp_query object and it&#8217;s $is_404 variable, which I don&#8217;t know why (Frederick from W3 Edge mentioned a redirection issue with WordPress) was returning true on all of my Twitter friendly links!</p>
<p>I figured out that the template_redirect hook (which is not documented in the WordPress Codex at all) didn&#8217;t quite do what I wanted it to. The easiest way out was adding a couple of lines before the redirect actually happened:</p>
<pre>global $wp_query;
$wp_query-&gt;is_404 = false;
</pre>
<p>And guess what, it worked! This may be not the smartest decission but hey, it&#8217;s working! One more workaround would be adding a regular expression to the W3 Total Cache page settings, exclude &#8220;[0-9]+/?$&#8221; which would not cache any .com/1234 queries, but that&#8217;s not so reliable for a couple of reasons. First, why not cache if we can cache? And second, what if we&#8217;re using Twitter Friendly Links in alphanumeric mode? That would mean &#8220;[0-9a-zA-Z]+/?$&#8221; which would probably match for all the other top-level pages, thus we&#8217;re losing all the benefits from caching. Meh!</p>
<p>I guess this is not the only place where the template_redirect action would return a 404. Some plugins that define their own permalinks through the template_redirect hook (WP Polls for poll results for instance, not sure though) will also get 404s if they don&#8217;t set it to false in $wp_query. Many wordpress websites have profile pages which are not actual pages in the database, but are handled through the template_redirect action for .com/profile_name sort of permalinks which is indeed cool. I&#8217;m actually planning on using it with one of my upcoming projects and I&#8217;m really glad I sorted it out.</p>
<p>So the big shoutout goes to W3 Total Cache and the <a href="http://www.w3-edge.com/">W3 Edge</a> team!</p>
]]></content:encoded>
			<wfw:commentRss>http://kovshenin.com/2009/wordpress-template-redirect-hook-404/feed/</wfw:commentRss>
		<slash:comments>8</slash:comments>
		</item>
		<item>
		<title>Multiblog WordPress: Eeek! No Database Connection</title>
		<link>http://kovshenin.com/2009/multiblog-wordpress-error-establishing-a-database-connection/</link>
		<comments>http://kovshenin.com/2009/multiblog-wordpress-error-establishing-a-database-connection/#comments</comments>
		<pubDate>Wed, 05 Aug 2009 08:41:26 +0000</pubDate>
		<dc:creator>Konstantin Kovshenin</dc:creator>
				<category><![CDATA[blogging]]></category>
		<category><![CDATA[WordPress]]></category>
		<category><![CDATA[hacks]]></category>
		<category><![CDATA[tips]]></category>
		<category><![CDATA[tricks]]></category>

		<guid isPermaLink="false">http://kovshenin.com/?p=1156</guid>
		<description><![CDATA[I tried browsing to www.kovshenin.com this morning and was pretty sure I&#8217;ll get the usual redirect, but no. I got an &#8220;Error establishing a database connection&#8221;. Right, it seems that www.kovshenin.com is not defined in the wp-config.php file we created earlier this week (Multiple Sites Driven By One WordPress Installation Part II) so here&#8217;s a [...]]]></description>
			<content:encoded><![CDATA[<p>I tried browsing to www.kovshenin.com this morning and was pretty sure I&#8217;ll get the usual redirect, but no. I got an &#8220;Error establishing a database connection&#8221;. Right, it seems that www.kovshenin.com is not defined in the wp-config.php file we created earlier this week (<a href="http://kovshenin.com/2009/multiple-sites-driven-by-one-wordpress-installation-2/">Multiple Sites Driven By One WordPress Installation Part II</a>) so here&#8217;s a workaround (and we&#8217;re switching back to example.org and example-two.org):</p>
<pre>$wp_multi = array(
    "example.org" =&gt; array(
        "DB_NAME" =&gt; "example",
        "DB_USER" =&gt; "example-user",
        "DB_PASSWORD" =&gt; "example-pass",
        "DB_HOST" =&gt; "example-host"
    ),

    "example-two.org" =&gt; array(
        "DB_NAME" =&gt; "example-two",
        "DB_USER" =&gt; "example-two-user",
        "DB_PASSWORD" =&gt; "example-two-pass",
        "DB_HOST" =&gt; "example-two-host"
    )
);
$server_name = str_replace("www." , "", strtolower($_SERVER["SERVER_NAME"]));
$wp_settings = $wp_multi[$server_name];
</pre>
<p>There. And we also got rid of an error we&#8217;d get if we typed eXamPle.org in the address bar.</p>
<p>I&#8217;m thinking of a way to wrap this up in some plugin or a little hack, or perhaps a super-short step-by-step tutorial, so that setting up multiple websites one a single wordpress bundle would be easier than ever. If you have any suggestions feel free to speak ;)</p>
]]></content:encoded>
			<wfw:commentRss>http://kovshenin.com/2009/multiblog-wordpress-error-establishing-a-database-connection/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>

