So I am using one of them cool new WP templates that come with an editor and all (Enfold, for this project).
I use the built-in enfold (avia layout builder) components to list blog posts in a certain area on my site. These posts only contain a url, so What I want to accomplish is to keep using the built-in components for listing the posts (links) but once a user clicks one of the post titles, they should be taken to the url of the post body instead of a page displaying that url in plain text.
I am using this setup in order for my users to be able to create these posts by the wordpress "publish by emailing" feature, otherwise I could probably have used a link plug-in instead.
Speaking of that, I am so sick of updating one million plugins all the time, so I don't want to bloat my WP install with a plugin for this purpose, and I don't want to pay anyone for writing such a plugin as well. And in my experience WP plugins have been a major security risk as well. So none of that.
My solution was to hijack all the link clicks in my list. I created two arrays containing all my post titles and their corresponding URLs.
I started by adding this script block right before my tag (in header.php):
<script>
//Newsredirecter
news_redirector_title = new Array();
news_redirector_content = new Array();
<?php
global $post;
$tmp_post = $post;
$recent = new WP_Query("cat=34&showposts=3");
while($recent->have_posts()) : $recent->the_post();
echo("
news_redirector_content.push('".get_the_content()."');
news_redirector_title.push('".get_the_title()."');
");
endwhile;
$post = $tmp_post;
?>
The line
$recent = new WP_Query("cat=34&showposts=3");
tells WP to pull out all posts of category 34, and to only pull out 3 of them.
In enfold, you can add an ID for a section, which I did. I called the section containing my blog posts "newsreplacer", and by the code below I hijacked all link clicks within that section and redirected them using the data in my arrays above.
$( document ).ready( function(){
//click event for the edit buttons
$("#newsreplacer").on('click', 'a', function(event) {
url = $(this).attr('href');
current_title = $(this).html();
//console.log('original link to: ' + url);
console.log('clicked link title: '+current_title);
for (i = 0; i < news_redirector_title.length; i++) {
if (news_redirector_title[i] == current_title) {
event.preventDefault();
window.location.href = news_redirector_content[i];
}
}
});
} )
</script>
Worth noting - I also had other normal blog posts listed in this same seciton, and I didn't want them to get hijacked. This is fine, since that last for-loop looks in the array for a title identical to the title of the clicked link.