Skip to content
Advertisement

Globally add code snippet to WordPress PDF links using functions.php

Using functions.php in WordPress, how do I identify all links that contain .pdf (all links to PDF files), ignoring links to other types of files, and then add a bit of code to the element? For example:

BEFORE

<a href="/...some path.../file.pdf">

AFTER

<a onClick="...some code..." href="/...some path.../file.pdf">

The added code will be identical for all links. I assume I need some sort of variation on this function:

function modify_pdf_links($html){
    $html=preg_replace('<a', '<a onClick="...some code..."', $html);
    return $html;
}
add_filter('the_content', 'modify_pdf_links', 10);

I based that function on another function I am using which removes HEIGHT and WIDTH parameters from WordPress elements.

Advertisement

Answer

I would use javascript or jQuery for this as you are using JS anyway.

$('a[href~=.pdf]').click(function(e) {
    // your click action
    // e is a jQuery event
    // your <a> element is the variable this
});
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement