Action for opening attachment or manipulaitng all attachment links

I am relatively new to WP-development and have now spent a while reading the docs and playing around but am of the assumption that the way I am trying to solve this problem is much more complicated than it has to be.

The end goal of my ‘learning project’ at the moment is to either execute an action in the backend if an attachment is opened (think pdf-files), so do something if a pdf-attachment link is clicked or – if that’s not possible – manipulate all links to pdf-attachments to include an onClick-event which will in effect AJAX call the same action in the backend.

I had started with the first way but was not able to find an action which fits this scenario so I went on to filters and tried many ways, i.e. finding all links on the page to pdf-attachments and manipulating them, which will give me the correct links and I can manipulate the HTML all I want within my function and echo it out (to the top of the page) but they will not overwrite the one in their original position:

function addAlert($post) {

$attachments = get_children( array (
‘post_parent’ => $post->ID,
‘post_type’ => ‘attachment’,
‘post_mime_type’ => ‘application/pdf’
));

if ( empty($attachments) ) {
// no attachments here
} else {
foreach ( $attachments as $attachment_id => $attachment ) {
$l = wp_get_attachment_link( $attachment_id, ”);
$h = addAlertTrigger($l);
echo $h;
return $h;
}
}
}

I have also tried the ‘term_link’-filter route:

function add_via_filter( $url, $term, $taxonomy ) {
$url = home_url() . ‘?test’ . $term->slug;
return $url;
}
add_filter( ‘term_link’, ‘add_via_filter’, 10, 3 );

which seems to be the wring filter. It works but not on the attachment links…

There has to be something I missed.
Would appreciate if someone pointed me in the right direction.

Thanks

Read more here:: Action for opening attachment or manipulaitng all attachment links

Leave a Reply

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