Prettier PHP Debug Messages

(prettier than what I’ve been doing, at least)

Hmm, let’s see. Trying to figure out a bug in my WordPress template. I need to know what the current post looks like. So I’ll go to the template and put in

print_r($post);

which produces

That’s helpful, but a little hard to read. So let’s create a Pretty Print function and put some preformat tags around the output.

(in my theme’s functions.php)

if (! function_exists('pp')) {
  function pp($msg) {
  	echo "<" . "pre>" . print_r($msg,true) . "<" . "/pre>";
  }
}

And so now if I call this in my template

  pp($post);

we get

A little better. So that’s been my Pretty Print function for quite a while. But sometimes the debug messages are unreadable due to their position in the template where I call pp(). Maybe there are theme colors hiding the messages, or possibly an overflow: hidden CSS rule blocks some of them.

So I decided to make another version which will collect all of the calls to pp() and put them in one visible spot. It will allow scrolling, and CSS styling.

(in my theme’s functions.php)

<?php
if (!function_exists('pp')) {
  function pp($obj) {  
    $data = json_encode(print_r($obj,true));
    ?>
    <script type="text/javascript">
      var obj = <?php echo $data; ?>;
      var logger = document.getElementById('bsdLogger');
      if (!logger) {
        logger = document.createElement('div');
        logger.id = 'bsdLogger';
        document.body.appendChild(logger);
      }
      ////console.log(obj);
      var pre = document.createElement('pre');
      pre.innerHTML = obj;
      logger.appendChild(pre);
    </script>
    <?php
  }
}

So now in my template, I debug all sorts of nonsense

            <?php the_content(); ?>
            <?php pp(Array('apples','oranges'));
            pp('HAHA');
            ?>
            <table style="border: 2px solid red;">
              <tr><td>What's this?</td><td>a table in the middle of nowhere?</td></tr>
            </table>
            <?php
            pp($post);
            ?>

Mix with some CSS to taste and you get


Notice that even though there’s a random table happening between debug calls, the debug messages still gather into their designated spot.

I think I’ll see how that suits me for a while. True, it obscures part of the content, but if I’m asking for a debug message in the first place, that’s primarily what I want to see. When I remove the pp() calls in the code, the message box goes away again.

If there are better ways of doing this, please let me know.

Relative Site URL on Content Save

Another post for WordPress admins, building on an earlier WordPress Tip: Bloginfo as a Shortcode

Having a shortcode is great, but why not automate the insertion of the shortcode into the content box? That’s what I’ve done here.

(To use this code, add it to your theme’s functions.php file)

function bsdrelative_content_replace_url($content) {  
  return str_replace(get_bloginfo('url'),'[url]',$content);
}
add_filter('content_save_pre','bsdrelative_content_replace_url');
 
function bsdrelative_url_shortcode($atts, $content = null) {
  return get_bloginfo('url'); 
}
add_shortcode("url", "bsdrelative_url_shortcode");

There’s a reason I’m using a shortcode rather just replacing http://site.com/the/link with /the/link and it’s that the latter assumes that the site is installed at the DocumentRoot of the webserver. Not a safe assumption. Often times, I’m developing a new website for a client under a subfolder such as a http://clientsite.com/staging or http://clientsite.com/dev while the current to-be-replaced site remains at the root level.

I’ve also made this available as a WordPress Plugin

WordPress Tip: bloginfo as a shortcode

I often need to help move a client’s redesigned website into WordPress at a new webhost. During this process, the client’s domain must remain pointing to the old website so there is no interruption in traffic. Repointing the domain becomes one of the last steps of the process.

WordPress addresses a potential problem here with a Template tag called bloginfo. Inside my theme’s templates, I use bloginfo(‘url’) rather than hardcoding my site’s URL. The actual URL is maintained in the Dashboard under Settings > General > WordPress address (URL). bloginfo(‘template_url’) adds the current theme path to the URL. Often when programming, computing a value gives you more flexibility than hardcoding a value.

Another area where I would like to have this flexibility is inside the actual content of the post. If I upload an image using the Media Uploader, it immediately computes the URL for the image. But I don’t want to have to come back later after the domain has been repointed to edit the URLs in the post. Can’t I have the same delayed computation that bloginfo(‘url’) provides, but inside the content?

Solution 1: Shortcodes for your URLs

Edit your theme’s functions.php

function my_url($atts, $content = null) {
  return get_bloginfo('url'); 
}
add_shortcode("url", "my_url");  
 
function my_template_url($atts, $content = null) {
  return get_bloginfo('template_url'); 
}
add_shortcode("template_url", "my_template_url");  
 
function my_images_url($atts, $content = null) {
  return get_bloginfo('template_url') . '/images'; 
}
add_shortcode("images_url", "my_images_url");

