Simplified Source

Code Clarity (TM) offers handcrafted and elegant Small Business Websites and Web Applications. We ar Web Development and Design firm based out of Boulder, Colorado. We specialize in W3C Standard complaint websites, SEO Marketing, PHP, Ruby on Rails, and much more. We also contribute to many open-source projects with interest and passion for Linux and Android.

This post originated on Forrst at, http://forr.st/~Vfg.

Serialized PHP Search and Replace

This is a very handy little PHP script. It allows you to perform a simplesearch and replace on your SQL database. Very helpful with Wordpress domain transfers among other usages when it comes to modifying your database.

View Code

From the Original Author

When you’re migrating WordPress (or any other platform using serialized PHP strings in the database) between domains, you must use a safe search and replace method that preserves the integrity of the serialized string lengths. A simple of a dump file for localhost to, for example, thenewdomain.com is problematic because the length of the string changes but the indexes for the serialized strings does not. Consequently settings are lost and widgets disappear. Not good.

This script can now also handle multiply nested serializations, which can happen in transient values in WP at times, and it can also handle multi-byte Unicode changes safely. This is important now that internationalised domain names are allowed.

IT’S NOT ONLY FOR WORDPRESS

It’s worth mentioning that the code will work for any platform that stores PHP serialized arrays in a MySQL database. You can easily use this script on Drupal, Joomla and many other systems where you need to change items across a database without messing up your stored arrays.

Read More

(This blog post originated from a post that I made earlier on Forrst.)

Wordpress 3.x has a lot to offer us Developers. We should take advantage of it. I’ve been developing a lot of custom plugins and custom widgets for my Clients who use Wordpress as their CMS. Now there are a ton of tutorials and code snippets of how to create a custom Plugin or a custom Widget for your Wordpress Installation but I kept running into issues with my Widgets not being able to be reused. So, I created a basic template for a Custom Plugin that creates a Widget Class that can be reused and is more than customizable.

View on PasteBin  View on Forrst

Every Wordpress Developer has their own methods and own opinions on how to create Widgets and Plugins and I just wanted to share my method. This is my basic template which creates a Plugin for a Client, and wrapped in this Plugin is a custom Widget that shoots back some text. Of course you can get nice and complex and do what ever you want here. (My code is a compilation of research and publicly available information).

Constructive criticism and feedback is welcome, as always.

<?php
/*
Plugin Name: ClientName Custom Widget
Description: Displays a custom feature for your Client in the form of a Widget.
*/


class customClientWidget extends WP_Widget {

   
function custom_clientWidget() {
       
// Declare your Widget name, the class name and a Description for the Dashboard
        $widget_ops
= array('classname' => 'customClientWidget', 'description' => 'Displays something that you specify in the code below.' );
        $this
->WP_Widget('customClientWidget', 'Your Custom Widget', $widget_ops);
   
}

   
function widget( $args, $instance ) {
       
// Very basic code that takes the Title from the form function and then displays your code
        extract
($args, EXTR_SKIP);

        echo $before_widget
;
        $title
= empty($instance['title']) ? ' ' : apply_filters('widget_title', $instance['title']);

       
if (!empty($title))
          echo $before_title
. $title . $after_title;

       
// Content to be displayed on page goes here
        echo
'Displaying some data here.';
        runThisFunctionNow
();

        echo $after_widget
;

   
}

   
function update( $new_instance, $old_instance ) {
       
// Allows for the Widget to be reused
        $instance
= $old_instance;
        $instance
['title'] = $new_instance['title'];
       
return $instance;
   
}

   
function form( $instance ) {
       
// Creates a very simple form so that you can Title your Widget.
        $instance
= wp_parse_args( (array) $instance, array( 'title' => '' ) );
            $title
= $instance['title'];
       
?>
         
<p><label for="<?php echo $this->get_field_id('title'); ?>">Title: <input class="widefat" id="<?php echo $this->get_field_id('title'); ?>" name="<?php echo $this->get_field_name('title'); ?>" type="text" value="<?php echo attribute_escape($title); ?>" /></label></p>
       
<?php
   
}

   
} // End of Widget Class

   
function customClient_widgets() {
   
// Register the Widget
    register_widget
( 'notable_pressWidget' );
   
}
   
// Quick WP Action to register the Widget
    add_action
( 'widgets_init', 'customClient_widgets' );

