0 Comments

WordPress is Catching My Attention Again

Ever since Ghost was released I’ve been incredibly interested in installing and learning the platform–even toying with the idea of switching over completely. Alas, on my host, this is impossible due Ghost’s dependency on node.js, and so I was left reeling just a bit.

It was in this fugue state over the past month that I discovered just how much I truly love WordPress again, particularly with the introduction of version 3.8 and the updates being made to the admin screen. I’m very happy with what is happening there, and I have faith in the platform as a whole. Yes, it can be a little bloated; yes the plugins aren’t always well written; but none of these things really detract from the flexibility of the system.

I’m excited to develop for WordPress again, and I can’t wait to see what’s coming next.


1 Comments

Updating The Gallery Markup

I’ve wanted to use the WordPress gallery shortcode functionality for quite some time on my site–not that I would overuse or abuse it or anything–but it seemed rather useful for including multiple images in a post if I happened to want to do so.

The unfortunate part about using it is the resulting markup that ends up being generated by the shortcode. The original code utilizes a definition list (dl) for each image in the gallery, and inserts a line break (br) after each row. Not the cleanest code in the world. I’m also using a lightbox to display the full size image and could not utilize its native gallery functionality with the markup as is. What’s a man, or woman, to do? Improve the situation, that’s what!

Improved Markup

<section id="gallery-1" class="gallery gal-col-3 clearfix">
    <figure class="gallery-item">
        <a rel="gallery-1" href="img/link/src.jpg" title="generic title"><img src="img/link/src-thumb.jpg" class="attachment-images-thumb" alt="generic title" height="220" width="220"></a>
       <figcaption class="wp-caption-text gallery-caption">Generic Caption</figcaption>
    </figure>
    <figure class="gallery-item">
        <a rel="gallery-1" href="img/link/src.jpg" title="generic title"><img src="img/link/src-thumb.jpg" class="attachment-images-thumb" alt="generic title" height="220" width="220"></a>
       <figcaption class="wp-caption-text gallery-caption">Generic Caption</figcaption>
    </figure>
</section>

This code is much cleaner, and perhaps a little more HTML5 centric using the figure and figcaption tags, while also eliminating the page breaks. In the spirit of OOCSS, I’m keeping most of the original classes intact. How am I styling that up? Glad you asked.

The Basic CSS

I’ve created a base set of styles to get you started. I’ve purposely not styled certain items in this tutorial/plugin because you should modify these to fit your purposes.

.gallery {
    margin:1.5em 0;
}
.gallery-item {
    float: left; 
    padding: 1%;
   -webkit-box-sizing: border-box;
   -moz-box-sizing: border-box;
   -o-box-sizing: border-box;
   box-sizing: border-box;
}
.gallery img {
    max-width: 100%;
    height: auto;    
    display: block;
    margin: 0 auto;
}
/* A gallery image caption */
.gallery .gallery-caption { }
 .gal-col-1 .gallery-item {
      width:100%;
      float: none;
      padding: 1% 0;
  }
  .gal-col-2 .gallery-item {
      width:50%;
  }
  .gal-col-3 .gallery-item {
      width:33.3333%;
  }
  .gal-col-4 .gallery-item {
      width:25%;
  }
  .gal-col-5 .gallery-item {
      width:20%;
  }
  .gal-col-6 .gallery-item {
      width:16.6667%;
  }
  .gal-col-7 .gallery-item {
      width:14.2857%;
  }
  .gal-col-8 .gallery-item {
      width:12.5%;
  }

Time To Change It All

You might be thinking, “that’s all well and good, but how do I get that beautiful markup on my site?” I’m glad you asked. There are a couple of approaches you could take. On my site I chose to create a new function in my theme functions file to manage the short code because that’s all I needed for my setup. For our purposes here, a plugin makes distribution easier.

If you wanted to go the theme function route, you can follow along to get a basic overview. First, unregister the default gallery shortcode in order to setup our own.