Using this shortcode, I can upload the image, insert the image into the post, and then modify the URL to use the shortcode. I don’t have to return to edit the URL later.

  <img src="[images_url]/chunky.jpg" />

Solution 2: Shortcode for bloginfo itself

I found this solution at Blue Anvil

function bloginfo_shortcode( $atts ) {
    extract(shortcode_atts(array(
        'key' => '',
    ), $atts));
    return get_bloginfo($key);
}
add_shortcode('bloginfo', 'bloginfo_shortcode');

Demo

That was uploaded with the Media Uploader, and here’s the final markup

<a href="[bloginfo key='url']/wp-content/uploads/2010/02/chunky-e1266723693872.jpg">
<img src="[bloginfo key='url']/wp-content/uploads/2010/02/chunky-e1266723693872-225x300.jpg" 
alt="" title="chunky" width="225" height="300" class="alignnone size-medium wp-image-462" /></a>

CodeIgniter Tip: Body class tags

WordPress 2.8 came out with the body_class() function which allows you to hang your per-page (or per-whatever) CSS off of dynamically generated class attributes on the body HTML tag. I’m going to show you how to have some of that flexibility when using the CodeIgniter PHP framework.

CodeIgniter URLs often take the form of http://my-cool-website.com/account/change-password, where account is the controller and change-password is the function. I want CodeIgniter to automatically put a CSS class “account-change-password” on the body tag whenver a user visits that page.

Step 1. Edit controllers/application.php

Application is the superclass of all of my other controllers, including the Account controller. Here we add 2 variables and populate them in the Application() constructor.

class Application extends Controller {
 
  var $controller;
  var $function;
 
	function Application() {
	  parent::Controller();
	  $this->controller = $this->uri->rsegment(1); // The Controller
          $this->function = $this->uri->rsegment(2); // The Function
	}

Step 2. Edit the body tag in your layout template

<body class="<?php echo $this->controller; ?>-<?php echo $this->function; ?>">

now you’re ready to make up some CSS such as

body.account-change-password  #main-content ul {
  list-style-type: none;
}

So now your page elements can have alternate CSS targeted to which controller-function page is currently displaying.

Playing the Guitar in 20 Questions

fretboard-triads

Check out this web page I wrote to help a player visualize and follow along with the process explained in the video below. If you color code each chord you build, you’re left with a good study guide for practicing.

If you have a guitar, I hope you’ll take a few minutes and try out the page. Let me know if you find it useful or not.

A while back I found this video which shows how to harmonize a maj7 chord over the major scale.

This exercise can be done with any chord and any scale that chord belongs to. As the chord walks up the scale, its sound retains some familiarity yet it also has to squeeze and stretch along each degree in order to remain in key. A reason you would do this exercise is to find other chords to consider for a progression.

Paul Davis and the catchy chorus

Take a few minutes to mellow out to the late Paul Davis. One evening as “Sweet Life” came up in my Pandora queue, someone insisted it was a rip-off of Paul Davis’s “Cool Night”. After asking YouTube, we sorted it out. They’re both from Paul Davis.  Listen to the chorus of both and you’ll see how easy they are to confuse.

First, “Sweet Life”

and now “Cool Night”

I tried to use YouTube’s deep linking to cue up the chorus but it seems to not always work.

Meet my fine (but not 0.5mm fine) pencils

I’m tired of not having any posts, so here’s something completely retarded.

These are my mechanical pencils. I prefer 0.7mm because the lead is thicker and won’t break under the plowing scrawl.

From back to front

The Pentel in back is the oldest and has the most mileage. I wish I actually did know much distance it has logged. There’s only so much tic-tac-toe one can play. But anyway. It also features a convenient side-mounted lead feeder button.

Next is the Pentech. This one is like a Corvette. Unlike the Pentel, this pencil has a nice shape and feels slightly heavy. I’m routinely impressed by how frictionless and pen-like the extra weight makes it seem. However, this one has a low capacity for lead. Maybe 3 is the most it will hold at once. I’ve had to retire this pencil however because I once crammed 4 leads into it, and it jammed up the innerworks. Poor pencil. I would’ve kept you with me forever. I told you this was going to be retarded.

Finally, the Papermate is the newest addition. It doesn’t have the right weight. Its top seems to be crimped around the eraser. I wonder if they’re meant to be just thrown away. Very odd, if that’s the case. I purchased this one in a set of four. The rotary lead feeder gives an extra ergonomic flair.

Thanks for listening to me introduce the special pencils in my life.

UPDATE: My newest is a Pentech Sensor 0.7mm (not pictured). Side feed. Refillable. The eraser basket twists to feed out more eraser, which are also refillable! The only down side so far is that I often break the lead. That rarely happened with the others.