Wordpress - Show random post with JS, not PHP - javascript

I have this page containing recent posts at the bottom. I have set it to randomly show me three posts from the same category as the current post. Heres the loop:
<!-- Related Posts =========================================== -->
<div class="relared-posts-heading">
<h2>SIMILAR INSIGHTS</h2>
</div>
<div class="container blog-card-container">
<div class="card-columns">
<?php
// the query
$the_query = new WP_Query( array(
'orderby' => 'rand',
'cat' => '-14',
'posts_per_page' => 3,
));
?>
<?php if ( $the_query->have_posts() ) : ?>
<?php while ( $the_query->have_posts() ) : $the_query->the_post(); ?>
<!-- Conditional a Link =========================================== -->
<?php
if(get_field('quote') == ''){
$yourTag = "<a href='".get_the_permalink()."'>" ;
} else {
$yourTag = "";
}
?>
<div> <?php echo $yourTag; ?> </div>
<div class="card">
<a href="<?php the_permalink(); ?>">
<div class="blog-thumb-container-2">
<?php if ( has_post_thumbnail() ) { the_post_thumbnail(); } ?>
</div>
</a>
<div class="blog-meta-container-2">
<p class="blog-cat-label"><?php the_category(', '); ?></p>
<h2 class="blog-card-title"><?php the_title(); ?></h2>
<p class="card-text"><?php the_excerpt(__('(moreā€¦)')); ?></p>
<p><strong><?php the_author(); ?></strong> | <?php echo get_the_date(); ?> </p>
</div>
</div>
</a>
<?php endwhile; ?>
<?php wp_reset_postdata(); ?>
<?php else : ?>
<p><?php __('No News'); ?></p>
<?php endif; ?>
</div>
</div>
This works fine currently.
The trouble is, when finished, the site will be behind a clients custom cache and he tells me that PHP randomisers wont work as it will just show the cached version. He suggested I do any randomising using Javascript!
So firstly - is this possible? Secondly, How would I go about targeting this is javascript!? Thanks for looking!!

Unfortunately you won't be able to randomize a post in this way for the caching reason.
What you can do instead is use an Ajax call to dynamically fetch and insert a random post...
$.get('/wp-content/themes/SomeTheme/random.php?v=' + Math.floor(Date.now() / 1000))
.done(function(resp) {
$('.random-post').html(resp);
})
.fail(function(xhr) {
// handle error (xhr object contains the response)
});
And then create a separate random.php file in your theme and put the code to randomly return a single post in there. Note, that you don't need to put the whole layout around the post (don't include header.php etc). That's because this exact HTML fragment will be sent to the frontend and inserted dynamically.
The ?v= parameter is required for cache busting so that it fetches a new post each time.

Try wrapping the entire funtionality as a shortcode.

Related

How to create a seperate popup form for each wordpress post on-click

I have listed my data through a custom-post-type plugin having some custom fields. Below code will display the custom-post-type listing data.
<?php
$args = array(
'post_type' => 'inde_case',
'posts_per_page' => -1
);
query_posts($args);
?>
<ul class="case_study_section1 col-md-12 nopadding">
<?php while ( have_posts() ) : the_post(); ?>
<?php $terms = get_the_terms( get_the_ID(), 'inde_case_category');
if( !empty($terms) ) {
$term = array_pop($terms);
}
?>
<li data-category="<?php echo $term->slug; ?>" class="case_study_img col-md-3 col-sm-6">
<div class="caseSection">
<div class="imagediv"><?php the_post_thumbnail(); ?></div>
<div style="width:100%;float:left;">
<a class="case_study_pdf" href="<?php the_field('linkicon'); ?>" >PDF</a>
<a class="case_study_title" href="<?php the_field('linktext'); ?>" ><?php the_title(); ?></a>
</div>
</div>
</li>
<?php endwhile; ?>
I have properly listed my data having thumbnail and pdf link...etc.
I am trying to create a popup by popup-maker plugin, it has created a class to open a popup. And when I put that class in above code (refer below), in this case only one popup will apply for each post.
<a class="popmake-6981 case_study_pdf" href="<?php the_field('linkicon'); ?>" >PDF</a>
When somebody click on pdf link how can I open a separate popup for each particular post?
Or can I open a specific popup-form using postId or some unique data?
Please Advice.
You can create popups with their [popup] shortcodes, like described here.
Match ID and a trigger class.
<?php while ( have_posts() ) : the_post();?>
<article>
<h2><a class="popmake-post-<?php the_ID();?>" href="<?php the_permalink();?>"><?php the_title();?></a></h2>
<?php echo do_shortcode("[popup id='post-". get_the_ID() ."' size='small' title='". get_the_title() ."']". get_the_content() . "[/popup]");?>
</article>
<?php endwhile; ?>
Beware that you may also need some popup on that page in targeting settings, otherwise they may not initialize.