// replace gallery shortcode
remove_shortcode('gallery');
add_shortcode('gallery', 'mm_gallery_shortcode');

Next, we need to modify the default gallery shortcode function. One of the first sets of things we’ll change are the default attributes in order to ensure we’re using semantically correct tags.

extract(shortcode_atts(array(
    'order'      => 'ASC',
    'orderby'    => 'menu_order ID',
    'id'         => $post->ID,
    'itemtag'    => 'figure',
    'icontag'    => '',
    'captiontag' => 'figcaption',
    'columns'    => 3,
    'size'       => 'images-thumb',
    'include'    => '',
    'exclude'    => ''
), $attr));

Then we’ll reflect those changes just a little further down in the function.

$itemtag = tag_escape($itemtag);
$captiontag = tag_escape($captiontag);
$icontag = tag_escape($icontag);
$valid_tags = wp_kses_allowed_html( 'post' );
if ( ! isset( $valid_tags[ $itemtag ] ) )
    $itemtag = 'figure';
if ( ! isset( $valid_tags[ $captiontag ] ) )
    $captiontag = 'figcaption';
if ( ! isset( $valid_tags[ $icontag ] ) )
    $icontag = '';

The last portion I want to highlight in the code is the actual output. I changed the gallery div tag into a section tag and modified the classes to reduce their number. I then add one to reflect the column number. Using str_replace I also add a rel attribute to our image link. Additionally, I have eliminated all line breaks from the output.

function mm_gallery_shortcode($attr) {
    /*A LOT of excluded CODE.....*/
    $gallery_div = "<section id='$selector' class='gallery gal-col-{$columns} clearfix'>";
    $output = apply_filters( 'gallery_style', $gallery_style . "\n\t\t" . $gallery_div );
    $i = 0;
    foreach ( $attachments as $id => $attachment ) {
         $link = isset($attr['link']) && 'file' == $attr['link'] ? wp_get_attachment_link($id, $size, false, false) : wp_get_attachment_link($id, $size, true, false);
         $link = str_replace( '<a href', '<a rel="'. $selector .'" href', $link );
         $output .= "<{$itemtag} class='gallery-item'>";
         $output .= "$link";
         if ( $captiontag && trim($attachment->post_excerpt) ) {
             $output .= "<{$captiontag} class='wp-caption-text gallery-caption'> " . wptexturize($attachment->post_excerpt) . " </{$captiontag}>";
         }
        $output .= "</{$itemtag}>";
    }
    $output .= "</section>\n";
    return $output;
}

The code I’m highlighting above is incomplete, so I recommend you use the plugin if you have no clue what you’re doing. Otherwise, use it as a jumping off point.

Example

View Project At GitHub


0 Comments

WordPress Admin Customization

Update: I’ve made some modifications to this plugin that ultimately make it work better. I won’t be updating the code in this overview to reflect the changes, but have uploaded a new version for download. One of the changes I made was to create an options page that will let you switch off dashboard widgets. Some of the others were necessitated by the recent WordPress 3.4 update.


We’re all creatures of habit, in many ways. We like to work in the same environment, with the same sets of tools, year after year, and we’re accustomed to living that way. In the online world, we’re not supposed to be like that, but we are. We arrange our desktops just so on a new system, we like our folder structure a certain way, and we like to work with familiar technology.

That’s not to say that we shouldn’t be adapting constantly.

I’m no different in my habits and preferences, and so there are a couple of things I like to do when I install WordPress for the first time. These are just a few of the things that help me get acclimated, and also to customize the experience for myself and whatever client I’m installing this for.

First things first, I’m going to set up a plugin to handle all of this functionality rather than add it to a theme’s functions.php file. That way I’m not wedded to the theme, or trying to transfer functions over when I change my mind.

/**
 * @package CUSTOM_Site_Functionality
 * @version 1.5
 */
/*
Plugin Name: Custom Admin
Plugin URI: http://mikemattner.com
Description: Custom admin functionality.
Author: Mike Mattner
Version: 1.5
Author URI: http://mikemattner.com/
*/

