Avoid trouble with filter and the_content in WordPress

One problem i just came across while working on my WordPress plugin that many might not know is the danger of making mistakes on filter and the_content action hook. The importance of 'the_content' action hook and where this particular small sentence will affect your overall WordPress and caused it to malfunction if WordPress plugin developer used it carelessly (scary stuff). In this article, i will show you some of the mistake i made and what are the consequences in screen shot to inform WordPress plugin developers what will happen to WordPress when this two is being used wrongly.

What is 'the_content and filter?

In case you don't know what is filter and the_content action hook, filter is used in WordPress to filter the data between WordPress and its database. Short to say, you can manipulate the data retrieved from WordPress database before it shows out. The 'the_content' action hook is used to tell WordPress to print the content of the post, short to say, i am trying to manipulate the data from WordPress before displaying out to the end-user.

Problem

i have a test site which use to debug and test my plugin in a test environment before implementing it on the LIVE site. Everything goes well on the TEST since there is only one plugin but problem came when there are more than one plugin which hell can happen, not only deal to naming or method contradiction but some other unknown problem can occurred. One of the very rarely unforeseen problem is the filter and 'the_content' action hook problem. By the way, I am using WordPress v2.8 for testing.

Consequences

Many might not know what will 'the_content' affect the internal and external of WordPress (Many might aware of the external consequences but not the internal ones). Let's take a look at one of my plugin tester site (http://1sitedaily.com) who reported these problems to me. In the post page, she was typing the post and this particular red thing came out of no where!
unidentify-red-bar-wp

This red post was either the previous post or the current post! It was caused by the use of 'the_content' action hook imappropriately (imagine how irritating will it be for the user). Once she clicked save as draft or worst when it suddenly auto save as draft and empty page is return!

post-save-draft-empty

Although the page was saved, this is not acceptable! Internally, this is what will happen to the Administration panel when 'the_content' action hook is not being used appropriately. Nonetheless, if this method is not used appropriately for the external part, the content might not even be showing!

missing-front-panel-content

This has missing content on the front page.

missing-sing-page-content

Same post with missing content on single page.

What happen?

So what really happen there? It is actually quite a silly mistake make by developers with PHP (even me) that usually forgotten by them when writing for a open source application. Deep in our mind, we think this is a new language with all the rule define by WordPress but its actually just PHP.The external mistakes was,

function article_example($content)
{
	if($content != "")
	{
		echo $content;
	}
	else
	{
		echo "NOTHING FOUND";
	}
}
add_filter('the_content', 'article_example');

Nothing seems wrong here, right? It will print out the relevant codes instructed on the template. But this is where the problem comes internally. Since filter event handler is also attached in the administration panel, anything that trigger 'the_content' in the administration panel will result in the above function execution (this means post page also uses 'the_content' to output the display we see on the editor). So, the red box appeared in WordPress was due to Ajax function being executed behind WordPress to save as draft and the function above was executed which duplicated a content out of the post. When the 'save as draft' button was clicked, a empty page (or any other words in the page which does not return the user back to the post page) was returned because the above function was executed and the echo statement was called. In PHP, during any execution or redirection was occurring, and echo statement will stop the page from redirecting. That is the main reason why the post page was not shown and other page appeared in front of the user.

The internal mistakes are something like this,

function article_example($content)
{
	$content = "The content contains: ".$content;
}
add_filter('the_content', 'article_example');

which the developers forgotten to output or return the correct value back to WordPress. The other thing that might occurs will be semantic errors or logic error.

Correct way of displaying filter and 'the_content'

Save yourself some time, in WordPress to echo a statement when using the filter statement ALWAYS use return,

function article_example($content)
{
	return "The content contains: ".$content;
}
 add_filter('the_content', 'article_example');

returning the value using filter will also resulting the display of the modified content! No problem will occurs like the above one when using return instead of echo although it also do the job!

Tutorial: How to create a simple vibration effect for your form box with jQuery

This effect can be used to validate certain criteria in your form. Other than using highlighter to highlight the error area, we can use a more creativity approach by vibrating that particular input box to alert the user. This tutorial demonstrate a very easy way to understanding how vibration works on the web and how it can be used in your web design.

The Concept

