Recent Updates Toggle Comment Threads | Keyboard Shortcuts

  • Frankie Jarrett 6:01 pm on May 8, 2013 Permalink | Reply
    Tags: attachments, , , , ,   

    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:

    <?php echo fjarrett_get_attachment_id_by_url( 'http://frankiejarrett.com/wp-content/uploads/2013/05/test-image.jpg' ) ?>

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

    <?php echo fjarrett_get_attachment_id_by_url( 'http://www.frankiejarrett.com/wp-content/uploads/2013/05/test-image.jpg' ) ?>

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

    <?php echo fjarrett_get_attachment_id_by_url( 'http://frankiejarrett.com/foo/test-image.jpg' ) ?>

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

    <?php echo fjarrett_get_attachment_id_by_url( 'http://www.anotherdomain.com/wp-content/uploads/2013/05/test-image.jpg' ) ?>

    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:

    <?php
    $url = 'http://frankiejarrett.com/wp-content/uploads/2013/05/test-image.jpg';
    $attachment_id = fjarrett_get_attachment_id_by_url( $url );
    $path = ( $attachment_id ) ? get_attached_file( $attachment_id ) : null;
    echo $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!

     
    • Weston Ruter 7:20 pm on May 8, 2013 Permalink | Reply

      What’s the use case for this function? I’m trying to think of why I’d need to look up a post associated with an uploaded file. Is it to obtain the attachment ID for an image that has been inserted into a post, one for which the ID-containing class name has been stripped?

      • Frankie Jarrett 8:48 pm on May 8, 2013 Permalink | Reply

        Hey Weston, yeah that’s one possible use case for it.

        In one of my themes I have a post meta field where users can enter a URL to a file, either one from the Media Library or an arbitrary one hosted elsewhere.

        By using this function we can determine whether or not the file in question has an attachment ID, and if so, the path can be retrieved using get_attached_file( $attachment_id ) to then pass inside a PHP force download script using readfile() in order to create a “Download File” link.

        I plan to post that force download functionality in its entirety in my next tutorial.

        • Rafal 7:05 am on May 12, 2013 Permalink

          I personally used a similar snippet found on stackexchange to get couple of different image sizes based on a single URL.

          I guess that adding wp cache to the db query could improve the snippet a bit.

    • Jeremy Ross 12:17 am on May 20, 2013 Permalink | Reply

      Is it safe to search the guid field? If someone changes the permalinks, or migrates urls without updating the guid field, this wouldn’t return anything even if the file actually existed.

      • Frankie Jarrett 10:05 am on May 20, 2013 Permalink | Reply

        Hey Jeremy! Thanks for your question.

        Changing permalinks on attachments in the WP Admin is not possible AFAIK. Even if you could, the GUID uses the actual file URL and not the permalink, which is a shortened URL using the attachment_id query string.

        Attachment media is the one exception to the “never touch GUID” rule. Since it uses the URL as the GUID it actually should be updated to the new hostname after a migration.

        However, the DB query in this function is using RLIKE to find a partial string match starting with the wp-content directory and ignores the hostname completely. E.g. wp-content/uploads/2013/05/test-image.jpg

        So even if you fail to update the GUID on attachments during a hostname migration, this function will still work (as long as the uploads directory hasn’t also changed).

  • Frankie Jarrett 3:45 pm on March 22, 2013 Permalink | Reply
    Tags: admin, , menu, ,   

    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!

     
  • Frankie Jarrett 8:26 am on May 25, 2012 Permalink | Reply
    Tags: , , , , , ,   

    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!

     
    • Pippin 12:37 pm on May 25, 2012 Permalink | Reply

      Great one man. I’m still planning to use this to fix the terrible name I used for the EDD post type.

  • Frankie Jarrett 6:41 pm on May 10, 2012 Permalink | Reply
    Tags: , , security, ,   

    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&gt;

    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.

     
    • Weston Ruter 11:23 pm on May 10, 2012 Permalink | Reply

      Good call on scrubbing the dependency versions. Here is an alternate filter which I think would be more robust:

      /* Hide WP version strings from scripts and styles
       * @return {string} $src
       * @filter script_loader_src
       * @filter style_loader_src
       */
      function fjarrett_remove_wp_version_strings( $src ) {
      	global $wp_version;
      	parse_str(parse_url($src, PHP_URL_QUERY), $query);
      	if ( !empty($query['ver']) && $query['ver'] === $wp_version ) {
      		$src = remove_query_arg('ver', $src);
      	}
      	return $src;
      }
      add_filter( 'script_loader_src', 'fjarrett_remove_wp_version_strings' );
      add_filter( 'style_loader_src', 'fjarrett_remove_wp_version_strings' );
      • Frankie Jarrett 11:29 pm on May 10, 2012 Permalink | Reply

        Very nice, Weston! I’ve never seen PHP_URL_QUERY before. I’ll have to remember that one.

    • Dean Stewart 1:59 pm on May 31, 2012 Permalink | Reply

      Hi

      Just a quick note to say thanks for the script.

      Been working on a WP website and some of the older alternatives simply did not work but this did straight away

      Thanks

    • JNPerez 8:37 pm on October 9, 2012 Permalink | Reply

      Here’s another alternative…

      function hide_wp_version($src) {
      global $wp_version;
      	return str_replace("?ver=$wp_version", "", $src);
      }
      add_filter('script_loader_src', 'hide_wp_version');
      add_filter('style_loader_src', 'hide_wp_version');
      
      • ReTox 4:23 pm on January 15, 2013 Permalink | Reply

        Won’t work if you have another ‘?’ in the url (google web font, for example). ‘?’ will be encoded.

  • Frankie Jarrett 9:12 pm on April 27, 2012 Permalink | Reply
    Tags: heroized, ,   

    I’ve been HEROized as The Solution! 

    Last night was a very memorable night for me as my friends at X-Team unveiled my inner superhero, dubbing me as The Solution!

    The Solution

    When Frankie Jarrett isn’t living his passion for working in WordPress or making music, he’s the problem solving hero known as, The Solution!

    He was born with the amazing cerebral super power to solve any problem. Frankie can always figure out a way to communicate clearly with anyone. He is often there to listen and offer support to others, no matter how difficult their situation. Often Frankie only needs to say, “I’ll have to think about this problem a little”, and soon he has an exciting solution!

    No situation is too big or too small and there is no danger too great for him to face. Whether you are having a tough time remembering trigonometry for your math test, or you are stranded on the roof of a burning building, The Solution can always figure out the best way to rescue someone.

    Our hero also has the natural ability to inspire others, whether leading musical worship in his church or jamming with friends, Frankie uses his voice and musical talents to uplift and inspire those around him.

    When not saving the innocent, Frankie spends his time watching the History channel with his wife, whom he absolutely adores.

    Being HEROized is a true honor, and I am grateful to Dave and the rest of the team for recognizing me in this way.

    Now to create more solutions! :)

     
    • levininja 6:24 pm on June 20, 2012 Permalink | Reply

      Nice. I’ve always wanted to be known as a friendly (not necessarily neighborhood) problem-solver. It’s the servant-heart of a Christian software engineer. :-) Glad to see I’m not the only one.

      • Frankie Jarrett 9:35 am on June 21, 2012 Permalink | Reply

        Thanks, Levi!

c
compose new post
j
next post/next comment
k
previous post/previous comment
r
reply
e
edit
o
show/hide comments
t
go to top
l
go to login
h
show/hide help
shift + esc
cancel