wordpress showing comments from a post retrieved with ajax - ajax

i'm loading a post with ajax.
The code is
$(document).ready(function(){
loadPostsFun = function(){
$.ajax({
url: "http://lab1.koalamedia.es/ajax/",
//url: "/random/",
success: function(response){
$("#randomPost").html( response );
}
});
};
$("#another").click(function(){
loadPostsFun();
return false;
});
});
The response is generated by a custom template with this code:
<?php
query_posts('showposts=1&orderby=rand');
the_post();
$args = array( 'numberposts' => 1, 'orderby' => 'date' );
$rand_posts = get_posts( $args );
?>
<?php
foreach( $rand_posts as $post ) : setup_postdata($post);
?>
<div id="post-<?php the_ID(); ?>" <?php post_class(); ?>>
<?php if ( is_front_page() ) { ?>
<h2 class="entry-title"><?php the_title(); ?></h2>
<?php } else { ?>
<h1 class="entry-title"><?php the_title(); ?></h1>
<?php } ?>
<div class="entry-content">
<?php the_content(); ?>
<?php wp_link_pages( array( 'before' => '<div class="page-link">' . __( 'Pages:', 'twentyten' ), 'after' => '</div>' ) ); ?>
<?php comments_popup_link(__('Comments (0)'), __('Comments (1)'), __('Comments (%)')); ?>
</div><!-- .entry-content -->
</div><!-- #post-## -->
<?php
//comments_template( '', true ); //this doesn't work
comment_form();
//wp_list_comments(''); //this doesn't work
?>
<?php endforeach; ?>
The ajax request works but the comments doesn't show.All the post data is there.
How can i show the comments?
neither comments_template or wp_list_comments work.
You can view a demo or download the template sample i've done here

