1

I'm trying to implement an Ajax request to load more posts on click.

However I've got an error : Call to undefined function query_posts()

Here is my Ajax script :

$('#next-container').click(function() { 
    var IDs = [];
    $(".element").each(function(){ IDs.push(this.id); });

    $('#next-container').html('loading');

    $.ajax({
        url: 'wp-content/themes/freakyshape/inc/data.php',
        type: 'POST',
        data: {'post_ids[]': IDs },
        success: function(data) {
            $container.isotope( 'insert', $(data));
        }
    });
});

my data.php file to load post:

<?php
if (isset($_POST['post_ids'])) {

$ids = array(); 
$ids[] = $_POST['post_ids'];

$posts_per_page = 8;

global $wp_query;
query_posts(array('post_type' => array('post', 'portfolio'), 'post__not_in' => $ids, 'posts_per_page' => $posts_per_page));
while (have_posts()) : the_post();  
?>

// I do some stuff echo;

<?php
endwhile;
wp_reset_query();
}
?>

and in my functions.php:

$admin_path = TEMPLATEPATH . "/inc/";
require_once ($admin_path . "data.php");

What do I need to make it work?

EDIT:

I try with the right way to do it but nothing works like this... I miss something... It's not easy to correctly understand blog instruction when you are not fluent in English...

function.php:

add_action('wp_ajax_load_post', 'load_post_callback');
add_action('wp_ajax_nopriv_load_post', 'load_post_callback');
wp_enqueue_script('script', get_template_directory_uri().'/js/load_post.js', array('jquery'), '1.0', 1 );
wp_localize_script('script', 'ajax_var', array('url' => admin_url('admin-ajax.php'), 'nonce' => wp_create_nonce('ajax-nonce')));

load_post.php :

<?php

function load_post_callback() {

if (isset($_POST['post_ids'])) {

    $nonce = $_POST['nonce'];

    if ( ! wp_verify_nonce( $nonce, 'ajax-nonce' ) ) {
        die ( 'Interdit !');
    }

    $ids = array(); 
    $ids[] = $_POST['post_ids'];

    $posts_per_page = 8;
    global $wp_query;
    query_posts(array('post_type' => array('post', 'portfolio'), 'post__not_in' => $ids, 'posts_per_page' => $posts_per_page));
    while (have_posts()) : the_post();

    $post_type = get_post_type( $post->ID );
    if ($post_type == 'post') {
        $post_type = 'blog';
    }
?>

<div class="element normal <?php echo $post_type; ?>" id="<?php echo the_id(); ?>">
    <div class="element-container">
        <img  src="<?php echo  wp_get_attachment_url( get_post_thumbnail_id()); ?>" class="thumbnail" />
        <div class="element-back"></div>
        <div class="element-description"><?php echo the_title(); ?></div>
        <div class="element-category"><i class="icon"></i>&nbsp;&nbsp <?php echo $post_type; ?></div>
        <a class="link" href="" title="<?php echo the_title(); ?>" onclick="gestionClic(compteur'id');">
            <div class="more">more.</div>
        </a>
    </div>
</div>  

<?php
    endwhile;
    wp_reset_query();
    }
}
?>

load_post.js:

