5

I am looking for a way to edit the link that get inserted in the editor when the user choose to add a media. The goal would be to add a class with the media type (pdf) in the link.

I know how to get the mime type but I am not sure which hook to use to retrieve the link before it gets inserted. Could you point me in the right direction?

Thanks!

3

So thanks to @amritanshu and @wycks github's code, here is the solution for those in need to add a class with the media type to the attachment url before it gets inserted in the editor :

if ( ! function_exists( 'epc_add_class_pdf' ) ) :

    function epc_add_class_pdf( $html, $id ) {

        $attachment = get_post( $id );
        $mime_type = $attachment->post_mime_type;

        // I only needed PDF but you can use whatever mime_type you need
        if ( $mime_type == 'application/pdf' ) {
            $src = wp_get_attachment_url( $id );
            $html = '<a class="pdf" href="'. $src .'">'. $attachment->post_title .'</a>';
        }

        return $html;
}
endif;
add_filter('media_send_to_editor', 'epc_add_class_pdf', 20, 3);
| improve this answer | |
2

Here's a shorter way to do it (PHP 5.4+):

add_filter( 'media_send_to_editor', function( $html, $send_id, $attachment )
{
  $class = wp_check_filetype( $attachment['url'] )['ext'];
  return str_ireplace( '<a href', sprintf( '<a class="%s" href',$class ? $class : 'unknown' ), $html );
}, 10, 3 );

where we get the attachment's info from the third input argument.

We could also use the mime type data, from wp_check_filetype(), instead of the extension.

| improve this answer | |
1

This is not the answer but just the hint.

media_send_to_editor should be the hook that should help you. Not sure how but came across this while searching for my problem

I would have commented but still 4 points short, so unable to comment

All the best

| improve this answer | |
  • @Pipo My pleasure.. Any idea how to do that for existing media. This will only work when you add new media but not for the existing media. – terminator Jul 8 '15 at 13:22
  • I don't think this is the best answer as I don't know much about SQL but I would try to use the REPLACE function of mysql to add a class after the end of the href. Of course this is kind of a hack and will only works if you can find a similarity in the links you want to replace (for example: replacing .pdf"> by .pdf" class="your-class"> in the relevant tables). But this is just an idea... – Pipo Jul 8 '15 at 14:43

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.