Custom Columns on Post Administration Pages

You can now add Custom Columns to Post Administration Pages especially when you are using Custom Post Types. The snippets of code below will help you set up new columns for your post type pages in no time.

add_filter('manage_edit-_columns', 'column_columns');
function column_columns($columns) {
    $columns['column_name'] = 'Column Name';
    return $columns;
}

the above code will register your new Column to the current columns of your Custom Post types. Remember to change <custom post type> with the singular post type name.

add_action('manage_posts_custom_column',  'column_show_columns');
function column_show_columns($name) {
    global $post;
    switch ($name) {
        case 'column_name':
		echo 'Column Value';
        break;
    }
}

The code above will show the value for each row for the selected column specified by your column name.

add_action('admin_head',  'column_admin_head');
function column_admin_head() {
?>


and to top it off. style it with your own CSS through the admin head hook.

WordPress Homepage Pagination

Ever wanted to add Pagination to your homepage list of blogs or your Archive? Well now you can.

Here is a snippet of getting pagination right to your theme file.

function numbered_page_nav($prelabel = '', $nxtlabel = '', $pages_to_show = 6, $always_show = false) {
	global $request, $posts_per_page, $wpdb, $paged;

	$custom_range = round($pages_to_show/2);
	if (!is_single()) {
		if(!is_category()) {
			preg_match('#FROM\s(.*)\sORDER BY#siU', $request, $matches);
		}
		else {
			preg_match('#FROM\s(.*)\sGROUP BY#siU', $request, $matches);
		}
		$blog_post_count = $matches[1];
		$numposts = $wpdb->get_var("SELECT COUNT(DISTINCT ID) FROM $blog_post_count");
		$max_page = ceil($numposts /$posts_per_page);
		if(empty($paged)) {
			$paged = 1;
		}
		if($max_page > 1 || $always_show) {
			echo '';
		}
	}
}

just stick the above code onto your functions.php and replace the post navigation section on your theme with this…

numbered_page_nav();

Canonicalize your WordPress

WordPress recently updated it’s core library to handle Canonicalization of pages and posts to avoid duplicate content(as explained here).

Here is a small snippet of code to provide you with a more flexible and customizable way of making canonical URLs for your site.

function seo_canonical() {
	global $post;
	// We remove WP's canonical function first
	remove_action('wp_head', 'rel_canonical');

	// Do the canonicals
		$canonical = get_bloginfo('url');
		if (is_single() || is_page()) {
			$canonical = get_permalink($post->ID);
		} else if (is_day()) {
			$year = get_query_var('year');
			$month = get_query_var('year');
			$day = get_query_var('day');
			$canonical = get_year_link($year, $month, $day);
		} else if (is_month()) {
			$year = get_query_var('year');
			$month = get_query_var('monthnum');
			$canonical = get_year_link($year, $month);
		} else if (is_year()) {
			$year = get_query_var('year');
			$canonical = get_year_link($year);
		} else if (is_author()) {
			$author = get_query_var('author');
			$canonical = get_author_posts_url($author);
		} else if (is_category()) {
			$cat = get_query_var('cat');
			$canonical = get_category_link($cat);
		} else if (is_tag()) {
			$tag = get_query_var('tag_id');
			$canonical = get_tag_link($tag);
		}
		echo '';
}

add_action('wp_head', 'seo_canonical');

this method will serve well to those who are really into customizing their SEO.

Detect a returning user with Browser cookies

There are a few ways to tackle this problem. Let’s take a look at the easiest way to do this.

basically, we will be using the browser’s COOKIES. These are data stored in your browser about your visit on a website. We will use this to our advantage by having the cookie remember actions for us.

We should start by understanding how COOKIES work.

from the image, we assume the user visits a site for the first time. This action requests data from a server somewhere and return it to you. often, but not always, the returned data requests your browser to store specifics from you. this is stored in a cookie. subsequent visits will then read data stored on the cookie. this cookie will already have data stored in it depending on the site you visited.

on the programmer’s point of view. There is a single PHP function for cookies and existing cookies are already available through the $_COOKIE superglobal.

setcookie (string $name, string $value,int $expire = 0)

what setcookie does is creates a cookie under the name of $name with a value of $value, this is the most important part of the method. the 3rd parameter is a unix timestamp of when the cookie will expire(see last paragraph).

We want to detect whenever a user has already visited our site, we can do this with the following code.

if (isset($_COOKIE['visited'])) {
     // cookie set, so it's a returning visitor
     // display page for returning visitors
} else {
     // cookie not set, so let's "tag" this visitor
     setcookie('visited', 1);
     // display page for first time visitors
}

above, we are checking if a cookie with the name “visited” exists, if it does, we show a page for returning users. else, we create a cookie with the name visited and fill it with a value.

we can also apply this to some examples such as showing a pop up for visitors…

if (!isset($_COOKIE['first_time'])) {
      setcookie('first_time', 1);
     // include popup javascript
     // echo the pop up markup
}  else {
    // subsequent visits will hide the popup
}

remember that cookies will be destroyed on certain conditions, this depends on how you set the cookies in the first place. This process is called expiration.
a cookie expires when the browser is closed, at a certain time in the future or a time that has already passed. cookies can also disappear when a user clears
his browsing history or explicitly removes the cookies from the browser.

Remember an Action using Browser Cookies

So if you want to remember a user’s action, all you need are cookies.

Cookies, as defined by Wikipedia, is also known as web cookie, browser cookie, and HTTP cookie. It is a piece of text stored on a user’s computer by their web browser. A cookie can be used for authentication, storing site preferences, shopping cart contents, the identifier for a server-based session, or anything else that can be accomplished through storing text data.

Let’s focus on the server side for now.

//to signify that the user DID an action, we set a cookie with a numerical value of true
setcookie('user_did_an_action', 1);

//to verify that the user DID do an action, we check for it's existence
if (isset($_COOKIE['user_did_an_action'])) {
     //do something
}

see php manual for the usage of the setcookie method

basically, we call setcookie when an action is done, we then do a check if the cookie exists when we want to do something.

this code is useful for “Remember me” checkboxes. I hope this helped you a bit 🙂

Multisite Global Search

While searching for WordPress’ Search method on Google, I came across this useful Multisite Search Plugin by Grial. It’s a simple plugin that utilizes database views for it’s search routine.

Basically, it enables you to search your site and your network using WordPress’ native search methods. The Plugin’s features include:

  • Search on posts and pages.
  • Clean database when the plugin is deactivated.
  • Put search form into your code.
  • Insert search form in templates using a shortcode:
  • Use type attribute to select vertical form or horizontal form. Default attribute value: vertical.
  • Use page attribute to change results page URI. Default attribute value: globalsearch.
  • Show excerpted results
  • Multisite Global Search Widget. Show a search form in your sidebar.
  • Customizable relative URI for results page.
  • Two different form types, vertical and horizontal.
  • Search across all network blogs or only in your blogs if you are logged.

A very useful Plugin indeed. If you need a Plugin that let’s you search your network, I suggest that you get this.

A very interesting note to remember, while this uses Database Views as it’s method for querying, some hosting accounts might not be able to install this plugin. Your database user should have the CREATE VIEW privilege to be able to activate this wonderful plugin. You can execute this SQL statement logged in as root to be able to achieve this. Surprisingly, Cpanel’s All Privileges isn’t enough.

GRANT CREATE VIEW ON {databasename}.* TO {databaseuser}@{host}
change databasename, databaseuser and host accordingly

Visit the Plugin’s Homepage for more information, or download directly from WordPress.org/extend.

Have a great day everyone.

Recent Comments from All Blogs from your Network

Howdy, we’re here again to share a simple snippet of code to create a widget for your WordPress Blog Network. This piece of code will fetch comments from every site and show it as a simple widget on your sidebar. Very useful for Multisite Installations.

Here is the code. Paste it to your functions.php file on your theme folder and you’re all set.


			

    get_results("SELECT blog_id FROM $wpdb->blogs", ARRAY_A); $old = $wpdb->blogid; $comments = array(); foreach ($blogs as $blog) { $wpdb->set_blog_id($blog['blog_id']); $query = get_comments(array('status' => 'approve', 'number' => 3, 'type' => 'comment')); $count = count($query); for ($i = 0;$i < $count;$i++) { $post = get_post($query[$i]->comment_post_ID); $query[$i]->permalink = get_blog_permalink($blog['blog_id'], $post->ID); $query[$i]->post_title = $post->post_title; } $comments = array_merge($comments, $query); } $wpdb->set_blog_id($old); function cmp($a, $b) { if (strtotime($a->comment_date) == strtotime($b->comment_date)) { return 0; } return (strtotime($a->comment_date) < strtotime($b->comment_date)) ? -1 : 1; } usort($comments, "cmp"); $comments = array_slice($comments, 0, $limit); if ($comments) { foreach ($query as $value) { ?>
  • comment_content; ?> on post_title; ?>

    comment_date)); ?>
  • } } else { ?>
  • There are no Comments in this Network

Have a great day 🙂

WordPress Multisite Custom Registration

There are quite a few plugins that solve this problem, mainly because WordPress’ Multi Site implementation isn’t as flexible and as documented as it’s single installation counterpart. We will try to make a basic custom Multisite Registration with Custom Passwords and ReCaptcha.

Warning: This is a Core Hack. This solution is messy and might break on upgrade. Since, there are no hooks that support this at the time of this writing.

First, you add registration.php to your Theme file. This piece of code hooks to WordPress’ current registration method which is in wp-signup.php


get_error_message('empty_password') ) { ?>
	

get_error_message('empty_confirm') ) { ?>

get_error_message('empty_captcha') ) { ?>

add('empty_password', "Please enter your desired Password below"); } if ($_POST['user_pass'] != $_POST['user_confirm_password'] || $_POST['user_confirm_password'] == '') { $result['errors']->add('empty_confirm', "Please enter your Password again"); } if (!$resp->is_valid) { $result['errors']->add('empty_captcha', "Please enter the letters you see below"); } } return $result; } function show_blogform($result) { $reg = get_option('signup_registration'); $reg[$_POST['user_email']] = $_POST['user_pass']; update_option('signup_registration', $reg); return $result; } ?>