Without much tweaking wp_list_comments() works in a comments template (usually comments.php) only.
Use get_comments(), pass the post ID as parameter:
$comments = get_comments(array ( 'post_id' => $post->ID );
if ( $comments )
{
foreach ( $comments as $comment )
{
print "<li>$comment->comment_author<br>$comment->comment_content</li>";
}
}

i've found the problem, i forgot to set the global variable:
global $withcomments;
i was using
$withcomments = true;
comments_template();
but without the global it didn't work.
Now works like normal comments do.

Related

How to get Advanced Custom Fields values with Ajax in Wordpress

I'm trying to do a WP_query on a custom-post-type but for some reason I cannot get the values from the custom-field-types of these posts.
Here is what I got so far (functions.php)
function fetch_cases(){
$args = array(
'post_type' => array('case'),
'post_status' => array('publish'),
'posts_per_page' => 5
);
$query = new WP_Query($args);
if($query->have_posts()) {
while($query->have_posts() ){
$query->the_post();
?>
<a href="<?php the_permalink(); ?>">
<div style="background-image:url('<?= get_field('case_picture'); ?>')">
<p><?= get_field('case_title') ?></p>
</div>
</a>
<?php }
}
die();
add_action('wp_ajax_nopriv_fetch_cases', 'fetch_cases');
add_action('wp_ajax_fetch_cases','fetch_cases');
}
And in my JS file have the following:
$.ajax({
url: "/wp-admin/admin-ajax.php",
data: {
action: "fetch_cases"
},
success: function(data) {
$(".fetch_cases").append(data);
},
error: function(errorThrown) {
console.log(errorThrown);
}
});
Can someone tell me what I'm doing wrong?
I also tried to do:
<?php the_field('case_picture'); ?>
but with no luck? what am I missing?
add_action() should be outside your custom function. Try this instead.
function fetch_cases(){
$args = array(
'post_type' => array('case'),
'post_status' => array('publish'),
'posts_per_page' => 5
);
$query = new WP_Query($args);
if($query->have_posts()) {
while($query->have_posts() ){
$query->the_post();
?>
<a href="<?php the_permalink(); ?>">
<div style="background-image:url('<?= get_field('case_picture'); ?>')">
<p><?= get_field('case_title') ?></p>
</div>
</a>
<?php }
}
die();
}
add_action('wp_ajax_nopriv_fetch_cases', 'fetch_cases');
add_action('wp_ajax_fetch_cases','fetch_cases');
you can use this logic by storing the field as a hidden value and pass in ajax through js
$query = new WP_Query($args);
if($query->have_posts()) {
while($query->have_posts() ){
$query->the_post();
?>
<a href="<?php the_permalink(); ?>">
<div style="background-image:url('<?= get_field('case_picture'); ?>')">
<p><?= get_field('case_title') ?></p>
<input type="hidden" id="hidden" name="hidden_field" value="<?= get_field('case_picture'); ?>"> // store the value
</div>
</a>
<?php }
}
die();
Now get the data in jquery and pass through ajax
<script>
var hidden=//Grab data here.
$.ajax({
url: "/wp-admin/admin-ajax.php",
data: {
action: "fetch_cases",
image:hidden, // Pass the data
},
success: function(data) {
$(".fetch_cases").append(data);
},
error: function(errorThrown) {
console.log(errorThrown);
}
});
</script>
and use the data in ajax called
function fetch_cases()
{
$image=$_POST['image'];
}
get_field method has 2nd parameter which is post ID, pass this and check. It should work.
$post_id = $post->ID;
$value = get_field( 'case_picture', $post_id );

WordPress AJAX load posts content in popup div

Using WordPress, I'm trying to load my posts content in a popup div using AJAX, but I can't seem to be able to make it work. I think I'm on the right tracks, but I'm not really a developer, so I need some help!
I want to achieve something like this. So here's my (relevant) code so far:
In my page portfolio.php:
<div id="popUp">
<div class="fermePop">X</div>
<div id="contenuPop"></div>
</div>
...
if ( $query->have_posts() ): ?>
<div class="tagged-posts">
<?php while ( $query->have_posts() ) : $query->the_post(); ?>
<a href="<?php the_permalink(); ?>" <?php post_class( 'tiles' ); ?> rel="<?php the_ID(); ?>">
<?php the_post_thumbnail(); ?>
<h2><?php the_title(); ?></h2>
</a>
<?php endwhile; ?>
</div>
<?php else: ?>
<div class="tagged-posts">
<h2>No posts found</h2>
</div>
<?php endif; ?>
Single.php
<?php
function is_ajax() {
return isset($_SERVER['HTTP_X_REQUESTED_WITH'])
&& strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest';
}
if (is_ajax()) {
get_header();
} ?>
<?php if (have_posts()) :
while (have_posts()) : the_post(); ?>
<div id="single-post post-<?php the_ID(); ?>">
<h2><?php the_title(); ?></h2>
<div class="contenu">
<?php the_content(); ?>
</div>
</div>
<?php endwhile; ?>
<?php endif; ?>
<?php
if (is_ajax()) {
get_footer();
}
?>
function.php
function ajax_load_projets(){
wp_register_script('ajax_load_projets', get_template_directory_uri() . '/js/ajax-load-projets.js', false, null, false);
wp_enqueue_script('ajax_load_projets');
wp_localize_script('ajax_load_projets', 'load_projets_vars', array(
'load_projets_ajaxurl' => admin_url('admin-ajax.php'),
)
);
}
add_action( 'wp_enqueue_scripts', 'ajax_load_projets' );
add_action('wp_ajax_load-single-post', 'prefix_ajax_single_post');
add_action('wp_ajax_nopriv_load-single-post', 'prefix_ajax_single_post');
function prefix_ajax_single_post() {
$pid = (int) filter_input(INPUT_GET, 'pID', FILTSER_SANITIZE_NUMBER_INT);
if ($pid > 0) {
global $post;
$post = get_post($pid);
setup_postdata($post);
printf('<div id="single-post post-%d">', $pid);
the_title();
the_content();
echo '</div>';
}
exit();
}
And finaly, my JQuery script :
jQuery(document).ready(function($) {
$.ajaxSetup({cache:false});
$(".tiles").click(function(event){
if (event.preventDefault) {
event.preventDefault();
} else {
event.returnValue = false;
}
var postID = $(this).attr('rel');
var $container = $("#contenuPop");
$('.filtre').show();
$("#popUp").show();
$container.html("Je charge!");
data={
action: 'prefix_ajax_single_post',
pID: postID,
};
$.post(load_projets_vars.load_projets_ajaxurl, data, function(content) {
$container.html(content);
});
});
function fermePop(){
$('.filtre').hide();
$("#popUp").hide();
}
$(".filtre").click(function(){
fermePop();
});
$(".fermePop").click(function(){
fermePop();
});
});
It's my first time using ajax, so I'm not sure what I'm doing wrong.
Try this.
function prefix_ajax_single_post() {
$pid = $_REQUEST['pID'];
if ($pid > 0) {
global $post;
$post = get_post($pid);
setup_postdata($post);
printf('<div id="single-post post-%d">', $pid);
the_title();
the_content();
echo '</div>';
}
exit();
}
add_action('wp_ajax_prefix_ajax_single_post', 'prefix_ajax_single_post');
add_action('wp_ajax_nopriv_prefix_ajax_single_post', 'prefix_ajax_single_post');
You're not getting the $pid correctly in the prefix_ajax_single_post() function. Since you're posting the data you can do:
$pid = $_POST['pID'];

Ajax error in Wordpress load more?

I have try to load option for my custom page template, Ajax return undefined error After click load more button.
Custom blog page
<?php if (have_posts()) : ?>
<section id="posts">
<?$postslist = get_posts( array(
'posts_per_page' => 2,
'order' => 'ASC'
) );
if ( $postslist ) {
foreach ( $postslist as $post ) :
setup_postdata( $post );
?>
<div style='color:#000'>
<?php echo '<br>'.$post->ID.'->'; the_title(); ?>
</div>
<?php
endforeach;
wp_reset_postdata();
} ?>
</section>
<?php if ( $wp_query->max_num_pages > 1 ) : ?>
<nav class="load_more">
<?php next_posts_link( 'Load More' ); ?>
</nav>
<?php endif; ?>
<?php endif; ?>
<div class="load_more"><a>list</a></div>
Custom js
jQuery('.load_more a').live('click', function(e){
e.preventDefault();
var link = jQuery(this).attr('href');
jQuery('.load_more').html('<span class="loader">Loading More Posts...</span>');
$.get(link, function(data) {
var post = $("#posts .post ", data);
$('#posts').append(post);
});
jQuery('.load_more').load(link+' .load_more a');
});
Ajax Error:
GET http://kannan.test.dev/blog/
200 OK
398ms
jquery....=1.11.1 (line 4)
GET http://kannan.test.dev/blog/undefined
404 Not Found
321ms
jquery....=1.11.1 (line 4)
"NetworkError: 404 Not Found - http://kannan.test.dev/blog/undefined"
You're trying to get the url by accessing the href attribute in your jQuery function, but you're not supplying it, that's why the url has undefined appended at the end.
You need to set your "href" attribute here
<div class="load_more"><a href='...'>list</a></div>
in order for this line of code to work:
var link = jQuery(this).attr('href');

How to paging when load ajax with wp_query?

I have an AJAX function that runs a PHP WP_Query function, and I'm not sure how these results would be outputted dynamically with pagination. The code in function.php
function feature_procject_list() {
// The $_REQUEST contains all the data sent via ajax
if ( isset($_REQUEST) ): ?>
<?php
$post_type = $_REQUEST['post_type'];
$id_cat = $_REQUEST['id_cat'];
$paged = ( get_query_var( 'paged' ) ) ? absint( get_query_var( 'paged' ) ) : 1;
$arr_2 = array(
'posts_per_page'=> 4,
'cat' => $id_cat,
'paged' => $paged,
);
$wp_query = new WP_Query( $arr_2 );
?>
<?php if($wp_query->have_posts()): ?>
<?php while ( $wp_query->have_posts() ) : $wp_query->the_post(); ?>
<div class="single_project">
<a class='img_thumb' href="<?php echo get_permalink();?>"><?php the_post_thumbnail('medium'); ?></a>
<h4><?php the_title(); ?></h4>
<p class="date"><?php the_date('j F \a\t G:i'); ?></p>
<?php the_excerpt(); ?>
</div>
<?php endwhile;
//wp_reset_postdata();
?>
<div id="paging_wrap">
<?php my_pagination(); ?>
<?php //paginate(); ?>
</div><!-- #paging_wrap -->
<?php else: ?>
<h4><?php _e( 'Sorry, no posts matched your criteria.' ); ?></h4>
<?php endif; ?>
<?php endif;die();
}
add_action( 'wp_ajax_feature_procject_list', 'feature_procject_list' );
add_action( 'wp_ajax_nopriv_feature_procject_list', 'feature_procject_list' );
function my_pagination() {
global $wp_query;
$big = 999999999; // need an unlikely integer
echo paginate_links( array(
'base' => str_replace( $big, '%#%', esc_url( get_pagenum_link( $big ) ) ),
'format' => '?paged=%#%',
'current' => max( 1, get_query_var('paged') ),
'total' => $wp_query->max_num_pages
) );
}
And get it on the page template:
function get_list_feature_project(id_category) {
$.ajax({
url: ajaxurl,
data: {
'action':'feature_procject_list',
'id_cat' : id_category
},
beforeSend : function(){
$('#loading').show();
},
success:function(data) {
// This outputs the result of the ajax request
$('#loading').hide();
$('.list_post').html(data);
},
error: function(errorThrown){
console.log(errorThrown);
}
});
}
The post still show but paging not working.

Ajax search and CGridView

I'm trying to implement an ajax search in my CGridView and I'm not having much luck getting it to work.
My Grid:
<?php $this->widget('zii.widgets.grid.CGridView', array(
'id'=>'talent-grid',
'dataProvider'=>$model->searchTalent(),
'hideHeader'=>true,
'template' => '{pager}{items}{pager}',
'pager'=>array('cssFile'=>'/css/pager.css','header' => '',),
'cssFile'=>'/css/client-grid.css',
'columns'=>array(
array(
'name'=>'talent_id',
'type'=>'raw',
'value'=>'$data->getTalentGridRow($data)',
),
),
)); ?>
Search form:
<?php $form=$this->beginWidget('CActiveForm', array(
'action'=>Yii::app()->createUrl($this->route),
'method'=>'get',
)); ?>
<div class="row">
<?php echo $form->label($model,'full_name',array('class'=>'inline')); ?>
<?php echo $form->textField($model,'full_name',array('size'=>60,'maxlength'=>64)); ?>
</div>
<div class="row">
<?php echo $form->label($model,'gender_id',array('class'=>'inline')); ?>
<?php echo $form->checkBoxList($model, 'gender_id',CHtml::listData(Gender::model()->findAll(), 'gender_id', 'name'),array('separator'=>' ')); ?>
<?php echo $form->error($model,'gender_id'); ?>
</div>
<div class="row buttons">
<?php echo CHtml::submitButton('Submit'); ?>
</div>
<?php $this->endWidget(); ?>
The search model:
public function searchTalent() {
$criteria=new CDbCriteria;
$criteria->compare('full_name',$this->full_name,true);
if ($this->gender_id != "") {
$criteria->compare('gender_id',$this->gender_id);
}
return new CActiveDataProvider($this, array(
'criteria'=>$criteria,
'pagination'=>array(
'pageSize'=>30,
),
));
}
The javascript:
Yii::app()->clientScript->registerScript('searchTalent', "
$('#search-form form').submit(function(){
$.fn.yiiGridView.update('talent-list', {
data: $(this).serialize()
});
return false;
});
");
The controller:
public function actionClients() {
$model = new Talent('search');
$model->unsetAttributes(); // clear any default values
if (isset($_GET['Talent'])) {
$model->attributes = $_GET['Talent'];
}
$this->render('clients', array(
'model' => $model,
'pages' => 10
));
}
the js submit fires, but the grid doesn't get updated. Not sure why.
You have specified the id of gridview in js as talent-list but the original id is talent-grid as specified in widget initialization call . So change the line as
Yii::app()->clientScript->registerScript('searchTalent', "
$('#search-form form').submit(function(){
$.fn.yiiGridView.update('talent-grid', {
data: $(this).serialize()
});
return false;
});
");

Resources