In order to perform a vibration effect, we must first understand how will a person feel during an earthquake. The whole world will be shaking right? In a more defined term, it means that the object are moving on it own, not us. Similarly, we are staring at the monitor while the boxes are moving on its own! Next question, how do you move? The answer to my question will be the same answer on how the boxes move but not by legs. Rather, the position will be moved. In conclusion, we will try to move the position left and right, up and down to simulate vibration.

The Code

Coding part will be split into 2 part. The structural and jQuery part. The CSS part is fairly simply to understand since we are just aligning them to the center and that's it.

HTML

The following will be the only thing we need in here.

<div id="frame">
	<div id="container">
		<div class="box" id="box1">
		<p>Username<input type='text' size='20'></p>
		<p>Password<input type='text' size='20'></p>
		<p><input type='button' value='Submit' id='activate'/></p>
		</div>
	</div>
</div>

We will only use the 'frame' and 'activate' ID in this tutorial. You can safely ignore all other structure as it will not affect the vibration. The reason is we are shaking the most outer box which is 'frame' and an event handler is attached on 'activate'.

jQuery

The confusing part may be the jQuery code. But we will only need to know certain variable in order for this to work. The variables are,

  var interval = 30;
  var duration= 1000;
  var shake= 3;
  var vibrateIndex = 0;
  var selector = $('#frame');
  var stopVibration;
  var vibrate;

Let me explain the variable shown above in a well indented manner,

  • interval: this is used to set the duration for each movement. eg, every 30 millisecond it will move left,right,top or bottom once.
  • duration: this is used to set the duration for the whole effect. eg, it will vibrate for 1000 millisecond
  • selector: this is the jQuery selector we are going to apply the vibrate with
  • stopVibration: this is the method that will stop the vibration after 'duration' variable
  • vibrate: this is the method that will start the vibration
  • vibrateIndex: this is the index that setInterval provides when used to tell 'stopVibration' which vibration to stop

It should be easy to understand the variables needed for this effect to accomplished. Now for the 'stopVibration' and 'vibrate' method explanation:

	var vibrate = function(){
	$(selector).stop(true,false)
	.css({position: 'relative', 
	left: Math.round(Math.random() * shake) - ((shake + 1) / 2) +'px', 
	top: Math.round(Math.random() * shake) - ((shake + 1) / 2) +'px'});
	}

Let's start with 'vibrate'. The above code will take the selector and stop whatever animate it is performing and set the box position as relative so it will move starting from his original position. We set the left and top randomly with a mathematics calculation. So it will move itself left or top randomly. (change the equation to make it vibrate differently)

	var stopVibration = function() {
	clearInterval(vibrateIndex);
	$(selector).stop(true,false)
		.css({position: 'static', left: '0px', top: '0px'});
	};

'stopVibration' will stop the interval with the index given and return the box to its original position. That's it!

Lastly, we will need to add an event handler to the button for it to vibrate!

	$('#activate').click(
	function(){	
	vibrateIndex = setInterval(vibrate, interval);
	setTimeout(stopVibration, duration);
	});

The button click will be attached with an event handler click that will use setInterval to vibrate the outer container in every 'interval' given (move left right top down randomly in every 'interval'). This will caused it to vibrate forever. Thus, we will have to use 'setTimeout' function to stop the vibration by placing the method 'stopVibration' and the 'duration' it wants to vibrate. And it is as simple as that. The final code will be:

$(function() {
  var interval = 30;
  var duration= 1000;
  var shake= 3;
  var vibrateIndex = 0;
  var selector = $('#frame');
	$('#activate').click(
	function(){	
	vibrateIndex = setInterval(vibrate, interval);
	setTimeout(stopVibration, duration);
	});

	var vibrate = function(){
	$(selector).stop(true,false)
	.css({position: 'relative', 
	left: Math.round(Math.random() * shake) - ((shake + 1) / 2) +'px', 
	top: Math.round(Math.random() * shake) - ((shake + 1) / 2) +'px'});
	}
	
	var stopVibration = function() {
	clearInterval(vibrateIndex);
	$(selector).stop(true,false)
		.css({position: 'static', left: '0px', top: '0px'});
	};

});

That is all you need to make your own vibrate effect.

The Demo

You can get and view the demo files from the following link:

Tutorial: jQuery wrap doesn’t work in IE

This is something happen to me a while ago when i am testing my WordPress plugin over different browser (testing cross browser issue). Every browser work well (Firefox, Opera, Chrome, Safari) but IE went wrong. Not surprising IE is the king for being different and causing most problem to developers (well known fellow). Oddly, IE is pointing its finger on one of the line related to jQuery wrap manipulation operation. Weird.

