Installing Memcache For WordPress W3 Total Cache Plugin

Today is a very distracted day. I was busy programming until i lose interest and read up google seo blog. There was this article about google page speed that suddenly makes me feel like speeding up all my website just for some seo benefits. The number one thing i notice about speeding up my website are surrounding caching. Hence, i digged down to my WordPress cache plugin W3 total cache and start exploring him a bit (after 10 months). However i was in a shared environment so the only option other than disk caching would be to install memcache on the server (quite some resources for some speed gain). But it does the trick. My server was using Centos 5.6 with cPanel installed.

Installing Memcache on WordPress Server

Follow the below sequence to get memcache install on your server.

#install require library
yum install libevent libevent-devel
#download the latest memcached. take note i'm downloading version 1.4.6
cd /usr/local/src && wget http://memcached.googlecode.com/files/memcached-1.4.6.tar.gz && tar -xzf memcached-1.4.6.tar.gz && cd memcached-1.4.6
#install it and compile
./configure && make && make install
# make sure memcache starts on boot
touch /etc/init.d/memcached
echo '#!/bin/sh -e' >> /etc/init.d/memcached
echo '/usr/local/bin/memcached -d -m 128 -p 11211 -u nobody -l localhost' >> /etc/init.d/memcached
chmod u+x /etc/init.d/memcached
echo '/etc/init.d/memcached' >> /etc/rc.local
# start memcached
/etc/init.d/memcached
# install memcache
pecl install memcache
# restart apache
/etc/init.d/httpd restart
# test whether we get memcahce
php -r 'phpinfo();' | grep 'memcache'

Upon completing the above steps, you should get yourself the option in W3 total cache plugin to use memcache as an option to use as a cache mechanism.

How to resend username and password to user in WordPress using retrieve_password function

Well, there are no such method where you can resend your existing user a reset password from your side. they must actually click on the "lost password" link and fill up the form in order to retrieve the activation email to reset their password. The method was retrieve_password() which is located in wp-login.php. Hence, you won't be able to use this method and even if you can, you will need to post it over from a form in order to utilized this method. The most easiest way to reuse this method is to recreate it by removing certain condition so that it makes life easier for you.

In my case, my system already has the user email addresses. Hence, all i need to do was to remove the checking for email address and start sending verification from the user whether they wish to reset their password.

/**
 * Handles sending password retrieval email to user.
 *
 * @uses $wpdb WordPress Database object
 *
 * @return bool|WP_Error True: when finish. WP_Error on error
 */
function retrieve_password($user_email) {
	global $wpdb, $current_site;

	$errors = new WP_Error();

	// redefining user_login ensures we return the right case in the email
	$user_login = $user_email;

	do_action('retreive_password', $user_login);  // Misspelled and deprecated
	do_action('retrieve_password', $user_login);



	$key = $wpdb->get_var($wpdb->prepare("SELECT user_activation_key FROM $wpdb->users WHERE user_login = %s", $user_login));
	if ( empty($key) ) {
		// Generate something random for a key...
		$key = wp_generate_password(20, false);
		do_action('retrieve_password_key', $user_login, $key);
		// Now insert the new md5 key into the db
		$wpdb->update($wpdb->users, array('user_activation_key' => $key), array('user_login' => $user_login));
	}
	$message = __('Someone requested that the password be reset for the following account:') . "\r\n\r\n";
	$message .= network_site_url() . "\r\n\r\n";
	$message .= sprintf(__('Username: %s'), $user_login) . "\r\n\r\n";
	$message .= __('If this was a mistake, just ignore this email and nothing will happen.') . "\r\n\r\n";
	$message .= __('To reset your password, visit the following address:') . "\r\n\r\n";
	$message .= '<' . network_site_url("wp-login.php?action=rp&key=$key&login=" . rawurlencode($user_login), 'login') . ">\r\n";

	if ( is_multisite() )
		$blogname = $GLOBALS['current_site']->site_name;
	else
		// The blogname option is escaped with esc_html on the way into the database in sanitize_option
		// we want to reverse this for the plain text arena of emails.
		$blogname = wp_specialchars_decode(get_option('blogname'), ENT_QUOTES);

	$title = sprintf( __('[%s] Password Reset'), $blogname );

	$title = apply_filters('retrieve_password_title', $title);
	$message = apply_filters('retrieve_password_message', $message, $key);

	if ( $message && !wp_mail($user_email, $title, $message) )
		wp_die( __('The e-mail could not be sent.') . "<br />\n" . __('Possible reason: your host may have disabled the mail() function...') );

	return true;
}