This basically hooks the code to your WordPress installation and let’s it run when the user is on the sign up page. It also validates the passwords and the Captcha so that we don’t get any spam registrations or wrong input.

For this to work though, you need to include this file from your functions.php. Add this line anywhere on your function.php.

include 'registration.php';

You will also need the ReCaptcha PHP Library on the same directory as your registration.php file. You can download at Google. Directory must be named “recaptcha” to work, recaptchalib.php must be directly under the recaptcha directory.

Add this Snippet of code starting at line 698 on ms-functions.php on your wp-includes folder. This line is after $user_id = username_exists($user_login);

...
$reg = get_option('signup_registration');
$password = $reg[$user_email];
unset($reg[$user_email]);
update_option('signup_registration', $reg);
...

This tells WordPress that we will set our own password from our password store.

After doing everything here, you should be bale to see your custom MultiSite Registration Page. You can download the files used here.

I will update the code as neccessary when this can be done as a full blown plugin.

For suggestions or modifications to the existing code. Please comment below.

WordPress Multi-Site Recent Posts Plugin

There have been little information about HOW to display posts from your Multi-site WordPress Blog. Well look no further, this plugin is a simple solution to our predicament.

Basically, what we wanted is to display posts from the blogs on our Network, a Multi-site enabled WordPress installation. So we approached it in a very basic manner and referenced every post saved on all blogs and have a hook listen to them. This hook then records the blog ID and the post ID of the published post inserted or updated from their respected blogs. We then put it on a table that enables our Widget to fetch posts from those blogs. You can control this procedure through the widgets panel provided.

Posts on blogs can also be hidden from the reference if they are explicitly specified. There is a meta box above the publish box that can do this.

Features

  • Fetch Posts from Blogs on your Network
  • Control how Posts are shown on the widget
  • Hide your post from fetching through a Post Meta data
  • Publish your Post to Index Blog
  • ReIndexes every post before Plugin Activation

*Updated: December 1, 2010 “Publish to Index Blog” feature added

The Latest version of the plugin can be downloaded here