Showing posts with label php. Show all posts
Showing posts with label php. Show all posts

Friday, 3 June 2011

WordPress Form Helper Functions

Setting the state of checkboxes, radio buttons and selected items in dropdown lists in html forms can become tiresome, so I was pleased to recently discover WordPress has some built-in helper functions. I've found these to be pretty handy in building admin forms for Wordpress plugins and hopefully they can save you some time too.

checked( $checked, $current = true, $echo = true )

This function compares two given values (for example, a saved option vs. one chosen in a form) and, if the values are the same, adds the checked attribute to the current radio button or checkbox. This is essentially the same as comparing values with if(), but results in more concise code. The third parameter determines if the result is echoed or just returned which is handy if you are concatenating to a string, etc.

This function has been defined since WordPress v1.0 and is documented here.


selected( $selected, $current = true, $echo = true )

This function is for use in dropdown form fields. Compares two given values (for example, a saved option vs. one chosen in a form) and, if the values are the same, adds the selected attribute to the current option tag. Again, the third parameter determines if the result is echoed or just returned which is handy if you are concatenating to a string, etc.

This function has been defined since WordPress v1.0 and is documented here.


disabled( $disabled, $current = true, $echo = true )

This function compares two given values (for example, a saved option vs. one chosen in a form) and, if the values are the same, adds the disabled attribute to a form input field. Again, the third parameter determines if the result is echoed or just returned which is handy if you are concatenating to a string, etc.

This function was not defined until WordPress v3.0 and is documented here.

These functions are all located in wp-includes/general-template.php.

Friday, 24 September 2010

Pro Tip: Check It Yourself

Yesterday I was pushing a module of new code to the blog site of a moderately famous celebrity that is still creaking along on Movable Type (the site, not the celeb). I've not really had to work with Movable Type much before so it was a little bit interesting and I learnt a few bits and pieces.

The code module was working exactly as expected on the development site so I was a bit surprised when it failed on the production site, truncating the rendering of some posts.