jQuery(document).ready(function() { 

    var url = ajax_var.url;
    var nonce = ajax_var.nonce;

    jQuery('#next-container').click(function() { 

            var IDs = [];
            $(".element").each(function(){ IDs.push(this.id); });
            console.log(IDs);

            $('#next-container').html('loading');

            $.ajax({
                url: 'wp-content/themes/freakyshape/inc/load_post.php',
                type: 'POST',
                data: {'post_ids[]': IDs },//'post_ids='+IDs,

                success: function($data) {  
                    $container.isotope( 'insert', $data);

                }
            })
    })
})
freaky
  • 990
  • 3
  • 17
  • 44
  • I'd suggest looking into the [WP-endorsed way to use AJAX](http://codex.wordpress.org/AJAX_in_Plugins) - I'm betting you're missing some basic WP core includes by not going this route. – jterry Jul 08 '13 at 14:26
  • Your data.php is a php file of its own. It has nothing of wordpress's data included. – Suthan Bala Jul 08 '13 at 14:26
  • Thank you, but how can I include my custom php file to wordpress core in order to make it works wordpress function? I miss something in the wordpress documentation... – freaky Jul 08 '13 at 14:28
  • Use WP's own admin ajax php file and use that to reference a function in your theme's functions.php file rather than including an external php file. Otherwise you have to load WP core in your data.php. – Ennui Jul 08 '13 at 14:36
  • [One example](http://wordpress.stackexchange.com/a/54875/12615) on how to make Ajax the WordPress way. Also, [**don't use `query_posts`**](http://wordpress.stackexchange.com/q/1753/12615). – brasofilo Jul 08 '13 at 14:37
  • thank you for the anwser. It's seems more complicated than I expected... Why they add more difficulties in wordpress than in the "normal" way to code an html template. For security? – freaky Jul 08 '13 at 14:42
  • Ok with including `wp-load.php` it seems to works (but I ve got syntax error...). If I correctly understand, I can't use wp-load.php include?? – freaky Jul 08 '13 at 15:11
  • Your EDIT is invalid. You should ask new Questions after you solve one. The code changed, the logic changed, there's no point trying to do a follow up here, a Q&A site doesn't work like this. – brasofilo Jul 10 '13 at 17:05
  • This question wasn't solve. Finally the problem was because I forget to add `` in the footer and because of `wp_localize_script` – freaky Jul 10 '13 at 17:13

1 Answers1

1

Using Ajax this way is not correct. For your code to work, you need to include wp-load.php and use some other workarounds. The web is full of this awful examples.

Otto, core contributor, explains the main reasons why we Don’t include wp-load, please.. And these are:

Why this is wrong

  1. You don’t have the first clue where wp-load.php actually is. Both the plugin directory and the wp-content directory can be moved around in the installation. ALL the WordPress files could be moved about in this manner, are you going to search around for them?
  2. You’ve instantly doubled the load on that server. WordPress and the PHP processing of it all now have to get loaded twice for every page load. Once to produce the page, and then again to produce your generated javascript.
  3. You’re generating javascript on the fly. That’s simply crap for caching and speed and such.

The proper way is:

  • using wp_ajax_ hooks to run PHP code and return it to the JS file.
  • using wp_localize_script to pass PHP variables to the JS file.

One working example of mine at WordPress Answers. And lots of good examples from one of our mods and leading contributor to the Ajax tag.

Community
  • 1
  • 1
brasofilo
  • 25,496
  • 15
  • 91
  • 179
  • There's a dedicated blog to Crappy Code ™, with this great post: [wp-load.php – I Will Find You!](http://crappycode.wordpress.com/2012/12/13/wp-load-php-i-will-find-you/) that tackles Otto's bullet point 1. – brasofilo Jul 08 '13 at 15:52
  • Ok. Thank you. I will learn that. By the way with in my code I've got a problem with `$container.isotope( 'insert', $(data));`. `has no method 'filter'` . In my html template it works great like this but not in wordpress.... – freaky Jul 08 '13 at 16:03
  • That's a topic for another common mistake: [*enqueuing jQuery the proper way*](http://stackoverflow.com/a/17506100/1287812) ;) – brasofilo Jul 08 '13 at 16:07
  • thank you. I'm lost with all this new requirements. My very simple ajax script become very hard to make it works in wordpress... I have 600 lines of custom script for pushstate and hashbang fallback that use `.load()`; do I will have this kind of problem also? – freaky Jul 08 '13 at 16:24
  • If you want it to work inside WP, it has to be the WP way, otherwise you'll flood [se] and [wordpress.se] with Q's trying to solve this kind of Ajax and jQuery errors. – brasofilo Jul 08 '13 at 16:36
  • I understand that but if I clearly understand, I need to split my single custom script file, for each function inside it that modify my website in several files. It will slow down the execution by the way that wordpress processes. Anyway I will learn to do it of course. Thank you for your help! – freaky Jul 08 '13 at 16:41
  • I find where is the problem. I don't have the variable in source code in the head with `wp_localize_script`. I write all the code in the right way but can get the variable from php. I don't know where it comes from... – freaky Jul 10 '13 at 12:38