The above method take in an email address and send out the email to the user to request a reset of password. You can change the message to your liking but you will need to know the user password in order to use this method. Hope it helps.

WordPress: How to check widgets in dynamic sidebar

There are times when you need multiple dynamic sidebar on your WordPress blog. Espeically when you are trying to customized your WordPress into something more powerful. Creating multiple dynamic sidebar is as simple as writing the following code.

$loop = array('SIDEBAR 1', 'SIDEBAR 2', 'SIDEBAR 3', 'SIDEBAR 4','SIDEBAR 5');
foreach($loop as $item){
if ( !function_exists('dynamic_sidebar') || !dynamic_sidebar($item) )
	echo 'no dynamic sidebar';
}

With a sidebar registration logic in your theme functions.php such as below,

$loop = array('SIDEBAR 1', 'SIDEBAR 2', 'SIDEBAR 3', 'SIDEBAR 4','SIDEBAR 5');
foreach($loop as $item){
	register_sidebar( array(
		'name' => __( $item, 'example' ),
		'id' => $item,
		'description' => __( $item, 'example' ),
		'before_widget' => '<li id="%1$s" class="widget-container %2$s">',
		'after_widget' => '</li>',
		'before_title' => '<h3 class="widget-title">',
		'after_title' => '</h3>',
	) );
}

Everything looks good. You could customized the tag and title before your widget and title. Not until you find yourself having to customized your dynamic sidear with a customized before and after tag.

Adding Before and After Tag On Dynamic Sidebar

Well, its not that hard, just add it as follow and you will get your before and after tag for your sidebar!

$loop = array('SIDEBAR 1', 'SIDEBAR 2', 'SIDEBAR 3', 'SIDEBAR 4','SIDEBAR 5');

foreach($loop as $item){
echo '<div class="'.$item.'">';
if ( !function_exists('dynamic_sidebar') || !dynamic_sidebar($item) )
	echo 'no dynamic sidebar';
}
echo '</div>';

There! all our sidebars have its own wrapper! But i only want these wrapper if there are widget on it! erm...i guess i would need to check whether there is widget on it before i append the wrapper for each sidebar. How do i check whether a widget is used on a dynamic sidebar?

How to check widget is in used on a dynamic sidebar

The problem is simple, the solutions, you would have to dig a bit. The solutions that i managed to get my hand on was is_active_sidebar which tells us whether a particular sidebar contains a widget. Hence, we can perform our code as below,

$loop = array('SIDEBAR 1', 'SIDEBAR 2', 'SIDEBAR 3', 'SIDEBAR 4','SIDEBAR 5');
foreach($loop as $item){
if (is_active_sidebar($item) ){
	echo '<div class="'.$item.'">';
	dynamic_sidebar( $item ); 
	echo '</div>';
}

the above code will determine whether a particular sidebar is active (contain a widget), if it does contain a widget, we can add a wrapper before and after the dynamic sidebar and populate out the contain of this dynamic sidebar within the wrapper tag. For those which doesn't have any widget, we will simply ignore it.

is_active_sidebar doesn't work!

Well, it really doesn't work that is why there is an article from me. ha ha ha. It is actually a small bug in this particular function provided by WordPress. (can't bother to report so i write it out instead) If you look closely into the core code of is_active_sidebar, you will notice that if you pass it either lowercase or index number into this method, you will find that it works perfectly fine. However, if you pass in an uppercase as shown on my example, you will face this problem. The reason is that the method will sanitize the text you provide and this cause your string to go lowercase whereas the sidebar that you have registered was an uppercase. Therefore, it fail. What you have to do is either lowercase your sidebar names or create a logic that lowercase it for you.

Hope it helps someone out there 🙂

WordPress 3.0 Plugin Activation Error – “Headers already sent”

Well, i have been customizing my WordPress a lot to produce something like the food directory or blogshopping tool which required a lot of hack on to WordPress to make everything work perfectly. Recently i have upgraded my WordPress to the latest version 3.0.1. Everything seems fine until one day i decided to enhance my site. Upon activting my WordPress plugin, an error message occurs stating "The plugin generated 3 characters of unexpected output during activation. If you notice “headers already sent” messages, problems with syndication feeds or other issues, try deactivating or removing this plugin.". Although the plugin successfully activated, it seems like there are some problem with the plugin that is causing this. I search high and low for it but couldn't seems to detect any header being sent explicitly without my knowledge.  To make matter worst, this caused all my timthumb (image of the fly) script to malfunction which caused ALL my images to break. Hence, none of the images generated by timthumb were generated on the website. This is disaster!!!  Why is my header being sent when there is NOTHING in my code that is sending it?!!! (panic)