Debugging code on a production server is a tricky business (especially when you can't find the error logs), but I tracked it down to this:

PHP Fatal error: Call to undefined function: file_put_contents() ...

The function file_put_contents() was introduced with PHP version 5, so this error indicated the production server was running some version of PHP4. This kind of disparity between production and development environments is certainly not the optimal configuration, but it's not entirely uncommon when working with legacy systems. The problem for me yesterday was that it took me a lot longer to identify and fix the problem because I was sure that the production site was on PHP5...

I'd asked the rest of the development team if the sites I was working on with this module were on PHP5, they were pretty sure they were, but recommended I checked with the ops team. A member of the ops team told me they were all on PHP5 too. I don't know if the error was due to a chat-window miscommunication, lack of familiarity with the site, or just a genuine mistake - it's not really a big deal. In reality, it probably would have been quicker to just check the phpversion() myself when I first thought to ask about it - I would have discovered it was on PHP4 and altered the module's code before I tried to push it to the production environment.

Tuesday, 16 March 2010

Suppressing Link URL In WP Media Library

UPDATE: You can now set the default action by adding the following code to your functions.php file.

update_option('image_default_link_type','none');





It's been a while since I've posted anything here (I've been pretty busy lately), so when I threw together a quick fix for a WordPress installation today, I thought I should put a quick note about it here.

The Problem:
When inserting or attaching an image to a post with WP's Media Library the Link URL is always pre-populated with the URL to the file. To remove this URL so that the image is not linking to the original file, users must go through the arduous process of remembering to click the "None" button before inserting the image.



OK, that was a little sarcastic, but that's pretty much what the feature request was saying. They wanted the field's behaviour to change so that the default was blank.

The Solution:
To create the desired behaviour, I created the following function and hooked it to the attachment_fields_to_edit filter to clear out the URL before it is displayed.


// hide the URL by default for people too lazy to click "None"
add_filter('attachment_fields_to_edit', 'suppress_linkURL');
function suppress_linkURL($fields) {
$img_url = $fields['image_url']['value'];
if(!empty($img_url)){
$html = $fields['url']['html'];
if(!empty($html)) {
$fields['url']['html'] = str_replace("value='$img_url'","value=''",$html);
}
}
return $fields;
}


I doubt there is going to be a lot of demand for this particular snippet of code, but hopefully somebody will find it helpful.

Wednesday, 20 January 2010

WordPress Theme URL Tip

Lately I've been putting a lot of hours into developing a couple of sites using the WordPress and WPMU platforms. These platforms are a solid starting point for pulling a content/post based site together relatively quickly - the wealth of useful plugins also helps reduce the chance of you having to re-invent the wheel.

Having said that there is still a lot to do to create a professional website that has it's own look and feel - much of this can be achieved by creating a custom theme.

If you are creating a custom theme you will probably need to link to multiple elements within that theme's directory structure. The most common approach to do this is somthing like this:

<img src="<?php bloginfo('stylesheet_directory'); ?>/images/myimage.png">

<?php
echo '<img src="'.get_bloginfo('stylesheet_directory').'/images/myimage.png">';
?>


I've certainly been using a lot of the latter style, until today.

I decided to clean up my code a bit and put the following line at the top of my theme's functions.php file:

<?php
if(!defined('WP_THEME_URL')) {
define( 'WP_THEME_URL', get_bloginfo('stylesheet_directory'));
}
?>


Then I replaced all the get_bloginfo('stylesheet_directory') instances with the constant WP_THEME_URL. Now my code is a lot more readable and there is less typing.


<img src="<?php echo WP_THEME_URL; ?>/images/myimage.png">

<?php
echo '<img src="'.WP_THEME_URL.'/images/myimage.png">';
?>


Using a constant like this should provide a slight performance increase here too - I haven't done any performance tests, but the current get_bloginfo() process is a fairly convoluted chain of function calls.

Note: Just in case the WP platform does start using this constant in the future, the constant's value is not set if it is already defined.

UPDATE: After this post was made I discovered WordPress defines a TEMPLATEPATH constant, but no constant currently exists for the TEMPLATEURL.

Saturday, 3 October 2009

PHP Parse Error: syntax error, unexpected $end

Yesterday I decided to upgrade my XAMPP install from (ye olde) v1.5.5 to (the current) v1.7.2. This was mainly precipitated by my inability to install Movable Type - apparently due to missing PERL libs. I like XAMPP. In my experience it's the easiest way to install the Apache/PHP/MySQL stack on a Win32 machine and I've been using it for years. So, since there was no simple upgrade path from v1.5.5 to v1.7.2, I set about backing up all of my development mySQL databases, and httpd.conf and extra\httpd-vhosts.conf files, etc...

I like to keep my root folder clean, so on the last install I'd opted for "c:\program files\xampp", but since I'd read that "program files" could cause major PERL problems, this time I installed in "c:\xampp". Installation went pretty smoothly, and I was able to drop in my old extra\httpd-vhosts.conf file with no problems. Then I re-imported the mySQL databases I needed and checked all my development sites were OK.

I did have an unexpected problem when I tested one of my sites - I was presented with the following error:
Parse error: syntax error, unexpected $end in {filename} on line {linenumber}

If you Google that error, you'll see a lot of pages stating that "it is caused by a missing curly bracket" or a bad class definition, which was definitely not the case for me. The cause in this instance was that this particular site's code was using Short Open Tags.

XAMPP's php.ini file states that Short Open Tags is a php.ini directive that:
"...determines whether or not PHP will recognize code between <? and ?> tags as PHP source which should be processed as such. It's been recommended for several years that you not use the short tag "short cut" and instead to use the full <?php and ?> tag combination. With the wide spread use of XML and use of these tags by other languages, the server can become easily confused and end up parsing the wrong code in the wrong context. But because this short cut has been a feature for such a long time, it's currently still supported for backwards compatibility, but we recommend you don't use them."

Due to the number of pages using these codes, I opted to update php.ini to allow Short Open Tags, but I fully endorse the above recommendation to use <?php in any new or updated code.

Finding the cause and implementing the solution was a simple matter, however I thought I should post a note about it here as the curly bracket comments could confuse some users, and hopefully this will help somebody. The default PHP setting for this directive is "On", (although XAMPP have disabled it in their install), so Short Open Tags will be supported unless your php.ini contains the following line - I'll let you decide if that's good or bad.
short_open_tag = Off

Friday, 4 September 2009

Short rant about quotes

It seems to me that a high percentage of PHP programmers are making a simple mistake in their code that increases the execution time of their scripts. I certainly seem to be frequently fixing the problem in other people's code, whether I am maintaining a website, or using an open source class or plugin, etc.

To some, the following two statements might appear to be functionally identical, but in the second statement PHP has to parse the double-quoted content and check for any variables to evaluate before outputting it.

<?php

echo 'Hello World, so long and thanks for all the ghoti!';
echo "Hello World, so long and thanks for all the ghoti!";

?>


If you're thinking, "So what? It's just one line..." then you are not thinking like a programmer. "Expect the unexpected" is one of the first rules of defensive programming. Imagine using this statement in a function or method that is executed many times in one script, or if it's called a few hundred times from within a loop, and maybe on a page which suddenly gets ten times the traffic you expected. All those extra CPU cycles quickly start to add up.

Now, think about all the times that static text is used inside your scripts outside of echo statements, because they will be parsed in exactly the same way. It's easy to imagine how this can start making a difference to the resources your site uses.

In a nutshell, if you're not evaluating anything in the string, use single quotes.

NB: ghoti = fish.