Tag Archives: custom functions

Get an attachment ID by URL in WordPress

We all know you can use wp_get_attachment_url() to return an attachment’s URL by passing in the ID, but what about the reverse scenario?

There are a lot of long-winded examples of how to get an attachment ID by URL floating around the interwebs. Most of them limit results to only returning images or use expensive DB queries. Really, there should be a function for this in core, but there isn’t.

Needless to say, I wasn’t really happy with any of the solutions I found people using, so I decided to take a stab at it.

Below is the most lightweight method I’ve come up with (so far) to get an attachment ID by passing through an attachment URL.

Example usage

Just as an example, this would echo the attachment ID integer of test-image.jpg onto the page:

This would echo the same result as above because we are ignoring www usage in the URL being passed through:

This would echo nothing, because the image doesn’t exist in the WordPress uploads directory:

And finally, this would also echo nothing because the URL of the file is pointing to an external domain:

Conclusion

We managed to fetch an attachment ID in just a few lines of code with no expensive DB queries! Awesome 8-)

Now you can do cool things like turn a URL into an absolute path:

For more information about what was used in this function, please see:
http://php.net/manual/en/function.explode.php
http://php.net/manual/en/function.parse-url.php
http://php.net/manual/en/function.str-ireplace.php
http://codex.wordpress.org/Function_Reference/home_url
http://codex.wordpress.org/Determining_Plugin_and_Content_Directories#Constants
http://codex.wordpress.org/Class_Reference/wpdb#SELECT_a_Column

Was this code helpful to you? Let me know in the comments!

Remove specific menu items from the WordPress Admin

Sometimes it’s best – especially when you’re using WordPress as a CMS – to remove those unwanted admin menus that create clutter for clients. They are never going to use them so why confuse their admin experience? For example: if the client isn’t going to blog, why include Posts or Comments in the menu at all?

Just insert this code into the functions.php file of your WordPress theme and *bam!* no more clutter. Please note that we are not going to restrict the Administrator user experience, this will just affect logged in users who can’t manage options.

(Make sure to edit the $restricted array with the items you want to hide, this is just an example so you can see what’s possible) Enjoy!

Add prefixes to WordPress post types when a theme is activated

Recently, I had a real problem on my hands.

I had neglected to prefix the post type names in some of my themes, and as it turns out, so did another popular WordPress plugin. Long story short: this plugin became unusable when running my themes, and this did not make my users very happy.

It became clear that I needed to bust out some ninja moves to overcome this dilema.

The code below is the solution I drafted – maybe it will help you too. It’s a function that runs when the theme is in use, and rewrites the post type names in the database with any prefix you choose.

After the theme is activated the specified post types will be renamed to: fjarrett_acme, fjarrett_foo and fjarrett_bar.

Sadly, there is not yet a hook that will fire only when themes are activated/updated. The after_setup_theme action is a little misleading in that it fires when WordPress sets up the current theme, not when an admin activates and/or updates the current theme.

So, it’s basically firing with every load of WordPress when the theme is active. Someone first made a patch for this 3 years ago and it looks like it’s finally being revisited.

For that reason, this is by no means the most resource-friendly solution, but we are killing the script if the prefixed post type already exists – which requires an additional query – but this is crucial for two reasons:

  1. So we’re not attempting to update the database with every page load – after the original post types are given prefixes the database update will never run again.
  2. So other plugins/themes (like the one I was in conflict with) can be installed later, creating their blasphemous post type names, and we won’t attempt to rewrite them.

Hopefully this is helpful to you and your project in some way. If so, please tell me about it the comments!

How to hide your WordPress version number…completely

Did you know that your WordPress version number is visible to everyone?

As Matt Mullenweg rightly pointed out several years ago, simply hiding your WordPress version number is not enough by itself to stay protected from potential threats (you should always be keeping your WordPress installation up-to-date).

But perhaps you have a client who has specifically requested its removal or maybe you just like keeping things on the safe side, either way there are a lot of tutorials out there on how to remove it from various areas but none that I’ve found showing how to remove it from every area at the same time.

The WordPress version number appears in three areas:

1. Generator Meta Tag in the Header

<meta name="generator" content="WordPress 3.3.2" />

2. Generator Tag in RSS Feeds

<generator>http://wordpress.org/?v=3.3.2</generator>

3. Query Strings on Scripts & Styles

If a script or style does not specify a version number when enqueued, the current version of WordPress is used.

foo.js?ver=3.3.2

One Block of Code to Rule Them All

Just enter this into your functions.php file and your WordPress version will be safely hidden from the public.

However, there is one small caveat to be aware of when using this method: This function will check to see if the ver query string matches the WordPress version number, so if the version of the enqueued script happens to be the exact same as the WordPress version then its version string will be removed as well.

This will occur rarely (if ever), especially when the current WordPress version is a point release, such as 3.3.2.

Add first and last classes to your loop without using JavaScript

So you’re a pixel-perfect designer who wants to keep control over your WordPress loop styles? Hell yeah! You’re already pretty cool in my book.

