Things I've Tagged ‘php’

Page 1 of 2

#Numbers App, #php, #Programming, #Web Design

Another Numbers Revamp

A couple of years ago I put together a little program to generate random numbers for the Mega Millions lottery and produce some analysis on the numbers most often drawn. Most recently I wrote about a revamp I had done to the tool to simplify its functionality.

Well, I’ve done it again. I’ve completely redesigned the interface, and let me tell you, it’s quite nice looking. The functionality is largely the same, though slightly modified, and everything is done asynchronously, so it’s nothing flashy, but I like it just the same.

My primary reasoning for redevelopment was that I wanted to use this on my phone, but the older interface was just a little clunky. This works perfectly for this purpose–though, some more modifications need to be made to make it more of a ‘mobile web app.’ It’s also a little buggy in spots, but oh well. Explore the tool, use it, and enjoy!

By the way, I make no guarantees about the results, but if you happen to pick the winning numbers, would you ?


#php, #Plugins, #WordPress

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


#Development, #Google Analytics, #php

Interacting With the Google Analytics Core Reporting API

I needed a way for my clients to access analytics data that for a variety of reasons didn’t need or have full access to Google Analytics data through the traditional web app. I found a simple, yet soon to be deprecated, solution to my problem–the Google Analytics Core Reporting API.

There are a couple of libraries that an individual can use, depending on the language you’re working in, and since my expertise is in php, I chose to use the Google Analytics PHP Interface. This happens to interact with the older v2.4 API; unfortunately, I didn’t realize this until I already built the thing…moving on.

Start Me Up

OK, so let’s just assume you already have a Google Analytics account, because frankly why else would you need something like this? So, let’s define a few things, include the gapi class and fill in our information to connect to the core reporting API.

define('ga_email','your@email.com');     // GA Email
define('ga_password','elkkdafasff');     // 2-part authorization password
define('profile_id','2345678');          // Analytics profile ID

require_once 'gapi/gapi.class.php';
$ga = new gapi(ga_email,ga_password);

So now we’ve got an object to work with and we can start grabbing some data for our report.

With the core reporting api, you have certain metrics that you can look at depending on the dimension you’re interested in. To find exactly what metrics go with what dimensions, browse the Dimensions and Metrics Reference.

I already know that I’m interested in seeing the visits, pageviews, pages/visit, and bounce rate of all traffic sources (referrals, search engines, etc.). So, using the object we’ve already created I can define the dimensions and metrics I’m interested in, sort it by greatest number of visits, and limit my results to 50. You’ll also see that you can choose a date range. For this example I’m not providing one, so by default it will show the last month’s worth of data.

$dimensions  = array('source');
$metrics     = array('visits','pageviews','bounces');
$sort_metric = '-visits';
                        			
$ga->requestReportData(profile_id,      
    $dimensions, 
    $metrics, 
    $sort_metric, 
    $filter=null, 
    $start_date=null, 
    $end_date=null, 
    $start_index=1, 
    $max_results=50);

It is also possible to filter your data, so that if you wanted to see only referrals as a source, then you could replace $filter=null with $filter='medium==referral'. For a quick reference of what you might be able to filter, take a look at a list of common queries. Really just explore the documentation there in depth.

So we’ve got our data, now let’s put it in a format that we can browse:

<table>
  <thead>
    <tr>
      <th>&nbsp;</th>
      <th>Source</th>
      <th>Visits</th>
      <th>Pageviews</th>
      <th>Pages/Visit</th>
      <th>Bounce Rate</th>
    </tr>
  </thead>
  <tbody>
  <?php
  $i = 1;
  foreach($ga->getResults() as $result):
  ?>
    <tr>
      <td><?php echo $i; ?>.</td>
      <td><?php echo $result; ?></td>
      <td><?php echo number_format($result->getVisits()); ?></td>
      <td><?php echo number_format($result->getPageviews()); ?></td>
      <td><?php echo number_format(($result->getPageviews()/$result->getVisits()),2); ?></td>
      <td><?php echo number_format(($result->getBounces()/$result->getVisits())*100,2); ?>%</td>
    </tr>
  <?php
  $i++;
  endforeach
  ?>
  </tbody>
</table>

How easy was that?

Utilizing that as a foundation, I was able to turn it into a tool for clients, or for myself, making it easy to get a quick look at stats. If you’re at all interested in using it yourself, let me know in the comments.


