How to open the_attachment_link ( WordPress ) in new window

Hello guys i have a post type attachment for PDF files using wp-types plugin. Actually the script work fine and display all PDF files in list but i need to open them i new window. Any idea how to solve this and make every file from the post type category to be opened in new window?

I know how to add this in normal HTML document or with a href with permalink.

Read More

<a href="#" title="My PDF File Title" target="_blank">PDF File</a>

For example i have similar PDF single file with the following code and is work fine:

<a href="<?php echo types_render_field("main-pdf");?>" target="_blank" title="Download <?php the_title(); ?> - Specifications"><i class="fa fa-file-pdf-o"></i> Download PDF Specification for <?php the_title();?></a>

I cannot make working the following code below to open each file in new window e.g follow this WordPress guide for “Display attached images and titles as a list” visit the link ( WordPress Codex )

target="blank"

Any suggestions or solutions with the code below?

<?php 
$args = array(
'post_type' => 'attachment',
'post_status' => 'any',
'target' => '_blank', // a try this but not working
'tax_query' => array(
    array(
        'taxonomy' => 'media_category',
        'field' => 'link',
        'terms' => 137
    )
)

);

$the_query = new WP_Query( $args );

if ( $the_query->have_posts() ) {
while ( $the_query->have_posts() ) {
    $the_query->the_post();


       echo '<li class="cataloguelist">';
       echo '<i class="fa fa-file-pdf-o"></i>';

       echo the_attachment_link( $attachment->ID, true);
       echo apply_filters( 'the_title', $attachment->post_title );

       echo '</li>';

}
} else {
// no attachments found
}

wp_reset_postdata();?>

Related posts

1 comment

  1. Remove 'target' => '_blank', // a try this but not working and add below code in theme’s functions.php to add target="_blank".

    It will only work when use the_attachment_link or wp_get_attachment_link

    function TargetAttachmentLink($markup) {
        return preg_replace('/^<a([^>]+)>(.*)$/', '<a\1 target="_blank">\2', $markup);
    }
    add_filter( 'wp_get_attachment_link', 'TargetAttachmentLink', 10, 6 );
    

Comments are closed.