[SOLVED] 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:


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


<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.


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

Answered By – Bazdin

Answer Checked By – Marilyn (BugsFixing Volunteer)

Leave a Reply

Your email address will not be published. Required fields are marked *