I'm trying to integrate ajax for the first time in my wordpress theme I am doing. This is my first attempt and I researched on the syntax and how it works. So far, my script is executed properly but there's no response.
The $.get Request
$(document).ready(function(){
$.get('Ajax-nao.php',{cat:12,ponum:5,panum:1},function(data) {
alert('data sent'+ data);
});
});
The Ajax-nao.php
$categoryid = $_GET['cat'];
$postnum = $_GET['ponum'];
$pagenum = $_GET['panum'];
$args = array (
'cat' => $categoryid,
'posts_per_page' => $postnum,
'paged' => $pagenum
);
$q = new WP_Query($args);
while( $q->have_posts()) : $q->the_post();
$post_excerpt = get_the_excerpt();
$wrapper = '<h2 class="column-titles">' . get_the_title() . '</h2>' . '<p>' . $post_excerpt . '</p>';
echo $wrapper;
endwhile;
home.php <-- Where the results will be displayed.
<div id="social-bar">
<div id="other-posts" class="just-float-left">
<div id="other-Posts-container">
</div>
</div>
</div>
Can anyone help me pin-point my error?
WP_Query($args) returns empty set.
At the end of your PHP script change it from:
echo $wrapper;
endwhile
to:
echo $wrapper;
exit();
endwhile
echo "No results found!";
you will gain assurance if there is any data found.
Related
I've stucked while working on my brand new blog template (on wordpress). I've got following query/php code:
echo '<div id="posts-container" class="fusion-blog-layout-medium fusion-blog-infinite fusion-posts-container-infinite fusion-blog-archive fusion-clearfix">';
$args = array( 'post_type' => 'era', 'post_status' => array('publish', 'future'), 'paged' => $paged );
$custom_query = new WP_Query($args);
while($custom_query->have_posts()) : $custom_query->the_post();
$post_classes = $post_class . ' ' . $alignment_class . ' ' . $thumb_class . ' post fusion-clearfix';
ob_start();
post_class( $post_classes );
$post_classes = ob_get_clean();
echo '<article id="post-' . get_the_ID() . '" ' . $post_classes . '>';
get_template_part( 'new-slideshow' );
echo '<div class="fusion-post-content koncert post-content">';
echo ( '<h2 class="entry-title fusion-post-title" data-fontsize="18" data-lineheight="27">' .get_the_title() . '</h2>' );
if ( get_field( "data_i_miejsce_koncertu", get_the_ID() ) ) {
echo ( '<div class="lista-koncert-podtytul">' . get_field( "data_i_miejsce_koncertu", get_the_ID() ) . '</div>' );
}
echo '<div class="fusion-post-content-container">';
do_action( 'avada_blog_post_content' );
if ( get_field( "opis", get_the_ID() ) ) {
echo '<div class="lista-koncert-opis">' . wp_trim_words(get_field( "opis", get_the_ID() ), 60, ' [...]') . '<br><br>Zobacz więcej ></div>';
}
echo '</div>';
echo '</div>'; // End post-content.
echo '</article>';
endwhile;
wp_reset_postdata(); // reset the query
echo '</div>';
What I would like to achieve is to not have regular pagination (I've already removed the controls from my template), but I would like to use jquery infinite scroll script. But being honest - i have no clue how to even start ;/ mainly because there are no that many live examples/tutorials in the internet.. thanks for any tips
You need to invovle javascript to make infinte scrolling work.
Basically what you need to have:
Page that displays first few posts and loads the infinite scrolling javascript function
Hook on wp_ajax to provide next posts data as you call it
After scroll/"click on load more" you call this with javascript and append the loaded posts at the bottom
Repeat this until all posts are loaded
This should give you a good starting point: https://www.billerickson.net/infinite-scroll-in-wordpress/
Also please don't write your HTML in Wordpress themes/plugins with echo. This is far more readable and helps you to keep your indentation right:
?>
<div id="posts-container" class="fusion-blog-layout-medium fusion-blog-infinite fusion-posts-container-infinite fusion-blog-archive fusion-clearfix">
<?php
$args = array( 'post_type' => 'era', 'post_status' => array('publish', 'future'), 'paged' => $paged );
$custom_query = new WP_Query($args);
while($custom_query->have_posts()) : $custom_query->the_post();
$post_classes = $post_class . ' ' . $alignment_class . ' ' . $thumb_class . ' post fusion-clearfix';
ob_start();
post_class( $post_classes );
$post_classes = ob_get_clean();
?>
<article id="post-<?php echo get_the_ID() ?>" <?php echo $post_classes ?>>
...
I tried to load more posts using ajax. I see there is lot of plugins and solutions in online and stackoverflow. But none of work for me. Actually I want to do this without plugin. So I can use this in different page archive or different page template where I need this code.
Here is my code that I got from another question in stackoverflow. My score is lower, so I can't comment out there.
Here is my index.php code:
<?php get_header(); ?>
<div class="ajax-posts">
<?php
$postsPerPage = 3;
$args = array(
'post_type' => 'post',
'posts_per_page' => $postsPerPage,
);
$loop = new WP_Query($args);
while ($loop->have_posts()) : $loop->the_post();
?>
<h2><?php the_title(); ?></h2>
<?php
endwhile;
echo '<a id="more_posts" href="#">Load More</a>';
wp_reset_postdata();
?>
</div>
<script type="text/javascript">
var ajaxUrl = "<?php echo admin_url('admin-ajax.php')?>";
var page = 1;.
var ppp = 3;
$("#more_posts").on("click",function(){
$("#more_posts").attr("disabled",true);
$.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>
<?php get_footer(); ?>
Here is functions.php code
<?php
function more_post_ajax(){
$offset = $_POST["offset"];
$ppp = $_POST["ppp"];
header("Content-Type: text/html");
$args = array(
'post_type' => 'post',
'posts_per_page' => $ppp,
'offset' => $offset,
);
$loop = new WP_Query($args);
while ($loop->have_posts()) { $loop->the_post();
the_title();
}
exit;
}
add_action('wp_ajax_nopriv_more_post_ajax', 'more_post_ajax');
add_action('wp_ajax_more_post_ajax', 'more_post_ajax');
?>
I don't know why posts not load or not work load more link. I hope someone will be help.
Ref: https://stackoverflow.com/a/31588401/5545813
The better way is to return an array with ur post title. Then display them after the success. If the array length < ppp (there is no more post).
$array_return = array();
$loop = new WP_Query($args);
while ($loop->have_posts()) { $loop->the_post();
$content = "<h1>" . get_the_title() . "</h1>";
$content .= "<div>" . get_the_content() . "</div>";
$content .= "<div>" . get_field("your_field") . "</div>";
$array_return[] = $content;
}
echo json_encode( $array_return );
die();
In your js script,
var posts = JSON.parse(posts);
for( var i = 0; i < posts.length; i++ )
$(".ajax-posts").append(posts[i]);
if( posts.length < ur_ppp )
$("#more_posts").fadeOut();
Something like that
I've developed custom theme from scratch with _S starter theme. I'm having issue getting Wordpress next posts via ajax request on click on read more button. I've tried many articles specifically the following articles, but no luck.
Reference Links:
Load More Posts Ajax Button in Wordpress
Load Next WordPress Posts With AJAX
Load Old WordPress Posts on the Same Page with AJAX
I've tried going with above custom loops and adding custom functions with jquery script but it don't work somehow.
Here is loop code example below:
Loop in index.php
<?php query_posts('showposts=5'); if (have_posts()) : while (have_posts()) : the_post(); ?>
<article class="post-item">
<h2><?php the_title(); ?></h2>
<?php the_excerpt(); ?>
</article>
<?php endwhile; ?>
<?php else : ?>
<h2>Sorry no posts are created yet.</h2>
<p>Please create some posts to see it in action.</p>
<?php endif; wp_reset_query(); ?>
<button class="load-more-btn">Load More</button>
I'm messing with this issue for over 4-5 days, so any one can help me out with this issue with working solution will be highly appreciable.
Thanks in advance.
I maybe have a solution for your.
First be sure to have a script enqueue in your theme
wp_enqueue_script('your_js_hanlde', get_template_directory_uri() . '/js/your_js_hanlde.js', array('jquery'), '1.0.0', true );
then localize add a function to add a js var in your dom
wp_localize_script('your_js_hanlde', 'ajaxurl', admin_url( 'admin-ajax.php' ) );
In your js, add an event on 'click' on your 'Load More' button
Pass an action name and the count of article you have in your dom, the response add the content before your button 'load more'
$("#load_more").click(function()
{
$.post(ajaxurl,
{
'action': 'your_load_more',
'count': $("article.post-item").length
},
function(response)
{
var posts = JSON.parse(response);
for( var i = 0; i < posts.length; i++ )
{
if( posts[i] == "0" )
$("#load_more").fadeOut();
else
$("#load_more").before(posts[i]);
}
});
});
create a function in your functions.php
function your_load_more()
{
$count = $_POST["count"];
$cpt = 1;
$args = array(
'posts_per_page' => -1,
'post_type' => 'post', // change the post type if you use a custom post type
'post_status' => 'publish',
);
$articles = new WP_Query( $args );
$ar_posts = array();
if( $articles->have_posts() )
{
while( $articles->have_posts() )
{
$articles->the_post();
$one_post = "";
if( $cpt > $count && $cpt < $count+6 )
{
$one_post .= "<article id='" . get_the_id() . "' class='post-item'>";
$one_post .= "<h3>" . get_the_title() . "</h3>";
$one_post .= "</article>";
$ar_posts[] = $one_post;
if( $cpt == $articles->found_posts )
$ar_posts[] = "0";
}
$cpt++;
}
}
echo json_encode($ar_posts);
die();
}
add_action( 'wp_ajax_your_load_more', 'your_load_more' );
add_action( 'wp_ajax_nopriv_your_load_more', 'your_load_more' );
It work for me.
I hope that help you.
I have a custom wordpress function that shows the number of featured recipes. The function works fine when showposts=-1 is in the query. However when I put 'showposts=5' only two of my posts are shown.
Below is my function
function pika_featured_recipes_shortcode() {
ob_start();
echo '<div class="featured-box-heading"> Featured Recipes </div>';
echo '<div class="featured-box">';
$temp = $wp_query;
$wp_query = null;
$wp_query = new WP_Query();
$wp_query->query('showposts=5&post_type=cp_recipe&order=Desc&orderby=date' . '&paged=' . $paged);
while ($wp_query->have_posts()):
$wp_query->the_post();
$entry_id = get_the_ID();
$entry_link = get_permalink($entry_id);
$entry_image = get_post_thumbnail_id($entry_id);
$entry_title = get_the_title($entry_id);
$entry_description = get_post_meta($entry_id, '_cp_recipe_short_description', true);
$entry_excerpt = get_post_meta($entry_id, '_cp_recipe_excerpt', true);
$likes = get_post_meta( $entry_id, '_cp_likes', true );
if (get_field('featured-pika-recipe') == 'Yes') {
echo '<div class="featured-result-box item ">
<div class="box">
<div class="pika-featured-box-img">';
if(!empty($entry_image)) {
echo ''.wp_get_attachment_image($entry_image, 'cp_298_192').'';
}
echo' </div><!-- /.box-img -->';
echo'<div class="box-entry">
<h5 class="pika-featured-title"><a href="';
echo $entry_link;
echo '">';
echo $entry_title;
echo'</a></h5>';
echo $trimmed = wp_trim_words( $entry_description, $num_words = 15, $more = null );
echo'</div><!-- /.box-entry -->';
echo'</div>';
echo'</div>';
echo'<div style="clear:both"></div>';
}
endwhile;
wp_reset_query();
echo '</div>';
$output = ob_get_clean();
return $output;}
add_shortcode( 'pika_featured-recipes', 'pika_featured_recipes_shortcode' );
The problem seems to be with
if (get_field('featured-pika-recipe') == 'Yes') {
removing this and the number of posts appear fine. Any way i can resolve this?
maybe because only 2 posts ( of the last 5 posts that you actually call ) got
get_field('featured-pika-recipe') == 'Yes'
you can try to add this custom field directly to your query to get last 5 posts with this custom field with following code
'meta_key' => 'featured-pika-recipe',
'meta_value' => 'Yes'
I have a external php file that queries the WP database for posts. I use the WP_Query class to customize my queries. It runs fine if I'm within the template files, but it won't when I add a new php file.
I would like to include the functions that WP uses to my file.
Ajax-nao.php
$categoryid = $_GET['cat'];
$postnum = $_GET['ponum'];
$pagenum = $_GET['panum'];
$args = array (
'cat' => $categoryid,
'posts_per_page' => $postnum,
'paged' => $pagenum
);
$q = new WP_Query($args);
while( $q->have_posts()) : $q->the_post();
$post_excerpt = get_the_excerpt();
$wrapper = '<h2 class="column-titles">' . get_the_title() . '</h2>' . '<p>' . $post_excerpt . '</p>';
echo $wrapper;
exit();
endwhile;
echo "No results found!";
When I run it I get this error
Fatal error: Class 'WP_Query' not found in I:\xampp\htdocs\dmp\wp-content\themes\dmp-v3\Ajax-nao.php on line 11
Also, is there a way to for $.get() to load the my php in my theme folder and not in the root directory?
Thanks.
From some research, try adding this to the top of your PHP file and change PATHHERE to the actual path:
// Include WordPress
define('WP_USE_THEMES', false);
require_once('PATHHERE/wp-blog-header.php');
For reference:
I want to run wp_query on a separate php file for an ajax call
wordpress loop with jquery .load()
There's a couple of ways to do this. One is to simply create a template file without any header or footer:
<?php
/**
* Template Name: AJAX NAO
*/
$categoryid = $_GET['cat'];
$postnum = $_GET['ponum'];
$pagenum = $_GET['panum'];
$args = array (
'cat' => $categoryid,
'posts_per_page' => $postnum,
'paged' => $pagenum
);
$q = new WP_Query($args);
while( $q->have_posts()) : $q->the_post();
$post_excerpt = get_the_excerpt();
$wrapper = '<h2 class="column-titles">' . get_the_title() . '</h2>' . '<p>' . $post_excerpt . '</p>';
echo $wrapper;
exit();
endwhile;
echo "No results found!";
Then you can use that template for a new page in your WP admin. In your jQuery, call the full URL of that page.
The harder but preferred way is to create a plugin. You'd need something like:
<?php
/*
Plugin Name: My AJAX NAO
Description: Returns NAO
Version: 1.0
Author: You
Author URI: http://yoursite.com
*/
//
function nao_callback() {
$categoryid = $_POST['cat'];
$postnum = $_POST['ponum'];
$pagenum = $_POST['panum'];
$args = array (
'cat' => $categoryid,
'posts_per_page' => $postnum,
'paged' => $pagenum
);
$q = new WP_Query($args);
while( $q->have_posts()) : $q->the_post();
$post_excerpt = get_the_excerpt();
$wrapper = '<h2 class="column-titles">' . get_the_title() . '</h2>' . '<p>' . $post_excerpt . '</p>';
echo $wrapper;
exit();
endwhile;
echo "No results found!";
}
add_action('wp_ajax_nao', 'nao_callback');
add_action('wp_ajax_nopriv_nao', 'nao_callback');
And then in your jquery:
jQuery.ajax({
url: '/wp-admin/admin-ajax.php',
method: 'POST',
dataType: 'html',
data: {
action: 'nao',
cat: '1',
ponum: '2',
panum: '3'
},
success: function(data) {
$('.js-element').html(data);
}
});
Assuming js-element is the class name of the container you want to add the result to.