Problem

After debugging a while, i manage to find the problem that is happening with IE and not with other browsers. I used wrap operation to insert a form into a div container (to perform a asynchronous upload over different browser and try not to knock on WordPress style sheet etc.). So the form should wrap over the div container as stated in jQuery documentation. However, in IE it couldn't seems to find this particular new form that was inserted through the wrap operation (scratch head). Since this is a JavaScript DHTML operation, obviously it won't show during view source (at least not for IE). Through the error line instructed by IE browser it indicated that the particular form ID could not be found (form doesn't exist). jQuery warp doesn't support IE 7? Nah..

Solution

So what is going on? Many jQuery users will like to write a wrap operation in this way (including me)


$('#example').wrap('<form id="form2" name="form" action="#" method="POST" enctype="multipart/form-data" >');

This is perfectly alright to wrap a form over some div block. Nothing seems to be wrong as it can be declare this way. Well, most of us will do that since it doesn't add additional word to lengthen the instruction which always make it a bit difficult to read (due to jQuery chaining). However, if you declare it this way using the wrap operation, IE will not work! The wrap operation basically fail without showing any error indicating that the new form which was instructed to create was not there. Good news is that it is not really jQuery fault that it doesn't work when declaring a wrap operation this way. In order for jQuery v1.3 to work in IE using the wrap operation, the declaration must be in this form


$('#example').wrap('<form id="form2" name="form" action="#" method="POST" enctype="multipart/form-data" ></form>');

seems no differences between the two code. But the key is the closing tag which is that ONLY requirement for IE to work flawlessly. Without the closing tag it will not work.

Demo

let me show you a demo to illustrate the differences between the two declaration using the following JavaScript.


$(function(){
	$('#wrong').wrap('<form id="form1" name="form" action="#" method="POST" enctype="multipart/form-data" >');
	$('#correct').wrap('<form id="form2" name="form" action="#" method="POST" enctype="multipart/form-data" ></form>');
});

function withoutCloseTag()
{
	if(document.getElementById('form1') != null && document.getElementById('form1') != "undefined")
	{
		alert("We found wrap for button 'IE with problem'");
	}
}

function withCloseTag()
{
	if(document.getElementById('form2') != null && document.getElementById('form2') != "undefined")
	{
		alert("We found wrap for button 'IE without problem'");
	}
}

The script will alert if the usage of wrap is successful and when fail it will not show any alert message. Try this in IE with other browser. You will find that the second declaration work flawlessly over all browser while the first declaration will only work on all browser except IE (IE no pop out).

Conclusion

Unlike some jQuery tutorial online that teaches the basic of jQuery that indicates the first method of declaration work (without closing tag). It is necessary for jQuery developers to know the differencces between declaring a DHTML operation using jQuery that a closing tag will make a differences when your application is serving different browser.

$(function(){
$('#wrong').wrap('
');
$('#correct').wrap('
');
});
function withoutCloseTag()
{
if(document.getElementById('form1') != null && document.getElementById('form1') != "undefined")
{
alert("We found wrap for button 'IE with problem'");
}
}
function withCloseTag()
{
if(document.getElementById('form2') != null && document.getElementById('form2') != "undefined")
{
alert("We found wrap for button 'IE without problem'");
}
}

Tutorial: How to get post id when using publish_post action hook in WordPress

This topic may seems stupid to some plugin developers but it may really surprise you. Most of you will just say, "Hey, just use the WordPress global variable, $post. Issue solved!". Yes, it is stated as global variable across WordPress developers and it should be globally available. Surprisingly, IT IS NOT~. I spend hours researching for an answer which are not document anywhere and finally decided to write a post to inform some plugin developer who are still unaware of such condition.

Problem

I wanted to attached a function to an event, publish_post whenever the user click on publish or update button when they have done with their post in WordPress. Usually, global variable $post will solve this problem easily. But for the case of publish_post action hook, this is not the case. The global variable $post which is accessible in any area of WordPress is not accessible when a user clicked on the publish button. The global variable $post will return 'null' instead of the post object which contain all the post data. Let the nightmare began.

Solution

Usually, we will see this on top of the post,

url-wordpress

The URL of the post page contains the post ID! So the smart alex me try to be funny and use a $_GET['post'] to try retrieve the post id after i have failed miserably on the global variable, $post upon user clicked on publish button. With hope, it fail again. So i was thinking, maybe there exist some post data instead of a get data. So i try to use $_POST['post'] to retrieve the post id. Fail (expected). Since i am using a function to tried all these methods (post,get, global variable) as shown below,

function example()
{
global $wpdb;
global $post;
echo var_dump($post)."<br />";
echo $_POST['post']."<br />";
echo $_GET['post']."<br />";
}
add_action('publish_post', 'example');

There might be a problem retrieving global variable in my function so i try doing it outside the method as shown below,

global $post;
echo var_dump($post)."<br />";
echo $_POST['post']."<br />";
echo $_GET['post']."<br />";

function example()
{
global $wpdb;
global $post;
echo var_dump($post)."<br />";
echo $_POST['post']."<br />";
echo $_GET['post']."<br />";
}
add_action('publish_post', 'example');

It still fail! Nightmare. If you look at WordPress Plugin API, on the publish_post description it state this,

Runs when a post is published, or if it is edited and its status is "published". Action function arguments: post ID.

Action function arguments: post ID? Looks like using this action hook required a function argument post ID. So i tried this instead.

function example($post_ID)
{
global $post;
echo $post_ID."<br />";
echo var_dump($post)."<br />";
echo $_POST['post']."<br />";
echo $_GET['post']."<br />";
}
add_action('publish_post', 'example');

Surprisingly, i got it! The ID is retrieved this way! No global variable available if you are using publish_post action hook!

Conclusion

I believe the reason why the global variable,$post  is not available during publish_post action hook was because the details of the post has been updated by the user and the information in the global variable are not updated. Thus, only the ID is available in the global variable if there is one. So to avoid unnecessary usage of memory, the global variable, $post was not created instead. The WordPress version for this was 2.8. Hope this help out a bit.

Tutorial: How to add action to excerpt in WordPress

In case some of you don't know what the title of this post means, it has to do with building plugin for WordPress. Let me explain  a little on what does an action means in WordPress. Basically, we can add a function to an action or event (whatever you called it) in WordPress to perform some task before or after the action or event has occured.

Problem

The reason why i bought this post up was because i nearly get frustrated working on my WordPress plugin because there wasn't any action listed in WordPress plugin API that stated an action that can be attached to an event before or after an excerpt is being bought out! Search all over the place, fail. So i decided to do a trial and guess with these action thing for my plugin to attached an event when an excerpt is being bought out.

Solution

In case you might not aware how a excerpt is being printed out on the template, they used


the_excerpt();

This will print out the excerpt in your WordPress. So i tried using the_excerpt to be placed into my WordPress add_action statement as shown below,


add_action('the_excerpt', 'hpt_attach_excerpt');

'hpt_attach_excerpt' is the function call when excerpt is being triggered. To my surprise, it work! But it will only display whatever the function, 'hpt_attach_excerpt' contains as shown below. no_exerpt_attached

So where is my regular excerpt? It seems like if i attached a defined action used in WordPress that are not listed in the WordPress Plugin API, it will be overwritten by my own method 'hpt_attach_excerpt'. I digged again to find the method in WordPress site that will provide me with the missing excerpt i was looking for. Fail. So i digged into the source code of WordPress and managed to find the key method that return the excerpt of a post, get_the_excerpt(). get_the_excerpt() is the based method that retrieve the data from the database to the_excerpt for it to filter.  Now i write the code as follow,


function hpt_attach_excerpt()
{
echo "This is the function 'hpt_attach_excerpt' produce";
echo get_the_excerpt();
}
add_action('the_excerpt', 'hpt_attach_excerpt');

Looking back to the display to check whether the attachment has completed.

found-excerpt-attached

There it is! Both my function message and my excerpt message!

P.S: You can use add_filter if you do not wish to overwrite the default function of 'the_excerpt' function.

Conclusion

If you have read through the post, you might aware that this is not only restricted to adding action for excerpt. This shows that we can add any WordPress function that are not defined in WordPress Plugin API (Offical action available) as action and rewrite or append any type of instruction to the default action given by WordPress. Can't find your action needed to perform your WordPress plugin? You just found the answer! Hope this can help many developers who are working on their plugin! ( Thanks for all the wonderful plugin developed! )