I just tested the following example code:
<?php
$the_query = new WP_Query( array(
'posts_per_page' => 12,
'paged' => get_query_var('paged', 1)
));
if ( $the_query->have_posts() ) {
// display #ajax wrapper only if we have posts
echo '<div id="ajax">';
while($the_query->have_posts()) {
$the_query->the_post(); ?>
<article <?php post_class(); ?>>
<div class="row">
<div class="col-md-4"><?php the_post_thumbnail('medium-thumbnail'); ?>
<h2><a class="post-title" href="https://wordpress.stackexchange.com/questions/252035/<?php the_permalink(); ?>"><?php the_title(); ?></a></h2>
<p class="post-excerpt"><?php echo get_the_excerpt(); ?></p>
<?php get_template_part( 'share-buttons' ); ?>
<a class="moretext" href="https://wordpress.stackexchange.com/questions/252035/<?php the_permalink(); ?>">Read more</a>
<?php comments_popup_link ('No Comments', '1 Comment', '% Comments', 'comment-count', 'none'); ?>
</div>
</div>
</article>
<?php }//end while
echo '</div>'; // close the #ajax wrapper after the post list
if(get_query_var('paged') < $the_query->max_num_pages) {
load_more_button();
}
} else { // if there are no posts
echo '<p>Sorry, no posts matched your criteria.</p>';
}//end if
?>
The <div id="ajax">
should wrap around the whole post-list and not every single post, correct? Than this container should be outside the while loop!
Also, when you not specify any post-type in the WP_Query, it defaults to “any” type. So make sure you want this!
‘any’ – retrieves any type except revisions and types with ‘exclude_from_search’ set to true.
In the <article>
tag you should also use <?php post_class(); ?>
instead of class="post"
to get some more and helpful classes automaticly. (including current post-type, status and category)
Update:
I’ve pasted the updated code above in my answer. It works at showing
the posts. However it only showed one post in a row, so I added 2 more
col-md-4. But now it just repeats the same post 3 times. How would I
fix this? Also the ajax button will not appear.
OK so, first … the loop has nothing to do how you will show the posts on the frontend.(in a grid or just below each other) I can see you tried to add 3 <article>
elements in the while
loop.
This is wrong, you just define the template of 1 <article>
here, and all following will use the same.
You use CSS to define how the articles will display on the frontend. So for example use a % width on the article elements to display 3 in a row.
(100% / 3)
Maybe you can also use existing CSS classes. In your code I see <div class="col-md-4">
, so this seems to already be a class of a grid/column system. So maybe look in the docs of the theme which you are using.
If that is already a class to display 3 cols in a row, maybe some CSS is overriding the width.
Yeah, you just need 1 article element, and than style with CSS.