A load more button that will load more posts

I've been trying to add a load more button to my front page for a few months now. For my front page I have a query that shows my latest posts, 15 per page. I want a simple load more button that will start after the first 15 posts and appears after every 15 posts. I would think this is pretty simple to do, but I just can not figure out for the life of me how to set it up. If anyone could help I would be extremely appreciative.
front-page.php
<?php
/*
* Template Name:
*/
get_header();
get_template_part ('inc/carousel');
$the_query = new WP_Query( [
'posts_per_page' => 15,
'paged' => get_query_var('paged', 1)
] );
if ( $the_query->have_posts() ) { ?>
<div id="ajax">
<?php
$i = 0;
$j = 0;
while ( $the_query->have_posts() ) { $the_query->the_post();
if ( $i % 5 === 0 ) { // Large post: on the first iteration and every 7th post after... ?>
<div class="row">
<article <?php post_class( 'col-sm-12 col-md-12' ); ?>>
<div class="large-front-container">
<?php the_post_thumbnail('full', array('class' => 'large-front-thumbnail')); ?>
</div>
<div class="front-page-date"><?php echo str_replace('mins', 'minutes', human_time_diff( get_the_time('U'), current_time('timestamp') ) . ' ago'); ?></div>
<h2><a class="front-page-post-title" href="<?php the_permalink(); ?>"><?php the_title(); ?></a></h2>
<p class="front-page-post-excerpt"><?php echo get_the_excerpt(); ?></p>
<div class="front-page-post-info">
<a class="moretext" href="<?php the_permalink(); ?>">Read more</a>
<?php get_template_part( 'front-shop-the-post' ); ?>
<?php get_template_part( 'share-buttons' ); ?>
<div class="front-comments"><?php comments_popup_link ('0', '1', '%', 'comment-count', 'none'); ?></div>
</div>
</article>
</div>
<?php
} else { // Small posts ?>
<?php if($j % 2 === 0) echo '<div class="row">'; ?>
<article <?php post_class( 'col-sm-6 col-md-6' ); ?>>
<?php the_post_thumbnail('full', array('class' => 'medium-front-thumbnail')); ?>
<div class="front-page-date"><?php echo human_time_diff( get_the_time('U'), current_time('timestamp') ) . ' ago'; ?></div>
<h2><a class="front-page-post-title" href="<?php the_permalink(); ?>"><?php the_title(); ?></a></h2>
<p class="front-page-post-excerpt"><?php echo get_the_excerpt(); ?></p>
<div class="front-page-post-info">
<a class="moretext" href="<?php the_permalink(); ?>">Read more</a>
<?php get_template_part( 'front-shop-the-post' ); ?>
<?php get_template_part( 'share-buttons' ); ?>
<div class="front-comments"><?php comments_popup_link ('0', '1', '%', 'comment-count', 'none'); ?></div>
</div>
</article>
<?php $j++; if($j % 2 === 0) echo '</div>'; ?>
<?php
}
$i++;
}?>
</div>
<?php if(get_query_var('paged') < $the_query->max_num_pages) { ?>
<?php
}
}
elseif (!get_query_var('paged') || get_query_var('paged') == '1') {
echo '<p>Sorry, no posts matched your criteria.</p>';
}
get_footer();
I'm not going to go into a huge amount of depth but you're going to need a button something like this at the bottom of your post
<div id="load-more">Load More< /div>
You'll then need some javascript / jQuery to watch for when that button is pressed
$('#load-more').on('click', function() {
console.debug("Load More button pressed");
});
From there you're going to need to make a little php script to get the next 15 posts. You will then need to call this from the javascript. I don't write WP code very often but it might look a little something like this
$lastPostId = $_GET['lastid']; // this will need to be passed from the javascript at a later point.
$posts = [];
$the_query = new WP_Query([
'posts_per_page' => 15,
'paged' => get_query_var('paged', $lastPostId)
]);
if ( $the_query->have_posts() ) {
while ( $the_query->have_posts() ) {
$the_query->the_post();
$posts[] = ""// See comment bellow
}
}
$response = ["posts" => $posts];
echo json_encode($response);
From here you'll need to figure out how you want to pass your post's data back to the javascript. You have 2 options here. You can render the html view inside of the response or parse the data into a json like format and return that back to your javascript.
From here we're going to need to handle the response from your php script.
Note: it's up to you to figure out how you're going to handle getting the last id part. Logically you can just add a data-id to each post container and then use jquery to get the last-child's data-id
$('#load-more').on('click', function() {
var lastId = 15;
// Now we make the query and handle it
$.get("myabovephpscript.php", {lastid: lastId}, function( data ) {
// for this example I'm going to to assume you've prebuilt the
// html so we're going to append it to the page.
for( let i = 0; i < data.posts.length; i ++ ) {
$( '#postsContainer' ).append( data.posts[i].postData );
}
});
});
and we're done. All you have to do is fill in the blanks and tidy it all up. Small disclaimer. I've not tested this at all. I've just written these types of systems to many times.

