Treehouse: Grow your CSS skills. Land your dream job.

Display / Echo friendlier MIME-type names in WordPress

  • # May 21, 2012 at 4:15 pm

    I am using a simple function to pull all PDF and MSWord documents attached to a post (a custom post-type) and return them in an unordered list for download, like so:

    Simple enough. But the outputted HTML return “Download XYZ Document Title (application/pdf)”.

    I want it to return a ‘friendlier’ name for the file type, like so, “Download XYZ Document Title (PDF)”

    Is there any way to achieve this?

    Thanks in advance for any help.

    # May 22, 2012 at 10:09 am

    You could wrap that post_mime_type property in a function that translates it to your “simpler” format. Probably a simple map of mimeTypes => friendlyMimeTypes

    # May 22, 2012 at 2:54 pm

    Hey Traq. Thanks for the reply.

    I’ve only ever used a translate function to change “Posts” to say “Articles”… But even that was from a tutorial.

    Any hints / snippets?

    # May 22, 2012 at 3:25 pm

    *Assuming* $attachment->post_mime_type prints out application/pdf, then you could do something like this:

    < ?php

    function friendly_mime( $mime ){
    $mime_map = array(
    "application/pdf" => "PDF"
    // and so on, like:
    ,"mime_type" => "Friendly"
    // if $mime not present in the array, return it unchanged
    if( empty( $mime_map[ $mime ] ) ){ return $mime; }
    // otherwise, return the friendly mime-type
    return $mime_map[ $mime ];

    print friendly_mime( "application/pdf" );
    // prints "PDF"

    print friendly_mime( "application/rss+xml" );
    // not in our list, so just prints "application/rss+xml"
    # May 22, 2012 at 3:37 pm

    Hi Traq

    My code above resides in archive-downloads.php

    I am echo-ing the resulting text, not printing.

    Feel a bit stupid right now… Where are you suggesting your snippet should go – functions.php? Also, how does the “print friendly_mime” but fit in..?

    # May 22, 2012 at 6:06 pm

    put the translating function after the $args array and call it on the line where you echo $attachment->post_mime_type;

    echo friendly_mime($attachment->post_mime_type);

    # May 22, 2012 at 8:53 pm

    echo is an alias for print.

    I don’t know where in WP you define your custom functions. I believe it’s in functions.php, yes. As long as the function is defined somewhere where it will be available when you try to use it, you’re fine.

    You would use this function in your code above instead of printing out the post_mime_type directly:

    // instead of
    echo $attachment->post_mime_type;
    // you would use
    echo friendly_mime( $attachment->post_mime_type );
    # May 23, 2012 at 3:06 am


    Thanks Traq and Schmotty – worked like a charm and I’ve learnt something new.


Viewing 8 posts - 1 through 8 (of 8 total)

You must be logged in to reply to this topic.