Loading more posts on WP site using AJAX - javascript

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

Related

Show post description outside while loop

I've a list of team members (custom post type) that I'm calling using WP_Query class. This part is working, however I'm trying to show the description (the_content()) of a team member outside the while loop when clicked on their name. This container (#team-info) is outside the while loop as you can see in the code. Page would ideally scroll to the description container after clicking on the name.
<div class="container">
<div class="row">
<div class="col-md-12">
<div id="team-info"></div>
</div>
</div>
<div class="container mt-15">
<div class="row">
<div class="col-md-12">
<?php
// The Query
$the_query = new WP_Query( array (
'post_type' => 'my_team_sp',
) );
if( $the_query->have_posts() ): $i = 0;
while ( $the_query->have_posts() ) : $the_query->the_post(); $i++; ?>
<div class="col-md-4 <?php echo $i ;?>">
<h4><?php the_title() ;?></h4>
</div>
<?php endwhile;
else :
endif;
/* Restore original Post Data */
wp_reset_postdata();
?>
</div>
</div>
You can Try this with jQuery. See the below Code.
<div class="container mt-15">
<div class="row">
<div class="col-md-12">
<?php
// The Query
$the_query = new WP_Query( array (
'post_type' => 'my_team_sp',
) );
if( $the_query->have_posts() ): $i = 0;
while ( $the_query->have_posts() ) : $the_query->the_post(); $i++; ?>
<div class="col-md-4 <?php echo $i ;?>">
<h4><?php the_title() ;?></h4>
<div style="display: none;"><?php the_content(); ?></div>
</div>
<?php endwhile;
else :
endif;
/* Restore original Post Data */
wp_reset_postdata();
?>
</div>
</div>
jQuery
Add this code in your Js file.
jQuery(document).ready(function($){
$( '.team-name' ).on('click', function(){
var teamInfo = $(this).next().html();
$( '#team-info' ).html( teamInfo );
});
});

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.

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; ?>

Problems with a wordpress project

Im new to StackOverflow, I need help with a wordpress project, I have created a post type for projects and I am displaying the projects with a function in the projects page, I need that when a user clicks on a project that projects appears in a modal or lightbox window, the problem is that I try to pass the value using get but the web refreshes and the modal dissapears, anybody could help me please???
This is the function:
/*funcion para mostrar los proyectos en la pagina de proyectos <-- jochi 17/07/2016 */
function showProyects(){
echo '<div class="row">';
$loop = new WP_Query( array( 'post_type' => 'proyectos', 'paged' => $paged, 'posts_per_page'=> 15 ) );
if ( $loop->have_posts() ) :
while ( $loop->have_posts() ) : $loop->the_post(); ?>
<?php $do_not_duplicate = $post->ID; ?>
<div class="pindex col-xs-12 col-md-4">
<h2><?php echo get_the_title(); ?></h2>
<?php if ( has_post_thumbnail() ) { ?>
<?php $proID = get_the_ID(); ?>
<a href="?projectID=<?php echo $proID;?>" rel="lightbox">
<div class="pimage opnpop">
<?php the_post_thumbnail(); ?>
</div>
</a>
<?php } ?>
<div class="pcontent">
<?php
the_content();
?>
</div>
<div class="btnproyect"><a class="opnpop" href="?projectID=<?php echo $proID;?>">Leer Más »</a></div>
</div>
<?php endwhile;
endif;
wp_reset_postdata();
echo '</div>';
}
add_shortcode('show_proyects', 'showProyects');
I created a shortcode to use the function in the projects page.

Show posts and image in same div

I have featured images shown for different posts of same category in a page in a specific div. I need to show the whole post related to this image in the same page in another div. I know i must use JavaScript in this. But i need some reference which i can use for this. Can anyone help me with this? I am using the following code to show the images
<?php
/*
Template Name: Meet The Team Template
*/
?>
<?php get_header(); ?>
<div id = "meet_posts" class = "narrowcolumn">
<?php
$recent = new WP_Query("cat=6&orderby=title&order=ASC");
while( $recent->have_posts() ) : $recent->the_post();
$desc_values = get_post_custom_values("description");
?>
<div id="meetteam_featured_image">
<a href="<?php the_permalink() ?>" rel="title">
<?php
if ( has_post_thumbnail() ) {
the_post_thumbnail();
}
?>
</a>
</div>
<?php endwhile; ?>
</div>
<?php get_footer(); ?>
Thanks in advance.
Replace your above code with this following code :
<?php /*
Template Name: Meet The Team Template
*/
?>
<?php get_header(); ?>
<div id="meet_posts" class="narrowcolumn">
<?php
$recent = new WP_Query("cat=6&orderby=title&order=ASC");
while($recent->have_posts()):$recent->the_post();
$desc_values = get_post_custom_values("description");
?>
<div id="meetteam_featured_image" class="<?php the_ID(); ?>">
<a href="<?php the_permalink() ?>" rel="title">
<?php
if ( has_post_thumbnail() ) {
the_post_thumbnail();
}
?>
</a>
</div>
<?php endwhile ?>
<div id="image-post-info"></div>
</div>
<?php get_footer(); ?>
Add this following code in functions.php file :
add_action( 'wp_ajax_ajaxified_function', 'ajaxified_function' );
add_action( 'wp_ajax_nopriv_ajaxified_function', 'ajaxified_function' );
function ajaxified_function() {
$temp = get_post($_POST['post_id']);
echo $temp->post_title.'<br/><br/>'.$temp->post_content;
die();
}
Add this following code in your custom js file :
jQuery(document).ready(function (){
jQuery('#meetteam_featured_image a').on('click',function(event){
event.preventDefault();
var post_id = jQuery(this).parent().attr('class');
jQuery.ajax({
type: "POST",
url: 'http://www.yoursitename.com/wp-admin/admin-ajax.php',
data: 'action=ajaxified_function&post_id='+post_id,
success: function (msg) {
jQuery('#image-post-info').html(msg);
},
error: function () {
alert('Error');
}
});
});
});
Add custom js file by including following code in functions.php file :
function add_custom_scripts() {
wp_enqueue_script( 'custom-scripts', get_stylesheet_directory_uri() .'/js/custom- scripts.js' );
}
add_action( 'wp_enqueue_scripts', 'add_custom_scripts' );
Hope this will help....!!!!!
<div id = "meet_posts" class = "narrowcolumn">
<?php
$recent = new WP_Query("cat=6&orderby=title&order=ASC");
while( $recent->have_posts() ) : $recent->the_post();
$desc_values = get_post_custom_values("description");
?>
</div><!--close first div-->
<div id="meetteam_featured_image">
<a href="<?php the_permalink() ?>" rel="title">
<?php
if ( has_post_thumbnail() ) {
the_post_thumbnail();
}
?>
</a>
</div><!--close second div-->
<?php endwhile; ?>

Categories