#Code Snippet, #php

Code Snippets: Ad Display Function For Use in A CMS Template

Since I was recently invited to be an AdPacks.com publisher, I had the pleasure of trying to find a way to integrate the ads tastefully into my site on the top level pages, as well as in individual posts. The current iteration of my site, as well as the last one, really only rely on the single column of content, so I lack a useful sidebar to place ads in; this pretty much limits me to placing ads in the content–well not quite in the content, but in the flow of content really.

So, I essentially needed ads to run after the first post, and only once on any page. In order to do that I needed a simple function that I could run in the WordPress loop, and guarantee my requirements were met.

Thus, the display_ads function was born:

function display_ads(){
    global $ad_count;
	if($ad_count < 1){
      $display = 'AD CODE HERE';
	  echo $display;
	}
	$ad_count++;
}

It's quick and dirty but pretty effective. Is there a better way to do this, because this is pretty much the quickest thing I could come up with on short notice? I am legitimately asking you, is there a better way?


#php, #Plugins, #weather, #WordPress

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!


#email, #php, #PHPMailer, #SMTP

Sending Email With PHPMailer

I’ve generally always handled forms with some quick and dirty php that used the standard mail() function to send me the resulting information. I never really got a good handle on setting that up properly, but, lucky for me, some one has done all of the dirty work by creating a class, PHPMailer, that was meant to handle emails quite a bit more extensively than I was able to do.

It’s actually fairly easy to get started using the class. This is the default implementation that the download provides for basic operation:

require_once('../class.phpmailer.php');

$mail             = new PHPMailer(); // defaults to using php "mail()"

$body             = file_get_contents('contents.html');
$body             = eregi_replace("[\]",'',$body);

$mail->AddReplyTo("name@yourdomain.com","First Last");
$mail->SetFrom('name@yourdomain.com', 'First Last');
$mail->AddReplyTo("name@yourdomain.com","First Last");

$address = "whoto@otherdomain.com";
$mail->AddAddress($address, "John Doe");

$mail->Subject    = "PHPMailer Test Subject via mail(), basic";

$mail->AltBody    = "This is for text based email"; // optional
$mail->MsgHTML($body);

$mail->AddAttachment("images/phpmailer.gif");      // attachment
$mail->AddAttachment("images/phpmailer_mini.gif"); // attachment

if(!$mail->Send()) {
  echo "Mailer Error: " . $mail->ErrorInfo;
} else {
  echo "Message sent!";
}

That is a very easy way to get up and running using the default mail() function. Most of the hard work has been done for you, all you’re left to do is to fill in the blanks. But hey, why go default when the thing provides you with some more advanced functionality? Like sending your email using SMTP.

The best way I found to handle my emails, and to send them using PHPMailer, was to create a component class, unoriginally named mmEmail, that would handle a few operations I needed in order to process the form and format the data.

class mmEmail {
        var $name          = null;
        var $email         = null;
        var $message       = null;
	var $time          = null;
	var $SMTP_host     = null;
	var $SMTP_username = null;
	var $SMTP_password = null;
	var $send_to       = null;
	var $send_name     = null;
        var $subject       = null;
	
	static $instance;
	
        public function __construct() {
		self::$instance = $this;
	}
        
        public function format($message) {
           //code that formats the message body
        }
        
        //this function handles the message template
        public function template($template) {
	    
		$name    = $this->name;
		$email   = $this->email;
		$message = $this->message;
		$time    = $this->time;
		
	        switch( $template ) {
		    case 'html' :
			    $the_body = $this->format($message);
	                    $body = 'html only';
				break;
				
			case 'text' :	
		            $body = 'text only';
				break;
				
			default :
			    break;
		
		}
		
		return stripslashes($body);
	}
   
        public function send() {
            //code to handle PHPMailer - I'll get to it.
        }
}

So this gets us set up to send our formatted email using the send() function above. That function uses PHPMailer to handle the heavy lifting.