Execute javascript for a particular get request in php

Suppose my domain name is www.example.com and I have a category, which contains many items. Example, Travel, Books, Education. Now, if I click on Travel the get request is www.example.com/category/travel-areas. Now, I want to execute a script when particularly that Travel is clicked from category, like <script>alert("hi")</script> it will be executed when I open www.example.com/category/travel-areas
This is my category.php file :-
<div class="content">
<?php tie_breadcrumbs() ?>
<?php
$category_id = get_query_var('cat') ;
$tie_cats_options = get_option( 'tie_cats_options' );
if( !empty( $tie_cats_options[ $category_id ] ) )
$cat_options = $tie_cats_options[ $category_id ];
?>
<div class="page-head">
<h1 class="page-title">
<?php echo single_cat_title( '', false ) ?>
</h1>
<?php if( tie_get_option( 'category_rss' ) ): ?>
<a class="rss-cat-icon ttip" title="<?php _eti( 'Feed Subscription' ); ?>" href="<?php echo get_category_feed_link($category_id) ?>"><i class="fa fa-rss"></i></a>
<?php endif; ?>
<div class="stripe-line"></div>
<?php
if( tie_get_option( 'category_desc' ) ):
$category_description = category_description();
if ( ! empty( $category_description ) )
echo '<div class="clear"></div><div class="archive-meta">' . $category_description . '</div>';
endif;
?>
</div>
<?php get_template_part( 'framework/parts/slider-category' ); ?>
<?php $loop_layout = ( !empty( $cat_options[ 'category_layout' ] ) ? $cat_options[ 'category_layout' ] : tie_get_option( 'category_layout' ) ); ?>
<?php get_template_part( 'loop' ); ?>
<?php if ($wp_query->max_num_pages > 1) tie_pagenavi(); ?>
</div> <!-- .content -->
In your code there is no part, where exactly link is displayed. But i can suggest that you have list of links to different areas. For example :
Area title
So i added some example to Jsfiddle. As you can see, some part of JS code will be executed only when be passed if expression. You can change that expression, so add some additional check.