// From here you can upload the file and directory to your /wp-content/plugins/ directory, then goto Admin Dashboard and Plugins and Activate the Plugin. Afterwords you can goto your Widgets and add the Widget to a Sidebar. Simple stuff.


?>

When it comes down to it, that’s a pretty easy setup.

Wordpress is a very powerful CMS. I have personally been developing for many years now. I tend to stay way from the Content Management System approach. As of the last year, that is more than a frequent request from my clients. They all want full unrestricted access to their websites and at times they would like to edit their own content. Code Clarity has been developing a Wordpress Framework that is aimed at Clients. Not just end-users or other developers but Clients. The Framework is basically a blank canvas, with a little functionality. I found this article very helpful. Courtesy of Smashing Magazine. 

It has been a big year for WordPress. If there were still some lingering doubts about its potency as a full-fledged content management system, then the full support for custom taxonomies and custom post typesin WordPress 3.0 core should have put them to rest. WordPress 3.1 took those leaps one step further, polishing custom taxonomies with multi-taxonomy query support, polishing custom post types with native template support for archives and feeds, and introducing features (like the “admin bar”) that make it easier to quickly edit and add content from the front end.

In the broader community, we’ve seen incredible plug-in suites such as BuddyPress mature, and even the emergence of independent WordPress-dedicated hosting services, such as page.ly. To celebrate WordPress’s progress, let’s review some new tips that can help template developers and consultants up their game even further.

Foreword for New Developers: What is a “Hook”?

Most of these tips take advantage of core WordPress “hooks.” Hooks are points in the code that allow any number of outside functions to “hook in” and intercept the code in order to add to or modify behavior at a particular point. Hooks are the fundamental concept that enables virtually all plug-ins. WordPress has two kinds of hooks: actions and filters.

Action hooks are intended to allow developers to intercept certain activities and execute some additional functionality. For instance, when a new post is published, the developer may want to add some extra functionality, such as posting the title and a link to Twitter.

Filter hooks allow the developer to intercept and modify data that is being processed by WordPress for display or saving. For instance, the developer may want to inject an advertisement into the content before displaying the post on the screen.

Learn more about hooks on the official WordPress codex.

The Underused Pagination Function

Many great plug-ins are in the official WordPress repository. But using fancy plug-ins to add fairly basic functionality to your theme is often like driving a tractor trailer to go around the block. There’s usually a lighter, smarter way: a bike or even a car. And while plug-ins are a fine solution for consultants who are staging a complete roll-out, they’re awkward solutions for theme developers who want to sell standalone templates.

WP-PageNavi is one of the most popular WordPress plug-ins; and no doubt it is well developed. It is ideal for those who are uncomfortable digging into WordPress code. But did you know that WordPress has a function built right into core that (with a bit of savvy about its parameters) can generate pagination links for everything from comments to post archives to post pages?

The function in question is paginate_links(). (For those who like to fish around in the source, it’s on line 1954 of general-template.php in the wp-includes folder as of WordPress 3.1.)  Believe it or not, this underused function has been around since 2.1. Another function, paginate_comment_links(), is actually a wrapper for this function that is designed specifically for paging comments, and it has been around since 2.7.

The function takes an array of parameters that make it versatile enough to use for any kind of paging:

  • base
    This is the path for the page number links, not including the pagination-specific part of the URL. The characters %_% will be substituted in that URL for the page-specific part of the URL.
  • format
    This is the “page” part of the URL. %#% is substituted for the page number. For example, page/%#%or ?page=%#%.
  • total
    The total number of pages available.
  • current
    The current page number.
  • show_all
    Lists all page links, instead of limiting it to a certain number of links to the left and right of the current page.
  • prev_next
    Includes the “Previous” and “Next” links (if applicable), just as you might normally do with theprevious_posts_link() function.
  • prev_text and next_text
    Text to put inside the “Previous” and “Next” links.
  • end_size
    The number of page links to show at the end. Defaults to 1 (e.g. 1 2 3 … 10).
  • mid_size­
    The number of pages to show on either side of the current page. Defaults to 2 (example: 1 … 3 4 5 6 7 … 10).
  • type
    Allows you to specify an output style. The default is “plain,” which is just a string of links. Can also be set to list (i.e. ul and li representation of links) and array (i.e. returns an array of page links to be potentially outputted any way you like in code).
  • You can also add query arguments and fragments.

