Archived topic
Custom post type category archive links to open in a new browser window
9 replies · Started by George on May 2, 2018
I have a custom post type category archive set to culumns. Is there an easy way of settings the archive blog items to open in a new browser tab without modifying template files?
Without modifying template files? Probably not.
You could maybe use javascript. You want the titles to open the single posts in a new window?
Yes archive images and titles to open the single items in a new window. Basically anything that links to the single item but it needs to be for that particularly custom post type category archive ("video").
Can you link me to one of those pages? I'll see if I can write up some javascript for you.
It's not easy to link now, I am working locally but basically the page displays a custom post category archive of a custom post type "Video" that belongs to a category called "Videos". I have already targeted it before using the if ( is_category( 'videos' ) ) conditional. I am guessing the javascript would need to target the <a> tag if ( is_category( 'videos' ) ) or something?
I wrote this in wp_head hook:
<?php
if ( is_category( 'videos' ) ) { ?>
<script>
(function($){
$(document).ready(function() {
$('a').each(function() {
var a = new RegExp('/' + window.location.host + '/');
if(!a.test(this.href)) {
$(this).click(function(event) {
event.preventDefault();
event.stopPropagation();
window.open(this.href, '_blank');
});
}
});
});
})(jQuery);
</script>
<?php } ?>
Didn't work. I also don't like writing code in there, I think it's unsafe and it's not easy to format.
It's not unsafe, but it's not easy to format, that's for sure.
Try this:
jQuery( document ).ready( function( $ ) {
$( '.category-video h2 a' ).each( function() {
$( this ).attr( 'target', '_blank' );
} );
} );
Let me know :)
Works great, but when I am using the Load More button there seems to be a conflict with the javascript and the code doesn't work anymore on items below where the Load More button was!
Here is the link:
https://www.audiotutorialvideos.com
Ah yea, that'll happen.
Let's try this instead then:
jQuery( document ).ready( function( $ ) {
$( document ).on( 'click', '.category-video h2 a', function( e ) {
e.preventDefault();
var url = $( this ).attr( 'href' );
window.open( url, '_blank' );
});
} );
Yep, works great now, thank you Tom!
You're welcome :)