Adding a second custom field

I have a custom field 'ExtraCSS' which brings in custom post css using the following code. (It is brought in from a 'have_posts()' loop)
html
<?php $extraCSS = get_post_meta(get_the_ID(),'ExtraCSS',true);?><!-- get specific css for post -->
<article>
<div id="post-<?php the_ID(); ?>" class="img-cell" style="background-image:url('<?php echo $thumbnail_url ?>');" <?php post_class('col-md-12'); ?> >
<a class="linkage" href="<?php the_permalink(); ?>"</a>
</div><!-- /#post -->
<div class="text-cell">
<div class="<?php echo $extraCSS?>" >
<h1><?php the_title(); ?></h1>
<h3><?php the_category(', '); ?></h3>
</div>
</div>
</article>
*EDIT
I want to add 1 more custom field ('BG-align') with either values 'BG-align-L' or 'BG-align-R'. I figured I just add another similar line of code under the current one.
ex.
<?php $extraCSS = get_post_meta(get_the_ID(),'ExtraCSS',true);?>
<?php $BGalign = get_post_meta(get_the_ID(),'BGalign',true);?>
but it doesn't work
According to *edit:
'BGalign' have to be defined in post (by "Add New Custom Field"), otherwise it is just empty.
You could set default value (edit "default-value") if not set in post:
<?php
$BGalign = get_post_meta(get_the_ID(),'BGalign',true);
$BGalign = ( !empty($BGalign) ? $BGalign : "default-value" );
?>
Then remember to echo that new php variable. For example:
<div class="<?php echo $extraCSS . " " . $BGalign; ?>" >
. is dot joining variables into one string
" " is empty space for sure that your both classes names will not be connected

Inserting Javascript (Adsense) between a grid loop of posts?

My site, dadgab.com (Wordpress) has a 2 column loop with 4 rows.
Header
X X
X X
X X
Footer
I would like to insert adsense javascript into the spot where the 3rd post would be (middle left). After running in circles all week trying to implement this, hoping someone on here can help me.
Here is my loop in index.php:
<?php while ( have_posts() ) : the_post(); ?>
<article id="post-<?php the_ID(); ?>" <?php post_class('box'); ?>>
<div class="post-image">
<?php
$thumb = get_post_thumbnail_id();
$img_url = wp_get_attachment_url( $thumb,'full' ); //get full URL to image (use "large" or "medium" if the images too big)
$image = aq_resize( $img_url, 300, 150, true ); //resize & crop the image
?>
<?php if($image) : ?>
<img width="300" height="150" src="<?php echo $image ?>" alt="<?php the_title() ?>" />
<?php endif; ?>
</div>
I have tried adding various methods including adding the following text to functions.php and adding a blank post, tagged with 'adsense'. This just yields an empty box, though if I actually click on the post the ad will display.
add_filter('the_content', 'replace_adsense_posts_excerpt');
function replace_adsense_posts_excerpt($excerpt)
{
$post = get_post(get_the_ID());
if (has_tag('adsense ', $post)) {
// Replace the content with our adsense code
$excerpt = my_adsense_code();
}
return $excerpt;
}
function my_adsense_code()
{
$adsense = 'ADSENSE CODE';
return $adsense;
}
Simply add a counter to your loop and output the code if the counter equals 3:
<?php $i=0; while ( have_posts() ) : the_post(); $i++;?>
<?php if($i==3):?>
<div <?php post_class('box'); ?>>ADSENSE CODE</div>
<?php endif;?>
<article id="post-<?php the_ID(); ?>" <?php post_class('box'); ?>>
....
You will need to use css to maker sure adsense is the same dimensions as the articles

Categories