Because the function takes all of the information needed to generate page links, you can use it for pretty much any pagination list, as long as you have some key information, such as the number of pages and the current page. Let’s use this function to generate pagination links for an article archive such as a category or main post index:

01// get total number of pages02global $wp_query;03$total $wp_query->max_num_pages;04// only bother with the rest if we have more than 1 page!05if $total > 1 )  {06     // get the current page07     if ( !$current_page = get_query_var('paged') )08          $current_page = 1;09     // structure of “format” depends on whether we’re using pretty permalinks10     $format empty( get_option('permalink_structure') ) ? '&page=%#%' 'page/%#%/';11     echo paginate_links(array(12          'base' => get_pagenum_link(1) . '%_%',13          'format' => $format,14          'current' => $current_page,15          'total' => $total,16          'mid_size' => 4,17          'type' => 'list'18     ));19}

Here’s the HTML generated by that code on the first of 10 posts pages:

01<ul class='page-numbers'>02     <li><span class='page-numbers current'>1</span></li>03     <li><a class='page-numbers' href='http://mysite.com/page/2/'>2</a></li>04     <li><a class='page-numbers' href='http://mysite.com/page/3/'>3</a></li>05     <li><a class='page-numbers' href='http://mysite.com/page/4/'>4</a></li> 06     <li><a class='page-numbers' href='http://mysite.com/page/5/'>5</a></li>07     <li><span class='page-numbers dots'>...</span></li>08     <li><a class='page-numbers' href='http://mysite.com/page/10/'>10</a></li>09     <li><a class='next page-numbers' href='http://mysite.com/page/2/'>Next &raquo;</a></li>10</ul>

Here’s a screenshot of the pagination on m62 visualcommunications, built using the em>paginate_linksfunction.

M62-pages in New WordPress Power Tips For Template Developers And Consultants

“I Wish Posts Were Called Articles For My Client.”

Have you ever wished you could change the wording of a built-in menu item or notification? If you’re a bit WordPress-savvy, you may have considered generating your own translations file. But you might not know that you can actually “hook” the translation functions in WordPress, capturing their input and modifying their output.

Be careful with this one. The code you put in this hook will run every time WordPress runs a string through its translation filters. Complex cases and conditionals could add a considerable amount of overhead, especially when loading pages filled with translation strings, such as the administrative pages. But if you just want to rename one thing that confuses your client (for example, maybe changing “Posts” to “Articles” for that corporate client who doesn’t “blog” yet), then these hooks can be very handy.

view sourceprint? 1// hook the translation filters2add_filter(  'gettext',  'change_post_to_article'  );3add_filter(  'ngettext',  'change_post_to_article'  );4 5function change_post_to_article( $translated ) {6     $translated str_ireplace(  'Post',  'Article',  $translated );  // ireplace is PHP5 only7     return $translated;8}

Translations in New WordPress Power Tips For Template Developers And Consultants

Redirect Failed Log-Ins

Adding a log-in form to the front end of WordPress is pretty easy. WordPress 3.0 gave us the flexiblewp_login_form() function, which displays a log-in form that can be customized with a number of arguments. By default, it will redirect the user back to the current page upon successful authentication, but we can also customize the redirect location.

1wp_login_form(array'redirect' => site_url() ));  // will redirect back to the website’s home page

There’s just one problem: it will only redirect upon successful authentication! If your idea was to hide the default WordPress log-in screen, then sending users who fail at a log-in attempt back to the default log-in screen probably isn’t ideal. Here’s a hook and some code that you can put in your functions.php file that will redirect failed log=ins to any location of your choosing.

01add_action( 'wp_login_failed''my_front_end_login_fail' );  // hook failed login02 03function my_front_end_login_fail( $username ) {04     $referrer $_SERVER['HTTP_REFERER'];  // where did the post submission come from?05     // if there's a valid referrer, and it's not the default log-in screen06     if ( !empty($referrer) && !strstr($referrer,'wp-login') && !strstr($referrer,'wp-admin') ) {07          wp_redirect( $referrer '?login=failed' );  // let's append some information (login=failed) to the URL for the theme to use08          exit;09     }10}

Adding Excerpts to Pages

With the addition of support for custom post types, content types (including the built-in Post and Page types) are more like abstract objects. Each content type can support any number of core features, such as the HTML editor, titles, featured images and so forth. One of these core features is the “excerpt.” By default, Pages do not support excerpts. Did you know that adding excerpt support to the built-in Page type is as simple as adding a single line of code?