function send() {
    $html_body  = $this->template('html'); //HTML Body
    $text_body  = $this->template('text'); //Text only body
		
    require("class.phpmailer.php");
    $mail   = new PHPMailer();
		
    $mail->IsSMTP(); //SMTP
    $mail->Host     = $this->SMTP_host;
    $mail->SMTPAuth = true;
    $mail->Username = $this->SMTP_username;
    $mail->Password = $this->SMTP_password;
        
    $mail->From     = $this->email;
    $mail->FromName = $this->name;
    $mail->AddReplyTo($this->email, $this->name);
    $mail->AddAddress($this->send_to, $this->send_name);
    $mail->Subject = $this->subject;
		
    $mail->IsHTML(true);
    $mail->Body    = $html_body;
    $mail->AltBody = $text_body;

    $result = $mail->Send();

    if($result)
    {
        echo 'Mail sent.';
    }
    else 
    {
        $result = $mail->ErrorInfo;
        return $result;
    }
}

Using my class is then fairly straight forward. I’ll define a few constants for my settings to make things easier for me to read, and from there sending an email is as simple as:

require("class.mmemail.php");
$email = new mmEmail();

$email->name          = NAME;
$email->email         = EMAIL;
$email->message       = MESSAGE;
$email->time          = TIME;
$email->SMTP_host     = SMTP_HOST;
$email->SMTP_username = SMTP_USERNAME;
$email->SMTP_password = SMTP_PASSWORD;
$email->send_to       = SEND_TO;
$email->send_name     = SEND_NAME;
$email->subject       = SUBJECT;
     
$email->send();

Why do something this complicated, when the result looks so much like the original PHPMailer setup? Because this allows me to format, check, and sanitize my data and then send my emails using a template system. I encourage you to take a look at a solution like this the next time you need a better way to send form emails.


PHPMailer can be found at: https://code.google.com/a/apache-extras.org/p/phpmailer/


#custom post types, #php, #Plugins, #widget, #WordPress

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.

#php, #Web Design, #WordPress

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.

#Movable Type, #php, #Web Design, #WordPress

WordPress vs MovableType: My Experience

I’ve been working on a bit of a personal project lately and decided the easiest and best way to introduce a blog would be to install WordPress, plus I really wanted to give that system a little more of a try than I had in the past.

My gut reaction upon installing and settling on a theme for modification was that this was REALLY easy to work with and highly customizable. I had, in fact, gotten used to working with my own MovableType installation, its quirks, and its own templating system, but the php based WordPress on my server was a breeze to deal with compared to the former. It was faster, offered better plugins, easier templating, and I could even edit the hell out of those plugins to customize the installation even further for my needs.

I’m so convinced by my experience that WordPress is the superior publishing platform for anyone looking to get started beyond the free services and put up a site on their own domain, that I am absolutely going to develop the next iteration of this site with WordPress in mind.

MovableType has been good to me, and it truly is a very powerful platform, but my servers don’t deal with it, and it is SLOW as a result. Plus, all of the plugins I want to use aren’t offered for MT or don’t offer what I need. And that can be frustrating.

What I like about MT, though, is the publishing experience. I feel like I can easily add tags to any entry with little problem, and the interface (MT 4.0+ at least) is minimal and easy to use. Previous versions were a bear to work with, I’m afraid, but 4.0+ is quite fantastic.

Anyway, my conclusion: WordPress for the future iteration, but MT will suffice for now; WordPress is superior to MT for beginners and its ease of use; and MT is not likely to catch up.


Update: 5/15/09 I am currently in the process of converting to WordPress. Manually. Really frustrating, but worthwhile. I’ve also discovered that it is a superior publishing experience.


#AJAX, #JavaScript, #jQuery, #php, #Web Design

jQuery AJAX Form Submission

I’ve never been much of a programmer; and I’m probably unusually intimidated by JavaScript. I can’t explain its effect on me, considering what I’ve tackled with php (which, I suppose is arguably pretty simple and inefficient stuff), but it’s not something I’m proud of.

At any rate, this week I decided to tackle a bit of a problem that has been bothering me for as long as I’ve had the current design on my portfolio site.
The portfolio side of things exists as a single page site with work samples, a little information, and a contact form. The contact form would require that you reload the page upon submission in order to process and send the message, which always seemed like a jarring experience from a user interaction perspective.
In order to solve that problem, my solution was the ever popular: AJAX.

I’ve used some jQuery plugins in the past, so I was familiar with the framework; after doing some reading and thinking about compatibility with my current setup, I decided that jQuery’s built in AJAX implementation, and animation effects, would be just about perfect for my needs. Why? Because the jQuery framework is incredibly useful to me, as a designer, with little time for figuring out how to implement all of these fancy user interactions with JavaScript. Plus, it’s the framework I use for everything.

Read the rest of this entry »