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.

Posted in Tutorials | Tagged , , | Leave a comment

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();
Posted in Tutorials | Tagged , | Leave a comment

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.

Posted in Tutorials | Tagged , , , | Leave a comment

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.

Posted in Tutorials | Tagged , | Leave a comment

Code to Search all Multi Site Network: Multisite Global Search Plugin

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.

Posted in Wordpress Plugin | Tagged , , | Leave a comment

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 🙂

Posted in Tutorials | Tagged , , | 1 Comment

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.

Posted in Tutorials | Tagged , , | 2 Comments

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

Posted in Wordpress Plugin | Tagged , , | Leave a comment

Exit Pop-up Plugin

Following my previous write up for Blocking users from exiting your site giving you one last chance to advertise, I have incorporated the script used from that tutorial and made a WordPress Plugin.

I have added a lot of Improvements to the existing code listed below.

  • Pixel control for the size of the CSS Popup layer
  • Specify Pages for the Script to Work in
  • Catch the user before your Page closes
  • Direct control over the Messages shown on the Alert Box and the CSS Popup Layer

This plugin requires the latest version of WordPress or jQuery installed.
jQuery 1.4.4 is already included in the download package.

Download this plugin here.

If you find bugs or have suggestions to improve the existing code, please comment below.

Posted in Wordpress Plugin | Tagged , , | 2 Comments

Exit Pop-up Script

Hi, We all know that everyone is a propective client right? I am here to show you how you can get that user who just clicked close on your web page. Let’s have this user stay before he decides to go on his way and never come back.

First, all you will need is a little bit of HTML knowledge. I’ll walk you through the code so you don’t need to worry.

First let’s add our favorite Javascript Library…

We then setup our script by defining some variables on a new <script> tag.


This will define how our Script runs.

  • detectblur is a boolean(true/false) value that determines whether the script should be fired whenever the user leaves your page without closing it. (e.g, change tab window)
  • interrupt is a boolean(true/false) value that determines whether the script should be fired whenever the window is going to be closed and interrupt the user with a custom message defined below.
  • interrupt_message a string value that is displayed on the interrupt confirmation box is fired.

We then paste the following code before the ending <script> tag.

var blurred = false; // flag that determines whether the screen is blurred or not
var mousestart = 0; // the placeholder where the user first entered the page from above(often, the tab)
var captured = false; // flag that determines whether mousestart was captured or not

$(function(){
	// The catch method. basically appends an html div that is filled with content from your own unblockable div then sets the appropriate flags
	var unblockable_catch = function() {
		if (!blurred) {
			$('body').append('

'); $('.unblockable .content').html($('#unblockable_content').html()); blurred = true; mousestart = 0; captured = false; $('#unblockable_catch').css({top:-10}); } } // The raw javascript interrupt screen that fires before the window gets closed if (interrupt) { window.onbeforeunload = function () { unblockable_catch(); // fires the catch method return interrupt_message; // your custom interrupt message defined from above } } // A bunch of event hooks $('body').append('
'); if (detectblur) { $(window).blur(unblockable_catch); } $('#unblockable_catch').live('mouseover', unblockable_catch); $('#unblockable_close input').live('click', function() { $('.unblockable_div, #unblockable_dim').fadeOut(500, function(){ $(this).remove(); blurred = 0; setTimeout(function(){$('#unblockable_catch').css({top:0});}, 5000); }); }); // A way we can determine where the tab is located. $(window).blur(function() { //so whenever the window is not focused we reset the mousestart and captured variables mousestart = 0; captured = false; }); // Whenever the user clicks the tab, we determine that the first mousemove over the page is from the tab location $(window).mousemove(function(e){ if (!captured) { if (e.pageY < 10) { mousestart = e.pageX - 185; // we set it half the width of the invisible catch div captured = true; // so we don't capture again $('#unblockable_catch').css({left: mousestart, top: -10}); setTimeout(function(){$('#unblockable_catch').css({top:0});}, 2500); } } }); });

Whoah! That's a lot of code there! well you don't need to understand all of it actually but if you do, read the comments above.

Now everything that we need for the script to run is given, let's get to styling. Copy the following code inside the <head> tag.


What's awesome is that our markup can be styled using the .unblockable class without being used directly in the script.

Then finally, our markup

	

Provide your own design and customize to your heart's content.

I hope this tutorial helped you catch that client in his attempt to escape 🙂

You can check out a Live Demo here.
For the script used in this tutorial, Download here.

This plugin requires the latest version of jQuery.

I have also made this script as a Plugin version for WordPress with added features and options. Check it out here.

If you see corrections or suggestions to the existing code, please comment below.

Posted in Tutorials | Tagged , | 3 Comments