You’ve probably got a fancy post separator, or a brilliant doodle to fit between your last post and the comments. Whatever the reason, you don’t have CSS class selectors for targeting the first or last posts in your archive – and you really need them.

There are a lot of tutorials on how to achieve this with jQuery. But it’s not worth relying on JavaScript for something that can easily be done with a little PHP magic.

First, insert this function into your functions.php file.

Now, open up loop.php and replace post_class() with the newly created fjarrett_post_class().

This new function accepts the same parameters as the original function, so you can use it the exact same way. The only difference will be that the first and last posts will be marked automatically with an appropriate class name. Enjoy total control. :)

If this helped you in any way I’d love to hear about it in the comments!

Create a dropdown of custom taxonomies in WordPress (the easy way)

So you’ve been busy taking advantage of custom post type functionalities in WordPress since mid 2010. And of course you’re using custom taxonomies too, right? Of course you are.

If you’re a theme or plugin developer you may have ran across the need to populate a dropdown list of your custom taxonomies. Essentially there are two different (easy) ways to accomplish this. One you always hear about and the other you don’t.

Method #1

Since WP 2.1 the wp_dropdown_categories function has been around but in WP 3.0 the taxonomy argument was introduced. So just calling this function and using the taxonomy argument is probably the absolute easiest way to populate a dropdown list of your custom taxonomies.

This method is great if you need the output of your dropdown values to be the category ID. Because this is the HTML that will be generated:


However, let’s say you want your option value output to be the taxonomy’s slug instead of the ID. Well, that’s impossible to achieve using the wp_dropdown_categories function.

Peering into the WordPress core we see that this function is using a walker class called Walker_CategoryDropdown. This walker is designed to output only the ID as the value for each dropdown item. There is not an argument in the function to control value output.

Method #2

That’s where Method #2 comes in. We’ll have to write our own custom function that will generate the dropdown so we can output each option value as a slug:

function fjarrett_custom_taxonomy_dropdown( $taxonomy ) {
	$terms = get_terms( $taxonomy );
	if ( $terms ) {
		printf( '' );
	}
}

So, now that we’ve got a cool custom function, we can call anywhere in our code like so:

Expansions on Method #2

If you’re a coding rockstar you can take Method #2 even further by making room for more parameters. This will give you even more control and make it function more like wp_dropdown_categories does:

function fjarrett_custom_taxonomy_dropdown( $taxonomy, $orderby = 'date', $order = 'DESC', $limit = '-1', $name, $show_option_all = null, $show_option_none = null ) {
	$args = array(
		'orderby' => $orderby,
		'order' => $order,
		'number' => $limit,
	);
	$terms = get_terms( $taxonomy, $args );
	$name = ( $name ) ? $name : $taxonomy;
	if ( $terms ) {
		printf( '' );
	}
}

Then call it in your code like so:

Conclusion

As you can see, WordPress has done a fabulous job of making room for you and I to do pretty much whatever we want.

To reference all available arguments and parameters, please see:
http://codex.wordpress.org/Function_Reference/wp_dropdown_categories
http://codex.wordpress.org/Function_Reference/get_terms

Was this code helpful to you? Let me know in the comments!

Create a shortcode for displaying Order History on your Cart66 site

I’m a fan of Cart66. It’s easy to integrate and has a fair amount of features that make it a flexible e-commerce and member management solution for WordPress.

However, there’s one pretty big feature that Cart66 is missing: the ability to display the Order History of a logged in user.

What? Really?

Yes. Really.

This doesn’t really require a lot of explanation. It was easy to achieve with a simple SQL query and a custom loop. And all without editing the Cart66 core! So you can keep updating the plugin without worry. :)

Websites that sell digital goods will especially find this handy since users will be able to view their past receipts to re-download purchases.

Just insert this code into the functions.php file of your WordPress theme and use the shortcode [order_history] on a member’s only page to show the Order History for that user. Enjoy!

The original code for this idea came from a post by Alison Barrett.

/* Shortcode for displaying Cart66 order history for the current logged in user
 *
 * @return {string} $table
 * @shortcode order_history
 */
function cart66_order_history( $atts, $content = null ) {
	extract( shortcode_atts( array(), $atts ) );
	global $wpdb;
	$results = $wpdb->get_results( "SELECT ouid, ordered_on, trans_id, total, status FROM " . $wpdb->prefix . "cart66_orders WHERE account_id = " . Cart66Session::get( 'Cart66AccountId' ) . ' ORDER BY ordered_on DESC' );
	foreach ( $results as $order ) {
		$data .= sprintf( '%s%s%s%s%s', $order->trans_id, date( 'F j, Y', strtotime( $order->ordered_on ) ), $order->total, ucwords( $order->status ), home_url( '/store/receipt/?ouid=' . $order->ouid ), __( 'Click to view receipt', 'cart66' ), __( 'View Receipt', 'cart66' ) );
	}
	$table = '' . $data . '
Order Number Date Total Order Status Receipt
'; return $table; } add_shortcode( 'order_history', 'cart66_order_history' );