class CUSTOM_Site_Functionality {
   static $instance;
   var $plugin_url;
	
   public function __construct() {
      self::$instance = $this;
      $this->init();
      define('PLUGIN_URL',plugin_dir_url( _FILE_ ));
      $this->plugin_url = PLUGIN_URL . "directory";
   }

   public function init() {
       /*....WordPress hooks to activate custom functions here.....*/
   }
   
   /*....functions will be placed here.....*/

}

$mm = new CUSTOM_Site_Functionality;

Alright, so we have our initial class and constructor set up, ready to go so we can start to add some customization functions. First and foremost, I’m not a big fan of the typefaces in use by default, so I try to grab something I like just a little bit better. In this case PT Sans served through the Google Fonts API.

// Google Fonts Code
public function add_google_fonts() {
echo '<script type="text/javascript">
      WebFontConfig = {
         google: { 
              families: [\'PT+Sans:400,400italic,700,700italic\']
          }
      };
      (function() {
         var wf = document.createElement(\'script\');
         wf.src = (\'https:\' == document.location.protocol ? \'https\' : \'http\') +
              \'://ajax.googleapis.com/ajax/libs/webfont/1/webfont.js\';
         wf.type = \'text/javascript\';
         wf.async = \'true\';
         var s = document.getElementsByTagName(\'script\')[0];
         s.parentNode.insertBefore(wf, s);
      })();
      </script>';
}

Now, this function alone isn’t particularly useful, but as you’ll see I add this to any page I want to use that font on. Below, I’m adding the javascript to whatever I’ll be adding to the head tags of the admin screen right along side of a custom style sheet I’m adding.

One of the first things I used to install was an admin theme plugin called Fluency; however, since the maturation of the 3.x versions of WordPress, Fluency is no longer compatible and that’s a damn shame. I’ve tried my best to replicate that look, and so I add this function to call my stylesheet.

/************* CUSTOM ADMIN *****************/  
public function cc_custom_css() {
   $this->add_google_fonts();
   echo '<link rel="stylesheet" href="' . $this->plugin_url . '/assets/css/admin.css">';
 }

After adding that, I also like to change the footer text. In most cases I use this to brand the admin page a little bit for clients.

//add attributions to footer.
public function modify_footer_admin () {
   echo 'Your custom text.';
}

Now that the admin theme is set, I add the necessary code to change the look of the login screen to match it. On top of that, there are a couple of other changes I make (and I cannot remember where I ever got these from, but the login_url and login_title function are not mine originally), but I also change the logo link and title to match your site so that it is no longer branded WordPress.

/************* CUSTOM LOGIN PAGE *****************/
 // calling your own login css so you can style it 
 public function cc_login_css() {
   $this->add_google_fonts();
   echo '<link rel="stylesheet" href="' . $this->plugin_url . '/assets/css/login.css">';
 }

// changing the logo link from wordpress.org to your site 
 public function cc_login_url() { return get_bloginfo('url'); }

// changing the alt text on the logo to show your site name 
public function cc_login_title() { return get_option('blogname'); }

On the dashboard of the admin, there are far too many useless widgets, at least in most of my use cases. This function will eliminate EVERYTHING. You don’t want that, so you should pick and choose which ones you want or don’t want.

// disable default dashboard widgets
public function disable_default_dashboard_widgets() {	    
   remove_meta_box('dashboard_right_now', 'dashboard', 'core');// Right Now
   remove_meta_box('dashboard_recent_comments', 'dashboard', 'core'); // Comments
   remove_meta_box('dashboard_incoming_links', 'dashboard', 'core');// Incoming Links
   remove_meta_box('dashboard_plugins', 'dashboard', 'core');// Plugins Widget
   remove_meta_box('dashboard_quick_press', 'dashboard', 'core');// Quick Press
   remove_meta_box('dashboard_recent_drafts', 'dashboard', 'core');// Recent Drafts
   remove_meta_box('dashboard_primary', 'dashboard', 'core');// WordPress Blog
   remove_meta_box('dashboard_secondary', 'dashboard', 'core');// WordPress News
 }

Now place the following actions and filters in the init() function to hook them to various WordPress functions.

//custom admin styling
add_action( 'admin_head', array($this,'cc_custom_css') ); //admin css
add_action( 'admin_menu', array($this,'disable_default_dashboard_widgets') );//disable some default dashboard widgets
remove_all_actions('in_admin_footer',1001); //remove footer text
add_filter('admin_footer_text', array($this,'modify_footer_admin')); //add footer attribution
		
// calling it only on the login page
add_action('login_head', array($this,'cc_login_css') );           //add login css
add_filter('login_headerurl', array($this,'cc_login_url') );      //change login url
add_filter('login_headertitle', array($this,'cc_login_title') );  //change login title

Anyway, I could go on and on about my admin customizations, but this is the place I start every time. It’s basic, and simple to modify. Frankly, if you’re using this, you should know what you’re doing, otherwise it won’t be too useful for you.

I’m providing it as a simple download, so use it, modify it, and improve it if you like.

View Project At GitHub


2 Comments

Upgrade to WordPress 3.3

I actually had not been following the latest WordPress developments too closely, and so I was quite pleasantly surprised by what the upgrade to WordPress 3.3 offered in terms of looks and functionality. But…

There were a few things that I had some issues with. First, I absolutely hate that the toolbar is on by default and apparently can’t be turned off without losing some important functionality. The toolbar is my least favorite feature of all the newer WordPress features. It’s ugly and intrusive. Why are you guys so focused on pushing this thing? Is it because of WordPress.com? I get it’s usefulness in that context, perhaps, but with the WordPress.org implementation it gets in my way more often than not.

I create custom plugins for all of my WordPress installations with some custom functionality and admin modifications appropriate to their contexts. Apparently a few of those were sloppily built because as soon as I upgraded, they promptly broke. There was just one line I screwed up in regards to calling a function within a class (typo), but it was something I didn’t notice as I never really ran those plugins through rigorous testing.

One of my favorite plugins for modifying the administration screen is Dean Robinson’s Fluency Admin. Unfortunately the update seems to not be compatible with it. Not one to be deterred, I went about modifying the new admin css to look at least passingly like Fluency.

If you were interested in doing the same, you could run this code through your functions.php file in a pinch, or better yet add it in a plugin:

function like_fluency_css() {
    echo '<style>
*,body {font-family: helvetica, sans-serif;} 
        img#header-logo{display: none;} 
        #adminmenu div.wp-menu-image {float: left;width: 1px;height: 28px;} 
        #adminmenu .wp-menu-image a{display: none;} 
        #wp-admin-bar-wp-logo{display: none;}
        #adminmenuback, #adminmenuwrap {background-color: #222;border-color: #444;border-right-color: #ddd;}
        #adminmenu li.wp-menu-separator {display: none;}
        #adminmenu div.separator {border-color: #0e6ac8;}
        #adminmenu a.menu-top, .folded #adminmenu li.menu-top, #adminmenu .wp-submenu .wp-submenu-head {border-top-color: #444;border-bottom-color: #000;}
        #adminmenu a {color:#fff;}
        #adminmenu .wp-submenu a {color:#777;}
        #adminmenu a:hover, #adminmenu li.menu-top>a:focus, #adminmenu ul.wp-submenu a:hover {color: #fff;}
        #adminmenu li.menu-top:hover>a, #adminmenu li.menu-top.focused>a, #adminmenu li.menu-top>a:focus {background-color: #000;text-shadow: 0 -1px 0 rgba(0, 0, 0, 0.4);}
        #adminmenu li.wp-not-current-submenu:hover>a {border-top-color: #000;border-bottom-color: #000;}
        #adminmenu li.wp-not-current-submenu .wp-menu-arrow {border-top-color: #000;border-bottom-color: #000;background: #000;}
        #adminmenu li.wp-not-current-submenu .wp-menu-arrow div {background: #000;border-color: #000;}
        #collapse-menu {color: rgba(255,255,255,0.3);}
        #collapse-menu:hover {color: rgba(255,255,255,1.0);}
        #collapse-menu:hover #collapse-button {border-color: rgba(255,255,255,0.4);background-color: #333;background-image: -moz-linear-gradient(center bottom , #333, #444);}
        #collapse-button {border-color: rgba(255,255,255,0.2);background-color: #000;background-image: -moz-linear-gradient(center bottom , #111, #000);}
        #adminmenu .awaiting-mod, #adminmenu .update-plugins, #sidemenu a .update-plugins, #rightnow .reallynow {background-color: #464646;box-shadow: 0 1px 0 rgba(255, 255, 255, 0.5);color: #FFFFFF;}
        .folded #adminmenu .wp-submenu-head {border-bottom-color: #ccc;border-top-color: #ccc;}
        .folded #adminmenu li.wp-has-current-submenu, .folded #adminmenu li.current.menu-top {border-bottom-color: #6D6D6D;border-top-color: #808080;}
    </style>';
}
add_action('admin_head', 'like_fluency_css'); //remove logo from admin

There will be more in the days to come, but for now, I’m happy with the progress the team continues to make, and thanks for a great, free product!


4 Comments

Weather? Here’s Your Weather

So, I got bored one day and decided that I wanted to make a weather widget for WordPress. Sort of. I thought that I needed one for a WordPress theme I was thinking about making. As per my previous experience, I couldn’t quite find one that fit the bill, and some were just downright cumbersome in implementation. A veritable nightmare.

When I first started development, I wasn’t too keen on what API/xml data feeds to use, so I went with the ever popular Weather.com XML data feed. Development was a bear because the terms of use were incredibly restrictive. You had to display their logo, which is fine, but then you HAD to display four links that were meant to generate click-throughs for them in some fashion; and all of this had to be visible near the weather data itself. Ok, I said to myself, I can deal with that, even if it makes the whole thing ugly.

This whole thing is kind of funny to me. But hey, you have to monetize that data.

Two weeks later, they decided to end the free XML data service in favor of a different API model. I thought, “Excellent, I can finally develop something free of the cumbersome links and logos I was required to use before!” Not so fast. This service cost several hundred dollars a year. Not so good for me if I’m creating a plugin. Then I discovered Yahoo! Weather, ironically enough, powered by Weather.com’s data.

Ok, get to it already, jerk.

Fine, fine, fine. I simply thought that background information would be useful for you. With the previous version of this plugin, the version using Weather’s data, you were required to register with Weather.com in order to obtain a key that would allow you to access the data, and I had to build that in to the plugin. This version will work fine without it. Yay! Simplification!

However, your site is limited in the number of requests that can be made in a given day. So if you have a high traffic site you’ll run into issues if you’re constantly requesting data from Yahoo. I had to build in data caching in order to keep those requests down, so now you’ll only access the API once or twice every hour to update data and that should take care of the problem. So, it’s not instant, but probably good enough.

At the moment this plugin is a little hit and miss. I don’t plan on doing much more with it, but feel free to fork this, modify it, whatever.

Download From the WordPress Repository

So, enjoy the fruits of my labor!


0 Comments

WordPress Site Funtionality: Plugin or Functions.php?

If you’re developing websites using WordPress as your CMS, you’ve probably had to decide whether or not to create a plugin for that site’s functionality or to just dump it into your theme’s functions.php file. My solution used to be the latter, but lately I’ve found the former to be superior for one simple reason: themes are less permanent and more likely to be changed after you’ve passed it off to the client than a plugin. Hell, even I change my theme frequently enough for it to be an issue.

That news is likely old hat to you, but it took me a while to really see things that way. I’m not much of a serious developer, and so I don’t have extensive training or knowledge of programming models and logic, but I’ve always had an interest in it. Unfortunately, using object oriented programming wasn’t something that I understood how to do. Don’t get me wrong, I get the model, and how useful it is, I just never knew how to implement it logically, efficiently, and usefully.

I found, though, that as WordPress progressed, it was going to become quite useful to understand OOP on at least a basic level.

As it stands, I’m becoming heavily invested in developing for WordPress, and when I create a site now, I am generally going to be modifying the user experience in such a way as to require the creation of a plugin. This is to make sure clients aren’t doing something that breaks the site, or to shut down some unneeded functionality mostly, but occasionally I’m adding some handy widgets and custom post types.

Bottom line: if you need some Theme dependent functionality, the obvious choice is to keep it in the functions.php file, otherwise create a plugin to preserve that functionality across themes.


17 Comments

Creating the Recent Custom Posts WordPress Widget

I recently found myself needing a way to display the most recent posts from multiple custom post types in multiple widgetized areas of a site I was working on.

Because I needed to do this quickly, and I assumed this need was common, I was on the lookout for an already well written and developed plugin that would do the job. I ran across a widget plugin from New2WP1 that allowed you to display the most recent posts from a single custom post type. Unfortunately, it wasn’t a multi-widget and you could only select one post type, so the plugin wasn’t suitable.

My first thought was that I could easily turn the plugin into a multi-widget capable plugin, but when I started to work on it, I realized that any modifications I made could easily be overwritten on the next update. Additionally, when I began work on turning it into a multi-widget plugin, it became exceedingly obvious that I would probably need to start from scratch.

That’s when I decided to develop a plugin of my own, based on the structure of what I saw in the plugin from New2WP, that would fit my needs, and hopefully the needs of others.

Where to Begin

Visit the Widgets API reference at the WordPress codex for a better overview of this information.

Once I figured out that I needed to turn the widget into one that could be used in multiple widgetized areas, I started to research like mad to find out what it would take to accomplish this. One trip over to the WordPress codex was enough to send me in the right direction.

It was basically as simple as this default usage code implies:

class My_Widget extends WP_Widget {
	function My_Widget() {
		// widget actual processes
	}

	function form($instance) {
		// outputs the options form on admin
	}

	function update($new_instance, $old_instance) {
		// processes widget options to be saved
	}

	function widget($args, $instance) {
		// outputs the content of the widget
	}

}
register_widget('My_Widget');

However, converting the existing plugin to this wasn’t as simple as the above code implies. The old plugin was built as a function, and its structure made it quite a bit more difficult to tie into the WordPress Widgets API.

Based on what I learned from New2WP’s plugin, and the WordPress Codex, I proceeded to build out my own plugin.

The Recent Custom Posts Plugin

I started by creating the directory /mm-recent-cpt/, the file mm-recent-cpt.php, and readme.txt file for future upload to the WordPress plugin directory.

In the php file I added the plugin header:

/**
 * Plugin Name: Recent Custom Posts
 * Plugin URI: http://mikemattner.com/custom-post-type-widget/
 * Description: Multi-widget for displaying recent posts of custom post types.
 * Version: 1.0
 * Author: Mike Mattner
 * Author URI: http://www.mikemattner.com/
 * Tags: custom post types, post types, latest posts, sidebar widget, plugin
 * License: GPL
 */

This allows WordPress to gather information about your plugin. If you just put that file into the plugins directory right now, you’ll have a plugin that does nothing, but it will show up in the list.

The structure of this widget is fairly simple because of the Widgets API. You’ll create a class that extends the WP_Widget class, essentially making it a breeze to create this plugin. I named my class mm_recent_posts. In order to get things moving, you need to initialize the plugin. In most cases you’ll use add_action to get your class or function working.

The function I’m calling with add_action returns register_widget, which takes the $widget_class argument. According to the Codex, $widget_class is the name of a class that extends WP_Widget.

So, this is my basic structure:

add_action( 'widgets_init', 'init_mm_recent_posts' );
function init_mm_recent_posts() { return register_widget('mm_recent_posts'); }

class mm_recent_posts extends WP_Widget {
    /** constructor */
    function mm_recent_posts() {
       parent::WP_Widget( 'widget_recent_cpt', $name = 'Recent Custom Posts' );
    }

    function widget($args, $instance) {
       // outputs the content of the widget
    }

    function update($new_instance, $old_instance) {
       // processes widget options to be saved
    }
    
    function form($instance) {
       // outputs the options form on admin
    }

}

The above is fairly self-explanatory as far as what each function’s purpose is. The constructor function mm_recent_posts() is designed to give a little information about the widget. You could use something along these lines to get it up and running: parent::WP_Widget('my_widget_base', 'My Widget title', array('description' => 'Very simple widget example', 'class' => 'my-widget-class'));.

Pretty easy, right?

The Plugin

The plugin I created is fairly straightforward. It is essentially just an extension of the original Recent Posts widget that comes with WordPress by default–except that this doesn’t overwrite that.

If this looks like something you could use, feel free to download, use, and modify till you’re blue in the face.

Download From WordPress Plugin Directory

I’ve now uploaded the plugin to the WordPress plugin directory. I hope you’ll find it to be useful.

I’m working on getting this added to the WordPress plugin repository The plugin can also be downloaded from the WordPress plugin repository. If you have any questions, comments, or modifications, let me know in the comments. I can’t guarantee that this will work with all plugins, particularly the Custom Post Type UI plugin, but I will say that I’ve used it, and it works for me. I apologize if my code isn’t up to snuff.

Also, welcome Stumblers! Thanks for stopping by. Hopefully you’ll find my little plugin to be useful.


  1. This is a fine plugin, it just needs to be multi-widget capable to be more useful.

2 Comments

Overwriting WordPress Functions

WordPress finds new ways to amaze me; some of these things are neither impressive nor particularly noteworthy, except that these things enable users to customize this platform in ways unimaginable to regular Joe Blogger, who simply uses the system. And in spite of how common such things are to those who truly dive into it, I struggled for quite a while trying to find the best way to change a bit of core functionality. 1

If you scroll down to the bottom of the site on the home page, and on any entry page, you’ll notice a set of buttons that will help you navigate to the next and previous entries, or the next and previous pages of the home page. I needed a way to style these, and oddly enough WordPress did not provide a class name for either of those links. Too bad. So I needed to find out how to adjust that in order to target those links. In addition to that, I needed to also make a small change that classes wouldn’t have allowed for, which was to get the function to output code for the cases in which there were no other pages or posts in a given direction. My first thought was to find whatever core file these functions were located in and then make the change there; I proceeded to do this, got it working, and decided that I should go about this in a different way if I ever wanted to upgrade without having to change that file every time–if I even remembered in those instances.

The tags in question were: next_posts_link, previous_posts_link, next_post_link, and previous_post_link, as well as a few more functions that were related to them. Each of these provides the basic functionality I needed to modify; I tried to replicate these functions, using the same name, in an effort to essentially overwrite the original WordPress core functions. Well, I located them in the link-template.php file, copied and pasted them into my themes functions.php file, and proceeded to make the necessary changes. When I uploaded functions.php and refreshed my site, I had a big giant error; actually it was less an error and more a blank screen, which is worse in a lot of ways as you have no idea what went wrong. I should have known from my programming experience that I couldn’t duplicate these functions in this way.

I was stumped for the longest time, and search after search on Google was leading me towards something called, add_filter, which it turns out doesn’t quite overwrite the function so much as filter the function results through your new function; this was not what I wanted to do on any level. I couldn’t manipulate the data through a filter to achieve the needed results.

After some time, and a lot of searching, I landed on a WordPress MU forum (still not sure what MU is), that gave me my answer–the most obvious answer–which was to take the functions I needed and rename them. I could then use those new function names in place of the old ones wherever I needed them in my theme files.

That’s easy, ain’t it? Why don’t people explain this more often, or even need to to do this enough for it to be found on Google?


Update 1/19/2010: I wanted to clarify just in case some one stumbled upon this looking for an actual bit of code that might show them what I was up to. So here goes.

Instead of adding a filter to the function you want to change:

add_filter('next_posts_link', 'new_next_posts_link', 0);

Add a new function to functions.php and call it in your template wherever you were going to use the old one.

function new_get_next_posts_link( $label = 'Next Page &raquo;', $max_page = 0 ) {
    global $paged, $wp_query;

    if ( !$max_page ) {
        $max_page = $wp_query->max_num_pages;
    }

    if ( !$paged )
    $paged = 1;

    $nextpage = intval($paged) + 1;

    if ( !is_single() ) {
        if( empty($paged) || $nextpage <= $max_page) {
            $attr = apply_filters( 'next_posts_link_attributes', '' );
            return '<a href="' . next_posts( $max_page, false ) . "\" class=\"next\" $attr>". preg_replace('/&([^#])(?![a-z]{1,8};)/', '&#038;$1', $label) .'</a>';
        } else {
            $attr = apply_filters( 'next_posts_link_attributes', '' );
            return '<span '.$attr.'>'. preg_replace('/&([^#])(?![a-z]{1,8};)/', '&#038;$1', $label) .'</span>';
        }
    }
}
function new_next_posts_link( $label = 'Next Page &raquo;', $max_page = 0 ) {
    echo new_get_next_posts_link( $label, $max_page );
}

I’ve essentially adjusted this line:

if ( !is_single() && ( empty($paged) || $nextpage <= $max_page) ) {
    $attr = apply_filters( 'next_posts_link_attributes', '' );
    return '<a href="' . next_posts( $max_page, false ) . "\" $attr>". preg_replace('/&([^#])(?![a-z]{1,8};)/', '&#038;$1', $label) .'</a>';
}

And changed it to this next bit in order to add a class to the link for styling purposes as well as to display a grayed out link if there was no next (or previous in the case of those set of functions) page.

if ( !is_single() ) {
    if( empty($paged) || $nextpage <= $max_page) {
        $attr = apply_filters( 'next_posts_link_attributes', '' );
        return '<a href="' . next_posts( $max_page, false ) . "\" class=\"next\" $attr>". preg_replace('/&([^#])(?![a-z]{1,8};)/', '&#038;$1', $label) .'</a>';
    } else {
        $attr = apply_filters( 'next_posts_link_attributes', '' );
        return '<span '.$attr.'>'. preg_replace('/&([^#])(?![a-z]{1,8};)/', '&#038;$1', $label) .'</span>';
    }
}

So, again. If you’ve got something to modify, do it this way. The functions.php template file is your best friend.


  1. Note: I want to caution you to avoid doing anything with WordPress’ core functions if you aren’t familiar with php. You will regret it, especially if you’ve done something directly to a core file. Stick with filtering and extending with plugins.

0 Comments

Adding Articles and Upgrading WordPress

I’ve spent a little bit of time over the past few days (don’t worry, I’m still working on your wordpress template!) creating a brand new category of entries: articles. Articles are those longer entries that I really just want to add a bit of style to, something that breaks the regular layout, or something that I found I wanted to do but was limited by the entry layout.

You won’t see these too often, but when you do, they should be decent. You can identify them by the § icon next to them.

On another note, while getting my hands dirty messing around with the article format, and simultaneously reading about a brand new exploit to WordPress (no relevance I hope), my admin section started to act a bit funky. I decided that I needed to upgrade in order to save the damn thing. It worked, and I’m now fully upgraded to the latest version.

I made the mistake of turning off the pesky upgrade notification, because I thought, hey, I just got this version, it works, why bother? Don’t do that. Just upgrade when the next version updates.


2 Comments

Spammy Comments

I’ve noticed an inordinate amount of spam comments coming in over the lines lately; most from a user name like Free-I-Phones-and-how-to-get-them. They are not immediately published, of course, but they still come through.

If anyone works with WordPress and knows of an excellent spam prevention plug in, let me know.