A load more button that will load more posts - javascript

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.

Related

How to show specific content relating to link clicked on

I am currently working on a site where my client wants a list of icons and when you click on an icon a panel slides in with the information relating to that icon. Here is a link to the section - https://vibrantpropertyservices-u8uj.temp-dns.com/wp/services/#services.
I have the sliding panel working but I can't seem to get the relevant content to show, it just shows the first icon's info. Here is my code:
<?php
$services_query = new WP_Query( array(
'post_type' => 'servicespage',
'posts_per_page' => -1,
'order' => 'ASC',
'orderby' => 'menu_order'
)
);
?>
<?php if ( $services_query->have_posts() ) : ?>
<?php while ( $services_query->have_posts() ) : $services_query->the_post(); ?>
<?php $current_id = get_the_ID(); ?>
<div class="icon" onclick="openNav()" data-src="content-<?php echo $current_id ?>">
<?php if (has_post_thumbnail( $post->ID ) ): ?>
<?php $image = wp_get_attachment_image_src( get_post_thumbnail_id( $post->ID ), 'single-post-thumbnail' ); ?>
<img src="<?php echo $image[0]; ?>">
<?php endif; ?>
<h3><?php the_title(); ?></h3>
</div>
<div id="slide" class="overlay">
×
<div id="content-<?php echo $current_id ?>">
<div class="test">
<h3><?php the_title(); ?></h3>
<?php the_content(); ?>
</div>
</div>
</div>
<?php endwhile; ?>
<?php wp_reset_query(); ?>
<?php endif; ?>
</div>
/* Open when someone clicks on the span element */
function openNav() {
document.getElementById("slide").style.width = "100%";
}
/* Close when someone clicks on the "x" symbol inside the overlay */
function closeNav() {
document.getElementById("slide").style.width = "0%";
}
I know I'm calling the id of "slide" but I don't know how to target <div id="content-<?php echo $current_id ?>"> for each individual link?
Many thanks
remove onclick function for both open
<div class="icon" data-src="content-<?php echo $current_id ?>">
and for close also
×
add below Jquery instead of functions
jQuery(document).on("click",".services-wrap .icon",function(){
jQuery(this).closest('div.overlay').css('width:100%');
});
jQuery(document).on("click",".overlay .closebtn",function(){
jQuery(this).closest('div.overlay').css('width:0%');
});

Wordpress - Show random post with JS, not PHP

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.

How to show all tags from posts before loop?

