This WordPress tweak is pretty unlikely to come up for most developers, but I was asked to remove the Google+ field from the Contact Info section of the User admin page. Here's a quick snippet to paste into functions.php to do so:
function custom_admin_js() {
// hide WP's Googleplus input on user profile
if( strpos($_SERVER["REQUEST_URI"], '/user-edit.php')) {
echo '<script type="text/javascript"> jQuery(\'#your-profile input[name="googleplus"]\').parent().parent().hide(); </script>';
}
}
add_action('admin_footer', 'custom_admin_js');
Showing posts with label WordPress. Show all posts
Showing posts with label WordPress. Show all posts
Tuesday, 21 January 2014
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.
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.
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.
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
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
.
Thursday, 31 March 2011
WordPress Post ID from Permalink
Lately I've been migrating a few websites from Movable Type to WordPress. One of the SEO issues involved with that is supporting the old site's URLs so that existing page rankings don't drop off en masse.
A common Movable Type URL format appends the entry id to the URL which makes it easy to redirect to the correct content IF you have preserved the entry id from MT as the new post id in WP, other times it can be a lot more convoluted.
One of the functions I sometimes need to employ is pretty uncommon, (which is not surprising due it's rare use), so I thought I'd create a quick post here so I can can easily find it next time I need it.
The function is url_to_postid()
This function returns the id for a post or page from a given URL. I like to this of this function as the reverse of the commonly used get_permalink().
It's pretty hard to turn up any useful search results for this function so hopefully this page will help somebody when they need it.
A common Movable Type URL format appends the entry id to the URL which makes it easy to redirect to the correct content IF you have preserved the entry id from MT as the new post id in WP, other times it can be a lot more convoluted.
One of the functions I sometimes need to employ is pretty uncommon, (which is not surprising due it's rare use), so I thought I'd create a quick post here so I can can easily find it next time I need it.
The function is url_to_postid()
This function returns the id for a post or page from a given URL. I like to this of this function as the reverse of the commonly used get_permalink().
It's pretty hard to turn up any useful search results for this function so hopefully this page will help somebody when they need it.
Wednesday, 18 August 2010
Wordpress colorpicker.js
The Wordpress wp_enqueue_script reference page lists Colorpicker as one of the default scripts imstalled, but doesn't offer any clues on how to implement it. The link on that page (currently) points to http://mattkruse.com/ which has no details on how to use it either.
The best online reference I've found so far is Matt Kruse's JavaScript Toolbox - Color Picker Swatch Popup which suggests you look at http://www.javascripttoolbox.com/ which doesn't have any documentation about colorpicker.js. Here's a link to the cached version of the documentation page just in case the source page is taken down: http://webcache.googleusercontent.com/search?q=cache:nlxkcPxsepEJ:mattkruse.com/javascript/colorpicker/
The javascript file /wp-includes/js/colorpicker.js is minified and browsing it doesn't easily reveal anything. There's a lot more information in /wp-includes/js/colorpicker.dev.js but it's not as straightforward as it could be.
What you need to do:
Include the colorpicker javascript file:
Create a colorpicker object and hidden div, preferably put this near the end of your page:
Set up the input field and picker anchor tag:
Alternatively, you could also try this approach where you ditch the anchor tag and use some jQuery to handle the rest:
Conclusion
This snippet of code is showing it's age and there are better options out there if you need a color picker. The more I try to use it the more I become frustrated with it.
jQuery UI doesn't have a native one (yet) but I am guessing that will come in time. For now, probably the best candidate is the jQuery plugin jPicker from Digital Magic Productions.
The best online reference I've found so far is Matt Kruse's JavaScript Toolbox - Color Picker Swatch Popup which suggests you look at http://www.javascripttoolbox.com/ which doesn't have any documentation about colorpicker.js. Here's a link to the cached version of the documentation page just in case the source page is taken down: http://webcache.googleusercontent.com/search?q=cache:nlxkcPxsepEJ:mattkruse.com/javascript/colorpicker/
The javascript file /wp-includes/js/colorpicker.js is minified and browsing it doesn't easily reveal anything. There's a lot more information in /wp-includes/js/colorpicker.dev.js but it's not as straightforward as it could be.
What you need to do:
Include the colorpicker javascript file:
wp_enqueue_script( 'colorpicker');
Create a colorpicker object and hidden div, preferably put this near the end of your page:
<SCRIPT LANGUAGE="JavaScript">
var cp = new ColorPicker(); cp.writeDiv();
</SCRIPT>
Set up the input field and picker anchor tag:
Color: <INPUT TYPE="text" id="color2" name="color2" SIZE="20" VALUE=""> <A HREF="#" onClick="jQuery('#color2').each(function(index){cp.select(this,'pick2');return false;});return false;" NAME="pick2" ID="pick2">Pick color</A>
Alternatively, you could also try this approach where you ditch the anchor tag and use some jQuery to handle the rest:
<INPUT TYPE="text" id="color2" name="color2" SIZE="20" VALUE="" class="jColorpicker" >
<SCRIPT LANGUAGE="JavaScript">
jQuery(".jColorpicker").bind("click", function(){cp.select(this,jQuery(this).attr(\'name\')); });
</SCRIPT>
Conclusion
This snippet of code is showing it's age and there are better options out there if you need a color picker. The more I try to use it the more I become frustrated with it.
jQuery UI doesn't have a native one (yet) but I am guessing that will come in time. For now, probably the best candidate is the jQuery plugin jPicker from Digital Magic Productions.
Friday, 18 June 2010
WordPress Broken Theme : Template is missing
I came across an interesting bug on a Wordpress development project I was working on this week. The issue was that the Wordpress Theme was reported as a Broken Theme because the "Template is missing" on the Appearances->Themes admin page.

In most cases the site was performing as expected using the allegedly broken theme, however the custom template selection was no longer available on the Pages admin page. (This is where I first spotted there was a problem and then discovered the Appearances->Themes admin page.)
After poking about for a bit, I traced the problem to a rather innocuous looking line the designer had added to the theme's style.css file.
It's just the "TEMPLATE:" portion that caused the style.css parser to fail. This line works just fine:
I doubt this error comes up often, but it took a few minutes to track down the problem so I thought I'd post something here to hopefully save somebody time in the future.

In most cases the site was performing as expected using the allegedly broken theme, however the custom template selection was no longer available on the Pages admin page. (This is where I first spotted there was a problem and then discovered the Appearances->Themes admin page.)
After poking about for a bit, I traced the problem to a rather innocuous looking line the designer had added to the theme's style.css file.
/* UNIQUE CATEGORY TEMPLATE: VIDEO*/
It's just the "TEMPLATE:" portion that caused the style.css parser to fail. This line works just fine:
/* UNIQUE CATEGORY TEMPLATE : VIDEO*/
I doubt this error comes up often, but it took a few minutes to track down the problem so I thought I'd post something here to hopefully save somebody time in the future.
Monday, 5 April 2010
Managing WordPress Filters
WordPress filters offer a great way to control many aspects of the way the WordPress engine processes or publishes information, without hacking any of the core code.
In recent projects I've found filters to be the easiest way to manage many of the functionality requests the client has made. Some examples of the are: RSS formatting, custom Avatars, auto rendering images/links in comments, controlling the Category used in permalinks, reformatting legacy data in posts, and even tweaking the behaviour of Admin pages.
All these changes can add up to quite a chunk of code and functions.php was getting quite large and difficult to maintain with all the other general functions in there. I decided to move all the filter functions and add_filter statements into a separate file called functions_filters.php and include it from functions.php. This made it much easier to add/maintain filters and localised the changes to that dedicated file.
It's an incredibly simple idea, but I highly recommend taking this approach if you are implementing filters to any degree.
If you've not used filters but want to learn more, you can find a good introduction here: http://codex.wordpress.org/Plugin_API/Filter_Reference
In recent projects I've found filters to be the easiest way to manage many of the functionality requests the client has made. Some examples of the are: RSS formatting, custom Avatars, auto rendering images/links in comments, controlling the Category used in permalinks, reformatting legacy data in posts, and even tweaking the behaviour of Admin pages.
All these changes can add up to quite a chunk of code and functions.php was getting quite large and difficult to maintain with all the other general functions in there. I decided to move all the filter functions and add_filter statements into a separate file called functions_filters.php and include it from functions.php. This made it much easier to add/maintain filters and localised the changes to that dedicated file.
It's an incredibly simple idea, but I highly recommend taking this approach if you are implementing filters to any degree.
If you've not used filters but want to learn more, you can find a good introduction here: http://codex.wordpress.org/Plugin_API/Filter_Reference
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.
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.
I doubt there is going to be a lot of demand for this particular snippet of code, but hopefully somebody will find it helpful.
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:
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:
Then I replaced all the
Using a constant like this should provide a slight performance increase here too - I haven't done any performance tests, but the current
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.
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.
Thursday, 17 December 2009
"X-Moz: prefetch" and skewed page-hits
Earlier today I installed a WordPress plugin recommend for tracking the popularity of posts. The plugin is unsurprisingly named "Recently Popular". After installing the plugin I ran some quick tests and found that I was getting extra hits recorded. I spent a bit of time back-tracking to find the source and after systematically disabling all other plugins and page elements found that it was firing in wp_head() in the page header.
After some more digging, I noticed that the extra hit was for the chronologically next published post and that the problem occurred in both WordPress and WordPressMU. This wasn't making a lot of sense so I decided to try a different browser - more of a sanity test than anything. That's when I found it didn't occur in Chrome, or Opera - just Firefox 3.5.6 that I'd upgraded to a few hours earlier.
I fired up the Live HTTP Headers add-on and checked out the requests Firefox was making. It was definitely making both post requests. I took a closer look at the second request and noticed the extra header "X-Moz: prefetch".
A quick search for X-Moz: prefetch turns up Mozilla's Link prefetching FAQ which gives a good description of what is happening and why. WordPress creates a tag similar to the following when wp_head() is executed:
<link rel='next' title='The Next Post' href='http://your_domain/year/month/day/the_next_post/' />
I am unaware of anyway to disable the prefetch hints. You could edit your header.php and remove the wp_head() statement, but many plugins rely on the execution of this function so results could be unexpected and undesirable. The issue for me was not that the hint was published but that the prefetch hits were being counted as real post requests, as well as the actual request when I clicked through a second or two later. This would seriously skew the perceived popularity of posts.
My solution was to ensure that the Recently Popular plugin ignored post requests that passed the "X-Moz: prefetch" header. Depending on your server configuration, the method of checking the header exists may differ - apache_request_headers() (alias getallheaders()) is only supported when PHP is installed as an Apache module. Most servers should support checking for $_SERVER['HTTP_X_MOZ'].
I wonder how many other people will wonder why their page hit stats have mysteriously increased without any increase in ad impressions, etc.
I will contact the plugin author to suggest an update once I've published this post.
After some more digging, I noticed that the extra hit was for the chronologically next published post and that the problem occurred in both WordPress and WordPressMU. This wasn't making a lot of sense so I decided to try a different browser - more of a sanity test than anything. That's when I found it didn't occur in Chrome, or Opera - just Firefox 3.5.6 that I'd upgraded to a few hours earlier.
I fired up the Live HTTP Headers add-on and checked out the requests Firefox was making. It was definitely making both post requests. I took a closer look at the second request and noticed the extra header "X-Moz: prefetch".
A quick search for X-Moz: prefetch turns up Mozilla's Link prefetching FAQ which gives a good description of what is happening and why. WordPress creates a tag similar to the following when wp_head() is executed:
<link rel='next' title='The Next Post' href='http://your_domain/year/month/day/the_next_post/' />
I am unaware of anyway to disable the prefetch hints. You could edit your header.php and remove the wp_head() statement, but many plugins rely on the execution of this function so results could be unexpected and undesirable. The issue for me was not that the hint was published but that the prefetch hits were being counted as real post requests, as well as the actual request when I clicked through a second or two later. This would seriously skew the perceived popularity of posts.
My solution was to ensure that the Recently Popular plugin ignored post requests that passed the "X-Moz: prefetch" header. Depending on your server configuration, the method of checking the header exists may differ - apache_request_headers() (alias getallheaders()) is only supported when PHP is installed as an Apache module. Most servers should support checking for $_SERVER['HTTP_X_MOZ'].
I wonder how many other people will wonder why their page hit stats have mysteriously increased without any increase in ad impressions, etc.
I will contact the plugin author to suggest an update once I've published this post.
Friday, 21 August 2009
WordPress Plugins
Earlier this month I decided to move pantsonhead.com from it's ancient codebase onto a current CMS platform. The goal was to make it easier to manage, and hopefully spur me into making more frequent posts, and to get some experience with another platform.
After a little deliberation and discussion with friends I decided to go with WordPress. With WordPress MU and BuddyPress looking to be quite big in the near future I thought this was a smart choice. I'd tried Joomla! before but didn't have a great experience. ExpressionEngine was also a possibility, I've used it before and liked it a lot and ExpressionEngine 2.0 being built on CodeIgniter sounds great.
In the end WordPress won out because it's open-source, because pantsonhead.com is 90% blog, and because the plugin development community seems very active. For me, writing Plugins is an attractive way to work on some bite-sized code projects for fun, and maybe even profit.
The conversion to WordPress was fairly painless although I did have to create a couple of plugins to provide the functionality I wanted. I decided to release some of these into wild and the response so far has been quite positive.
Activity Sparks
Activity Sparks is a highly customizable widget to display a sparkline style graph in your sidebar indicate post and/or comment activity. This WordPress plugin leverages Google’s Chart API, so does not require the PHP GDI library. Customization options include Title, size, colour, background transparency, activity granularity and period.
RandomText
RandomText is a handy WordPress plugin that allows you to save, edit and delete categorized text, and inject random text by category into the sidebar (via widget) or pagebody (via template tags). Whether you want to display random trivia, quotes, helpful hints, featured articles, or snippets of html, you can do it all easily with RandomText.
RSS Blogroll
RSS Blogroll allows you to link to your favourite blogs via the latest items from their RSS feed. Article titles are much more attention grabbing and will deliver much higher quality traffic. We all hate clicking through to abandoned blogs – displaying article publication dates also lets readers know these are up to date and active sites. RSS Blogroll will create deeplinks to the target sites, which are much more useful for SEO than homepage links. Overall it’s a win-win situation with a better browsing experience for users and the linked sites getting more visitors who are actually interested in their content.
I'll be posting any future WordPress plugins on pantsonhead.com.
After a little deliberation and discussion with friends I decided to go with WordPress. With WordPress MU and BuddyPress looking to be quite big in the near future I thought this was a smart choice. I'd tried Joomla! before but didn't have a great experience. ExpressionEngine was also a possibility, I've used it before and liked it a lot and ExpressionEngine 2.0 being built on CodeIgniter sounds great.
In the end WordPress won out because it's open-source, because pantsonhead.com is 90% blog, and because the plugin development community seems very active. For me, writing Plugins is an attractive way to work on some bite-sized code projects for fun, and maybe even profit.
The conversion to WordPress was fairly painless although I did have to create a couple of plugins to provide the functionality I wanted. I decided to release some of these into wild and the response so far has been quite positive.
Activity Sparks
Activity Sparks is a highly customizable widget to display a sparkline style graph in your sidebar indicate post and/or comment activity. This WordPress plugin leverages Google’s Chart API, so does not require the PHP GDI library. Customization options include Title, size, colour, background transparency, activity granularity and period.
RandomText
RandomText is a handy WordPress plugin that allows you to save, edit and delete categorized text, and inject random text by category into the sidebar (via widget) or pagebody (via template tags). Whether you want to display random trivia, quotes, helpful hints, featured articles, or snippets of html, you can do it all easily with RandomText.
RSS Blogroll
RSS Blogroll allows you to link to your favourite blogs via the latest items from their RSS feed. Article titles are much more attention grabbing and will deliver much higher quality traffic. We all hate clicking through to abandoned blogs – displaying article publication dates also lets readers know these are up to date and active sites. RSS Blogroll will create deeplinks to the target sites, which are much more useful for SEO than homepage links. Overall it’s a win-win situation with a better browsing experience for users and the linked sites getting more visitors who are actually interested in their content.
I'll be posting any future WordPress plugins on pantsonhead.com.
Subscribe to:
Posts (Atom)