I went to alert my hosting company (hostgator) about this and tried to resolved this on the server level as my test environment which is another host were functioning perfectly without causing me a single problem! However, they couldn't find any cause on their server side that may caused this problem and direct me back to the application problem and asked me to check my code. Puzzled by all the mystery that is happening on my test and live environment. I decided to look further into what could have happened. And here are some of the things that i found but doesn't happen to me.

Extra whitespace / Character

Extra whitespace or character before the tag will caused this to happen. This is a comment mistakes made by many new php developers. But in my case, this wasn't the problem.

My Situation

Soon, i found out my mistake. Apparently, my test environment server setting allows Unicode encoded file type to be read normally. However, the one on Hostgator only allows ANSCII to be read. Hence, all the Unicode encoded files were the culprits that is causing all this problems. It seems like the php setting made on the server can caused this to happen as the file type unknown to the php parser seems to bypassed the php output buffer and sent out the plaintext mime type before everything else which caused my timthumb to not work properly (since image sent in jpg mime instead of plaintext). This might be the reason why WordPress is giving you a message of "The plugin generated 3 characters of unexpected output during activation. If you notice “headers already sent” messages, problems with syndication feeds or other issues, try deactivating or removing this plugin." when you try to activate the plugin. It can also be caused by other plugins builder who are unaware that this might happen as their environment works perfectly and yours doesn't. Oh, the reason why anyone would want to change the encoding from ASCII to other form of encoding can be due to special character or other languages writing that ASCII doesn't support. Hence, changing the file encoding types allows php to display out the correct message. (WordPress is multilingual, this should happen more often than you think :)). Hope it helps 🙂

“You do not have sufficient permissions to access this page.” on plugin admin page after update to WordPress 3.0

Well, if you are having problem with your WordPress plugins after an upgrade to WordPress 3.0, this article might just help you. The error you will being seeing on your WordPress plugins will most likely be located on the admin side of WordPress. You will most likely see the message "You do not have sufficient permissions to access this page." and starts debugging and looking for clues on what is happened suddenly with the new upgrade of WordPress 3.0. (that what happens to me) You will most likely find yourself looking at the function user_can_access_admin_page() which return false and cause you debugging all these in the first place. Then, you will find yourself stuck at line 1407 of wp-admin/includes/plugins.php with the following code.

	if ( isset( $plugin_page ) ) {
		if ( isset( $_wp_submenu_nopriv[$parent][$plugin_page] ) )
			return false;

		$hookname = get_plugin_page_hookname($plugin_page, $parent);
		if ( !isset($_registered_pages[$hookname]) )
			return false;
	}

Now, the culprit is definitely caused by $_registered_pages[$hookname] array variable not being set. Hence, this keep you wonder, "why there wasn't any problem until now until WordPress 3.0?". How do we solve this?

Solutions for plugin "You do not have sufficient permissions to access this page." error

There is an obvious solution for this that is to set the global array varaible of $hookname into it so that it always return a true.

	GLOBAL $_registered_pages;
	$hookname = get_plugin_page_hookname( $plugin_file , '' );
	$_registered_pages[$hookname] = true;

This way, you will bypass the validation easily. This is easy but who want hack when there is a properly way of doing it?

My problem solution

Well, my plugins problems can be solved this way but i believe there is an easier way out. Hence, after some try and reading i suspect there is a stricter rules implemented on WordPress when creating your WordPress plugin. Finally, i get a hold on what is wrong with my plugins that is causing "You do not have sufficient permissions to access this page." on all my plugins admin page. Here's the culprit.

	#Before 3.0
	$plugin_page = add_options_page("Hungred Feature Post List", "Hungred Feature Post List", 10, "Hungred Feature Post List", "hfpl_admin");

	#After 3.0 onwards
	$plugin_page = add_options_page("Hungred Feature Post List", "Hungred Feature Post List", 10, "Hungred-Feature-Post-List", "hfpl_admin");

Take note that the slug parameter is being changed from spaces to dashes. WordPress get_plugin_page_hookname will remove all spaces on your slug parameter instead of leaving it which will give "Hungred Feature Post List" instead of "HungredFeaturePostList". Since there is only "Hungred Feature Post List" exist within the $_registered_pages global array and "HungredFeaturePostList" wasn't being registered. The validation fail and throw me an error page.