I have a structure like this in my wordpress search.php:
<div class="tags">
<!-- show all tags from posts in here -->
</div>
<div class="posts">
<!-- Wordpress Query loop here -->
<!-- get_the_tags() for each posts -->
<!-- End loop -->
</div>
I'm able to show inside the loop the list of tags for all the posts. But I need to show them on the div with the class "tags" that is outside the loop.
I know that if I want to show them after the loop is easy, I just have to use a global php variable and show them afterwards. But the only way I think I can add those tags before the loop is inserting them on the HTML DOM with javascript.
Is there any other method to do this more easily?.
Full code as requested:
<?php
global $global_tags;
?>
<div class="col-left">
<div class="tags">
<div class="placeholder-tags"></div>
</div>
</div>
<div class="col-right">
<div class="profile-wrapper">
<?php
$tag = single_tag_title( '', false );
$args = array (
'pagination'=> true,
'posts_per_page' => '8',
'post_type' => 'profile',
'tag_slug__in' =>array($tag)
);
$the_query = new WP_Query( $args ); ?>
<?php if ( $the_query->have_posts() ) : ?>
<!-- pagination here -->
<!-- the loop -->
<?php while ( $the_query->have_posts() ) : $the_query->the_post(); ?>
<div class="profile">
<a href="<?php echo get_permalink(); ?>">
<?php $current_profile = get_field("profile_personal")[0]; ?>
<div class="profile-image">
<img alt="" src="<?php echo $current_profile["profile_image"]['sizes']['thumbnail']; ?>"/><br>
</div>
<div class="profile-name">
<?php echo $current_profile["profile_name"] . ' ' . $current_profile["profile_surname"]; ?>
</div>
<div class="profile-country">
<?php echo $current_profile["profile_country"]; ?><br>
</div>
<?php
$list_tags = get_the_tags();
foreach ( $list_tags as $single_tag) {
$global_tags[] = $single_tag->slug;
}
?>
<?php if ( has_category("bolaber",$post->ID) ) { ?>
<div class="worked-with-us">
●
</div>
<?php } ?>
</a>
</div>
<?php endwhile; ?>
<!-- end of the loop -->
<?php wp_reset_postdata(); ?>
<?php else : ?>
<p><?php _e( 'default Sorry, no posts matched your criteria.' ); ?></p>
<?php endif; ?>
I came up with a not very elegant or efficient solution, but it works perfectly, I added another loop on the tags placeholder with the same query loop parameters, but without showing anything but the tags.
<?php
global $global_tags;
?>
<div class="col-left">
<div class="tags">
<?php
$tag = single_tag_title( '', false );
$args = array (
'pagination'=> true,
'posts_per_page' => '8',
'post_type' => 'profile',
'tag_slug__in' =>array($tag)
);
$the_query = new WP_Query( $args ); ?>
<?php if ( $the_query->have_posts() ) : ?>
<?php while ( $the_query->have_posts() ) : $the_query->the_post(); ?>
<?php
$list_tags = get_the_tags();
foreach ( $list_tags as $single_tag) {
$global_tags[] = $single_tag->slug;
}
?>
<?php endwhile; ?>
<pre>
<?php
if ( $global_tags ) {
$global_tags = array_unique($global_tags);
foreach ($global_tags as $value) {
echo '</br>#'. $value .'';
}
}
?>
</pre>
<?php wp_reset_postdata(); ?>
<?php else : ?>
<?php endif; ?>
</div>
</div>
<div class="col-right">
<div class="profile-wrapper">
<?php
$tag = single_tag_title( '', false );
$args = array (
'pagination'=> true,
'posts_per_page' => '8',
'post_type' => 'profile',
'tag_slug__in' =>array($tag)
);
$the_query = new WP_Query( $args ); ?>
<?php if ( $the_query->have_posts() ) : ?>
<!-- pagination here -->
<!-- the loop -->
<?php while ( $the_query->have_posts() ) : $the_query->the_post(); ?>
<div class="profile">
<a href="<?php echo get_permalink(); ?>">
<?php $current_profile = get_field("profile_personal")[0]; ?>
<div class="profile-image">
<img alt="" src="<?php echo $current_profile["profile_image"]['sizes']['thumbnail']; ?>"/><br>
</div>
<div class="profile-name">
<?php echo $current_profile["profile_name"] . ' ' . $current_profile["profile_surname"]; ?>
</div>
<div class="profile-country">
<?php echo $current_profile["profile_country"]; ?><br>
</div>
<?php
$list_tags = get_the_tags();
foreach ( $list_tags as $single_tag) {
$global_tags[] = $single_tag->slug;
}
?>
<?php if ( has_category("bolaber",$post->ID) ) { ?>
<div class="worked-with-us">
●
</div>
<?php } ?>
</a>
</div>
<?php endwhile; ?>
<!-- end of the loop -->
<?php wp_reset_postdata(); ?>
<?php else : ?>
<p><?php _e( 'default Sorry, no posts matched your criteria.' ); ?></p>
<?php endif; ?>

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.

Loading more posts on WP site using AJAX

I have site on WP. And I'm trying to load posts with AJAX. The difference from other such problems is that I have no pagination, the post section is very simple: two posts near and button below. On click on this button to two posts append previous two posts. I tried to write the solution by myself, but I have little expirience in PHP and maybe in it is the problem.
Post structure:
<div class="row">
<?php if ( have_posts() ) : while ( have_posts() ) : the_post(); ?>
<div class="col-lg-6 col-md-6 col-sm-12 col-xs-12 news-item">
<div class="news-date">
<?php the_time($format = 'j F Y'); ?>
</div>
<div>
<h3><?php the_title(); ?></h3>
<p><?php the_content(); ?></p>
</div>
</div>
<?php endwhile; ?>
<?php endif; ?>
</div>
<div class="more-link">Read more>
</div>
JS
$(function () {
var posts = 2;
var posts_offset = 0;
$("#load-post").click(function (e) {
e.preventDefault();
$.ajax({
type: "POST",
url: "/wp-content/themes/1cka/load-posts.php",
dataType: 'html',
data: {
posts_offset: posts_offset
},
success: function (data) {
$('.news').append(data);
posts_offset += 2;
}
});
})
});
PHP
<?php require_once("header.php"); ?>
<?php
if (isset($_GET['posts_offset']))
{
$posts_offset = $_GET['posts_offset'];
}
global $post;
// записываем $post во временную переменную $tmp_post
$tmp_post = $post;
$args = array( 'posts_per_page' => 2, 'offset'=> $posts_offset );
$myposts = get_posts( $args );
foreach( $myposts as $post ) : setup_postdata($post); ?>
<?php if ( have_posts() ) : while ( have_posts() ) : the_post(); ?>
echo '<div class="col-lg-6 col-md-6 col-sm-12 col-xs-12 news-item">
<div class="news-date">
<?php the_time($format = 'j F Y'); ?>
</div>
<div>
<h3><?php the_title(); ?></h3>
<p><?php the_content(); ?></p>
</div>
</div>'
<?php endwhile; ?>
<?php endif; ?>
<?php endforeach;
$post = $tmp_post;
?>
Sorry I don't have an immediate solution but have you seen https://github.com/WP-API/WP-API ? It implements a rest api for most of your wordpress content, you would be able to fetch any additional posts with a simple ajax call

Categories