I am trying to include a Wordpress posts loop in my AJAX refresh query, it should refresh every 10 seconds and pull the latest post from the Wordpress loop.
The query is working fine with plain HTML and returning the correct code and refreshing every 10 seconds as per jQuery below. However, when I add in the following code into test.php it returns no data.
<?php
query_posts( array ( 'category_name' => 'top-story', 'posts_per_page' => 1 ) );
while (have_posts()) : the_post(); ?>
<h1><b><?php the_title(); ?></b></h1>
<?php the_post_thumbnail('full', array('height' => '450px', 'class' => 'img-responsive')); ?>
<h2 class="main-subtitle"><?php the_field('job-title'); ?><h2>
<?php
endwhile; wp_reset_query();
?>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.3/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
sendRequest();
function sendRequest(){
$.ajax({
url: "/wp-content/themes/website.co.uk/test.php",
success:
function(data){
$('#autodata').html(data); //insert text of test.php into your div
},
complete: function() {
// Schedule the next request when the current one's complete
setInterval(sendRequest, 10000); // The interval set to 5 seconds
}
});
};
});
</script>
Related
I want to make a bundle creator in Wordpress using Woocommerce, where you select 1 of 4 T-shirts + 1 of 4 pairs of socks and they get added to the cart. Currently I am stuck on figuring out how to approach this. What I currently need to achieve is this:
There is a top image which corresponds to the currently selected product and three smaller images below that. Once you click the small image, it needs to change the top image. There is also a title on the bottom, which corresponds to the currently selected product, that changes together with the top image. You can see the intended result here.
I need to somehow get the ID of the product the user clicks on and pass it to other php functions. This is where I got stuck. Can anybody help me out?
The code should look something like this:
<div id="selected-product-image">
<?php get_the_post_thumbnail(/* ID of the currently selected product*/); ?>
</div>
<ul class="products">
<?php
$args = array( 'post_type' => 'product', 'posts_per_page' => 4, 'product_cat' => 't-shirts', 'orderby' => 'name' );
$loop = new WP_Query( $args );
?>
<?php while ( $loop->have_posts() ) : $loop->the_post(); global $product; ?>
<li class="product">
<div class="select-product"><!--This should have a function to capture the product ID on click. -->
<?php echo get_the_post_thumbnail($loop->post->ID, 'shop_catalog'); ?>
</div>
</li>
<?php endwhile; ?>
<div id="selected-product-name">
<?php get_the_title(/* ID of the currently selected product*/) ?>;
</div>
<?php wp_reset_query(); ?>
</ul>
I understand that I can do something like this using AJAX, but I am not sure how to use the returned ID back in get_the_post_thumbnail() or get_the_title(). This is what I got:
<script type="text/javascript">
jQuery(document).ready(function() {
jQuery("#select-product").click(function() {
var id = 29; /* Any value for testing */
jQuery.ajax({
method: "post",
url: "/test.php",
data: {
productID: id
}
})
.done(function(data) {
alert(data);
/* How do I use this data to update the picture/title? */
});
});
});
</script>
<!-- THE test.php FILE -->
<?php
$productID = $_POST['productID'];
echo $productID;
?>
UPDATE:
I have tried editing the test.php to echo a function, but I am getting a 500 error every time I try using a Wordpress function inside the test.php file. I tried including the wp-blog-header.php file so the functions can run, but it still doesn't help. What am I doing wrong?
<!-- THE test.php FILE -->
<?php
include_once('wp-blog-header.php');
$productID = $_POST['productID'];
echo get_the_post_thumbnail($productID);
?>
I have custom post types displaying on a static front page, initially showing 8 posts, where I have now created a load more button using an example of jQuery and AJAX that I found online that will show 4 more posts when the button is clicked. I am wondering how I can add 4 to the offset each time so it keeps moving through the next posts. As it is now every time I click the load more button it shows the same 4 over again. My code in my front-page.php:
<script>
var now=2; // when click start in page 2
jQuery(document).on('click', '#load_more_btn', function () {
jQuery.ajax({
type: "POST",
url: "<?php echo get_site_url(); ?>/wp-admin/admin-ajax.php",
data: {
action: 'my_load_more_function', // the name of the function in functions.php
paged: now, // set the page to get the ajax request
posts_per_page: 4, //number of post to get (use 1 for testing)
},
success: function (data) {
if(data!=0){
jQuery("#ajax").append(data); // put the content into ajax container
now=now+1; // add 1 to next page
}else{
jQuery("#load_more_btn").html("<h4>No more
results</h4>");
}
},
error: function (errorThrown) {
alert(errorThrown); // only for debuggin
}
});
});
and the code in my functions.php file:
add_action('wp_ajax_my_load_more_function', 'my_load_more_function');
add_action('wp_ajax_nopriv_my_load_more_function',
'my_load_more_function');
function my_load_more_function() {
$offset = 8;
$page = (get_query_var('page')) ? get_query_var('page') : 1;
$query = new WP_Query( [
'posts_per_page' => $_POST["posts_per_page"],
'order'=>'ASC',
'offset'=> $offset,
'post_type' => 'videos',
'page' => get_query_var('page', $_POST["paged"])
] );
if ($query->have_posts()) {
$offset = (($page - 1) * 8) - $offset;
$query->set( 'offset', $offset );
while ($query->have_posts()) {
$query->the_post();
$img1 = get_field('video_thumbnail'); ?>
<div class="col-6 col-sm-3 box no-gutters" style="background-
image: url('<?php echo $img1['url']; ?>')"><a href="<?php
the_field('video_link'); ?>" data-lity><div class="overlay"><span
class="title"><?php the_field('name'); ?></span></div></a></div>
<?php
}
wp_reset_query();
}else{
return 0;
}
exit;
}
I'm wondering how I can get offset to be +4 each time the query is run after the initial time where it is set at 8. I'm fairly new to thsi type of thing and can not seem to get it working properly.
Im making a blog list page, with Load More... and I have a problem. After click/load my whole content duplicates, but only the first page, doesnt duplicates, only the next pages.
If Im open a PHP file, where's my content generated, it shows only the current page what I need to load, for example only second page
There's the whole code
<?php
$paginationClass = 'otw_portfolio_manager-load-more-newspapper';
$paginationLoadMore = 'otw_portfolio_manager-load-more-newspapper';
$uniqueHash = wp_create_nonce("otw_pm_get_posts_nonce");
$listID = $this->listOptions['id'];
$maxPages = $otw_pm_posts->max_num_pages;
$paginationPageNo = (int) $_GET['page'];
//echo $paginationPageNo;
($paginationPageNo == 0) ? $page = 2 : $page = $paginationPageNo + 1;
$ajaxURL = admin_url( 'admin-ajax.php?action=get_pm_posts&post_id='. $listID .'&nonce='. $uniqueHash .'&page='. $page );
?>
<script>
$(document).ready(function(){
$(document).on('click','.show_more',function(){
var ID = $(this).attr('id');
$('.show_more').hide();
$('.loding').show();
$.ajax({
type:'POST',
url:'<?php echo $ajaxURL;?>',
data:'id='+ID,
success:function(html){
$('#show_more_main-'+ID).remove();
$(".row.works").append(html);
}
});
});
});
</script>
<!-- Load More Pagination -->
<div class="js-pagination_container">
<div class="<?php echo $paginationClass;?> hide">
<?php echo $page;?>
</div>
<div id="show_more_main-<?php echo $page;?>" class="<?php echo $paginationLoadMore;?> js-otw_portfolio_manager-load-more">
<?php _e('Load More', OTW_PML_TRANSLATION);?>
</div>
</div>
<?php?>
<!-- End Load More Pagination -->
</div>
Console report after 3 clicks on last "Load More"
13:36:29.502 jquery.min.js:4 XHR finished loading: GET ".../wp-admin/admin-ajax.php?action=get_pm_posts&post_id=1&nonce=7452b3a7e4&page=2".
13:36:31.842 jquery.min.js:4 XHR finished loading: POST ".../wp-admin/admin-ajax.php?action=get_pm_posts&post_id=1&nonce=7452b3a7e4&page=2".
13:36:31.905 jquery.min.js:4 XHR finished loading: GET ".../wp-admin/admin-ajax.php?action=get_pm_posts&post_id=1&nonce=7452b3a7e4&page=3".
13:36:31.936 jquery.min.js:4 XHR finished loading: POST ".../wp-admin/admin-ajax.php?action=get_pm_posts&post_id=1&nonce=7452b3a7e4&page=3".
13:36:36.333 jquery.min.js:4 XHR finished loading: GET ".../wp-admin/admin-ajax.php?action=get_pm_posts&post_id=1&nonce=7452b3a7e4&page=4".
13:36:36.380 jquery.min.js:4 XHR finished loading: POST ".../wp-admin/admin-ajax.php?action=get_pm_posts&post_id=1&nonce=7452b3a7e4&page=2".
13:36:36.585 jquery.min.js:4 XHR finished loading: POST ".../wp-admin/admin-ajax.php?action=get_pm_posts&post_id=1&nonce=7452b3a7e4&page=3".
13:36:36.929 jquery.min.js:4 XHR finished loading: POST ".../wp-admin/admin-ajax.php?action=get_pm_posts&post_id=1&nonce=7452b3a7e4&page=4".
13:36:36.982 jquery.min.js:4 XHR finished loading: POST ".../wp-admin/admin-ajax.php?action=get_pm_posts&post_id=1&nonce=7452b3a7e4&page=3".
I make this function in wordpress
Now I update and move my jquery away from php and now I see how much times it duplicates, and how it works
This is my template
<div class="row works">
<?php foreach( $otw_pm_posts->posts as $post ){
echo $this->buildInterfacePortfolioItems( $post ); ?>
<?php echo $this->getSocial( $post ); ?>
<?php echo $this->getDelimiter( $post ); ?>
<?php }?>
<?php
$paginationClass = 'otw_portfolio_manager-load-more-newspapper';
$paginationLoadMore = 'otw_portfolio_manager-load-more-newspapper';
$uniqueHash = wp_create_nonce("otw_pm_get_posts_nonce");
$listID = $this->listOptions['id'];
$maxPages = $otw_pm_posts->max_num_pages;
$paginationPageNo = (int) $_GET['page'];
//echo $paginationPageNo;
($paginationPageNo == 0) ? $page = 2 : $page = $paginationPageNo + 1;
$ajaxURL = admin_url( 'admin-ajax.php?action=get_pm_posts&post_id='. $listID .'&nonce='. $uniqueHash .'&page='. $page );
?>
<script>
$(document).ready(function(){
loadMore();
});
</script>
<!-- Load More Pagination -->
<div class="js-pagination_container">
<div class="<?php echo $paginationClass;?> hide">
<?php echo $page;?>
</div>
<div class="<?php echo $paginationLoadMore;?> js-otw_portfolio_manager-load-more">
<?php _e('Load More', OTW_PML_TRANSLATION);?>
</div>
</div>
<?php?>
<!-- End Load More Pagination -->
</div>
And this is my jQuery now
function loadMore(){
$(document).on('click','.show_more', 'a' ,function(e){
var post = $(this).attr('href');
$('.show_more').hide();
$('.loding').show();
$.ajax({
type:'POST',
url:post,
success:function(html){
$(html).insertAfter(".row.works");
}
});
e.stopPropagation();
});
}
And how its duplicates
1. click - shows second page
2. click - 3 times duplicate third page
3. click - n times duplicate fourth page and content with second and third page content
I am trying to update an included PHP file and get the refreshed results and variables from that file. The file getmssg.php is included in the foreach loop because I need in that file a row value. The variable $ergebnis1 I get from the file getmssg.php.
How can I call/refresh the query values of the included PHP file without reloading the page?
<?php
include("chatmain.php");
?>
<?php foreach ($result2 as $key => $row): ?>
<?php include("getmssg.php"); ?>
<li data-icon="false" name="listi5" class="listitem5">
<a type="button" class="ui-btn" id=5">
<?php if ($ergebnis1 > 0) {
echo '<span class="ui-li-count">'.$ergebnis1.'</span>';
} ?>
</a>
</li>
<?php endforeach; ?>
What I have now:
function getmsg() {
$.ajax({
url: 'getmssg.php',
type: 'post',
success: function(output) {
//alert(output);
}
});
}
var timer;
function docount() {
timer = setInterval(function(){
getmsg();
}, 3000);
}
docount();
Try to put the php forEach inside a php function and call that function in the success callback of the ajax .It will update the contents without pageload
I've had a look through the old questions and tried many of the different methods that there seems to be to do this. The closest I've got to working is this one here: How to implement pagination on a custom WP_Query Ajax
I've tried everything and it just doesn't work. Absolutely nothing changes on the page. If you inspect the Load More Button and click it, the jQuery is making the Load More Button action as it changes from <a id="more_posts">Load More</a> to <a id="more_posts" disables="disabled">Load More</a> which even that doesn6't seem right to me anyway. It's not adding the posts, I think I'm missing something simple but for the life of me I can't work it out.
The code in my template file is:
<div id="ajax-posts" class="row">
<?php
$postsPerPage = 3;
$args = [
'post_type' => 'post',
'posts_per_page' => $postsPerPage,
'cat' => 1
];
$loop = new WP_Query($args);
while ($loop->have_posts()) : $loop->the_post(); ?>
<div class="small-12 large-4 columns">
<h1><?php the_title(); ?></h1>
<p><?php the_content(); ?></p>
</div>
<?php
endwhile;
echo '<a id="more_posts">Load More</a>';
wp_reset_postdata();
?>
</div>
The code in my functions file is:
function more_post_ajax(){
$offset = $_POST["offset"];
$ppp = $_POST["ppp"];
header("Content-Type: text/html");
$args = [
'suppress_filters' => true,
'post_type' => 'post',
'posts_per_page' => $ppp,
'cat' => 1,
'offset' => $offset,
];
$loop = new WP_Query($args);
while ($loop->have_posts()) { $loop->the_post();
the_content();
}
exit;
}
add_action('wp_ajax_nopriv_more_post_ajax', 'more_post_ajax');
add_action('wp_ajax_more_post_ajax', 'more_post_ajax');
And my jQuery in the footer is:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>
<script type="text/javascript">
jQuery(document).ready( function($) {
var ajaxUrl = "<?php echo admin_url('admin-ajax.php')?>";
// What page we are on.
var page = 5;
// Post per page
var ppp = 3;
$("#more_posts").on("click", function() {
// When btn is pressed.
$("#more_posts").attr("disabled",true);
// Disable the button, temp.
$.post(ajaxUrl, {
action: "more_post_ajax",
offset: (page * ppp) + 1,
ppp: ppp
})
.success(function(posts) {
page++;
$("#ajax-posts").append(posts);
// CHANGE THIS!
$("#more_posts").attr("disabled", false);
});
});
});
</script>
Can anybody see something I'm missing or able to help?
UPDATE 24.04.2016.
I've created tutorial on my page https://madebydenis.com/ajax-load-posts-on-wordpress/ about implementing this on Twenty Sixteen theme, so feel free to check it out :)
EDIT
I've tested this on Twenty Fifteen and it's working, so it should be working for you.
In index.php (assuming that you want to show the posts on the main page, but this should work even if you put it in a page template) I put:
<div id="ajax-posts" class="row">
<?php
$postsPerPage = 3;
$args = array(
'post_type' => 'post',
'posts_per_page' => $postsPerPage,
'cat' => 8
);
$loop = new WP_Query($args);
while ($loop->have_posts()) : $loop->the_post();
?>
<div class="small-12 large-4 columns">
<h1><?php the_title(); ?></h1>
<p><?php the_content(); ?></p>
</div>
<?php
endwhile;
wp_reset_postdata();
?>
</div>
<div id="more_posts">Load More</div>
This will output 3 posts from category 8 (I had posts in that category, so I used it, you can use whatever you want to). You can even query the category you're in with
$cat_id = get_query_var('cat');
This will give you the category id to use in your query. You could put this in your loader (load more div), and pull with jQuery like
<div id="more_posts" data-category="<?php echo $cat_id; ?>">Load More</div>
And pull the category with
var cat = $('#more_posts').data('category');
But for now, you can leave this out.
Next in functions.php I added
wp_localize_script( 'twentyfifteen-script', 'ajax_posts', array(
'ajaxurl' => admin_url( 'admin-ajax.php' ),
'noposts' => __('No older posts found', 'twentyfifteen'),
));
Right after the existing wp_localize_script. This will load WordPress own admin-ajax.php so that we can use it when we call it in our ajax call.
At the end of the functions.php file I added the function that will load your posts:
function more_post_ajax(){
$ppp = (isset($_POST["ppp"])) ? $_POST["ppp"] : 3;
$page = (isset($_POST['pageNumber'])) ? $_POST['pageNumber'] : 0;
header("Content-Type: text/html");
$args = array(
'suppress_filters' => true,
'post_type' => 'post',
'posts_per_page' => $ppp,
'cat' => 8,
'paged' => $page,
);
$loop = new WP_Query($args);
$out = '';
if ($loop -> have_posts()) : while ($loop -> have_posts()) : $loop -> the_post();
$out .= '<div class="small-12 large-4 columns">
<h1>'.get_the_title().'</h1>
<p>'.get_the_content().'</p>
</div>';
endwhile;
endif;
wp_reset_postdata();
die($out);
}
add_action('wp_ajax_nopriv_more_post_ajax', 'more_post_ajax');
add_action('wp_ajax_more_post_ajax', 'more_post_ajax');
Here I've added paged key in the array, so that the loop can keep track on what page you are when you load your posts.
If you've added your category in the loader, you'd add:
$cat = (isset($_POST['cat'])) ? $_POST['cat'] : '';
And instead of 8, you'd put $cat. This will be in the $_POST array, and you'll be able to use it in ajax.
Last part is the ajax itself. In functions.js I put inside the $(document).ready(); enviroment
var ppp = 3; // Post per page
var cat = 8;
var pageNumber = 1;
function load_posts(){
pageNumber++;
var str = '&cat=' + cat + '&pageNumber=' + pageNumber + '&ppp=' + ppp + '&action=more_post_ajax';
$.ajax({
type: "POST",
dataType: "html",
url: ajax_posts.ajaxurl,
data: str,
success: function(data){
var $data = $(data);
if($data.length){
$("#ajax-posts").append($data);
$("#more_posts").attr("disabled",false);
} else{
$("#more_posts").attr("disabled",true);
}
},
error : function(jqXHR, textStatus, errorThrown) {
$loader.html(jqXHR + " :: " + textStatus + " :: " + errorThrown);
}
});
return false;
}
$("#more_posts").on("click",function(){ // When btn is pressed.
$("#more_posts").attr("disabled",true); // Disable the button, temp.
load_posts();
});
Saved it, tested it, and it works :)
Images as proof (don't mind the shoddy styling, it was done quickly). Also post content is gibberish xD
UPDATE
For 'infinite load' instead on click event on the button (just make it invisible, with visibility: hidden;) you can try with
$(window).on('scroll', function () {
if ($(window).scrollTop() + $(window).height() >= $(document).height() - 100) {
load_posts();
}
});
This should run the load_posts() function when you're 100px from the bottom of the page. In the case of the tutorial on my site you can add a check to see if the posts are loading (to prevent firing of the ajax twice), and you can fire it when the scroll reaches the top of the footer
$(window).on('scroll', function(){
if($('body').scrollTop()+$(window).height() > $('footer').offset().top){
if(!($loader.hasClass('post_loading_loader') || $loader.hasClass('post_no_more_posts'))){
load_posts();
}
}
});
Now the only drawback in these cases is that you could never scroll to the value of $(document).height() - 100 or $('footer').offset().top for some reason. If that should happen, just increase the number where the scroll goes to.
You can easily check it by putting console.logs in your code and see in the inspector what they throw out
$(window).on('scroll', function () {
console.log($(window).scrollTop() + $(window).height());
console.log($(document).height() - 100);
if ($(window).scrollTop() + $(window).height() >= $(document).height() - 100) {
load_posts();
}
});
And just adjust accordingly ;)
Hope this helps :) If you have any questions just ask.
If I'm not using any category then how can I use this code? Actually, I want to use this code for custom post type.