1add_action( 'init''my_add_excerpts_to_pages' );2function my_add_excerpts_to_pages() {3     add_post_type_support( 'page''excerpt' );4}

Technically, that was a couple of lines of code, but many themes already hook init, so the hook might not be necessary.

Page-excerpt in New WordPress Power Tips For Template Developers And Consultants

Add Body Classes Based on Special Conditions

If a theme is well constructed, then it would use the body_class() function to automatically generate classes for the body tag based on the properties of the page being viewed, like categorycategory-3, and logged-in.

Some websites may have sections that should share some styling but aren’t unified by any of the default classes generated by body_class. Say we want page ID 7, category ID 5 and the archive for the tagneat to share the body class neat-stuff, so that we can add a number of styling properties to them all without cluttering the style sheet.

Body-neat-stuff in New WordPress Power Tips For Template Developers And Consultants

Luckily, we can hook the body_class() output!

1add_filter( 'body_class''my_neat_body_class');2function my_neat_body_class( $classes ) {3     if ( is_page(7) || is_category(5) || is_tag('neat') )4          $classes[] = 'neat-stuff';5 6     return $classes7}

“You Can Have Settings Access, But Don’t Say We Didn’t Warn You!”

Clients often expect full administrative access (and rightly so), including access to settings pages. Let’s look at how we can hook admin “notices” (those warning boxes generated by some plug-ins) to send some warnings to administrative users when they are on settings pages.

1add_action( 'admin_notices''my_admin_notice' );2function my_admin_notice(){3     global $current_screen;</div>4     if $current_screen->parent_base == 'options-general' )5          echo '<div><p>Warning - changing settings on these pages may cause problems with your website’s design!</p></div>';6}

Warning-settings in New WordPress Power Tips For Template Developers And Consultants

Remove the “Links” Menu Item

With WordPress increasingly being used for full website implementations, the blog roll and links feature is being used less and less. Thankfully, a new, little-known function added in WordPress 3.1 makes it very easy to remove unwanted menu items such as “Links.”

1add_action( 'admin_menu''my_admin_menu' );2 3function my_admin_menu() {4     remove_menu_page('link-manager.php');5}

No-links in New WordPress Power Tips For Template Developers And Consultants

Take Out the Dashboard News Feeds… and Add a New One of Your Own

If you build WordPress websites for clients, then the number of WordPress news feeds loaded by default in the dashboard might be an annoyance. If you’re clever, you might just inject some of your own client’s news.

01add_action('wp_dashboard_setup''my_dashboard_widgets');02function my_dashboard_widgets() {03     global $wp_meta_boxes;04     // remove unnecessary widgets05     // var_dump( $wp_meta_boxes['dashboard'] ); // use to get all the widget IDs06     unset(07          $wp_meta_boxes['dashboard']['normal']['core']['dashboard_plugins'],08          $wp_meta_boxes['dashboard']['side']['core']['dashboard_secondary'],09          $wp_meta_boxes['dashboard']['side']['core']['dashboard_primary']10     );11     // add a custom dashboard widget12     wp_add_dashboard_widget( 'dashboard_custom_feed''News from 10up','dashboard_custom_feed_output' ); //add new RSS feed output13}14function dashboard_custom_feed_output() {15     echo '<div class="rss-widget">';16     wp_widget_rss_output(array(17          'url' => 'http://www.get10up.com/feed',18          'title' => 'What\'s up at 10up',19          'items' => 2,20          'show_summary' => 1,21          'show_author' => 0,22          'show_date' => 1 23     ));24     echo "</div>";25}

10up-news in New WordPress Power Tips For Template Developers And Consultants

Add Your Own Credits to the Administrative Footer

If you build WordPress websites for clients, then you should certainly make sure that WordPress gets its due. It wouldn’t hurt to sneak in a little credit to your agency either.

1add_filter( 'admin_footer_text''my_admin_footer_text' );2function my_admin_footer_text( $default_text ) {3     return '<span id="footer-thankyou">Website managed by <a href="http://www.get10up.com">10up</a><span> | Powered by <a href="http://www.wordpress.org">WordPress</a>';4}

Admin-footer in New WordPress Power Tips For Template Developers And Consultants

Further Reading

Here are more tips for developers who build websites for clients:

More WordPress power tips from Smashing Magazine:

Visit Article

(Published by Jacob Goldman via Smashing Magazine)