1

I have an Ajax call for loading more posts on button click. The Ajax is generating a new WP_Query according to some arguments it gets from a form, then send the posts it gets back to the page.

It's working well on my home page and one of the taxonomy archives. I thought I've built it correctly in a way it would work anywhere, but apparently something is not going quite right on author.php. The code it not very thin ,I know, sorry.

JS:

$('.more-items-form.in-list').submit(ajaxMoreItems_list);

function ajaxMoreItems_list(e){

    e.preventDefault(); //prevent form normal submission

    var form = this; //the form
    ajaxUrl = $('input[name=ajax]',form).val(); //ajax url
    template = $('input[name=template]',form).val(); //template url
    tax = $('input[name=tax]',form).val(); //posts taxonomy
    term = $('input[name=term]',form).val(); //posts term
    author = $('input[name=author]',form).val(); //posts author
    ot = $('.more-items',form).text(); //original button text
    articles = $('.post-listing article').length; //number of loaded articles 

    /* start the ajax call */
    $.post(ajaxUrl, {
        template: template,
        action:'bayadaim_ajax_fetch_posts',
        offset: articles,
        ppp: 6,
        tax: tax,
        term: term,
        author: author,
        beforeSend : function(){
            $('.more-items',form).text('טוען...'); //change button text
            $('.more-items').prop('disabled',true); // Disable all more-items buttons to avoid mess, temp.
        }
    }).success(function(posts){
        $(posts).hide().appendTo('.post-listing').fadeIn(200); //print the items
        $('.more-items').not('fin').removeAttr('disabled'); //re-enable all more-items buttons

        if(!$.trim(posts)){
            $('.more-items',form).text('הסוף');
            $('.more-items',form).addClass('fin');
            $('.more-items',form).prop('disabled',true);
        }else{
            $('.more-items',form).text(ot); //reset the button text
            $('.more-items',form).removeAttr('disabled'); //re-enable all more-items buttons
        }

    }).error(function(){
        alert("שגיאה בטעינת נתונים, בבקשה נסו שנית.");
    }).complete(function(){

    });

PHP:

    /** fetch more POSTS with ajax **/
    function bayadaim_ajax_fetch_posts(){
        $template = $_POST['template'];
        $offset = $_POST["offset"];
        $ppp = $_POST["ppp"];
        $tax = $_POST["tax"];
        $term = $_POST["term"];
        $meta = $_POST["meta"];
        $author = $_POST["author"];
        $orderby = $_POST["orderby"];
        $order = $_POST["order"];
        $post_type = (!empty($_POST["post_type"]) ? $_POST["post_type"] : "post");
        header("Content-Type: text/html");

        $args = array(
            'meta_key' => $meta,
            'orderby' => $orderby,
            'order' => $order, 
            'posts_per_page' => $ppp,
            'tax_query' => array(
                array(
                    'taxonomy' => $tax,
                    'field'    => 'slug',
                    'terms'    => $term,
                ),
            ),
            'author' => $author,
            'offset' => $offset,
            'post_status' => 'publish',
            'post_type' => $post_type
        );

        $loop = new WP_Query($args);

        if ($loop->have_posts()) :
            while ($loop->have_posts()) : $loop->the_post();
                if ( $template = "row" ) {
                    include( locate_template( 'content-post_in_row.php', false, false ) ); //by using include(locate_template()) combination i keep child-theme functionality while still passing variables to included file.
                }else{
                    include( locate_template( 'content-post_in_listing.php', false, false ) ); //by using include(locate_template()) combination i keep child-theme functionality while still passing variables to included file.               
                }
            endwhile;
        else :
            if ( !empty($loop) ) console($loop); //for debugging
        endif;

        exit; 
    }

    add_action('wp_ajax_nopriv_bayadaim_ajax_fetch_posts', 'bayadaim_ajax_fetch_posts'); 
    add_action('wp_ajax_bayadaim_ajax_fetch_posts', 'bayadaim_ajax_fetch_posts');

WP_Query array returned:

    WP_Query Object
(
    [query] => Array
        (
            [meta_key] => 
            [orderby] => 
            [order] => 
            [posts_per_page] => 6
            [tax_query] => Array
                (
                    [0] => Array
                        (
                            [taxonomy] => 
                            [field] => slug
                            [terms] => 
                        )

                )

            [author] => 228
            [offset] => 6
            [post_status] => publish
            [post_type] => post
        )

    [query_vars] => Array
        (
            [meta_key] => 
            [orderby] => 
            [order] => DESC
            [posts_per_page] => 6
            [tax_query] => Array
                (
                    [0] => Array
                        (
                            [taxonomy] => 
                            [field] => slug
                            [terms] => 
                        )

                )

            [author] => 228
            [offset] => 6
            [post_status] => publish
            [post_type] => post
            [error] => 
            [m] => 
            [p] => 0
            [post_parent] => 
            [subpost] => 
            [subpost_id] => 
            [attachment] => 
            [attachment_id] => 0
            [name] => 
            [static] => 
            [pagename] => 
            [page_id] => 0
            [second] => 
            [minute] => 
            [hour] => 
            [day] => 0
            [monthnum] => 0
            [year] => 0
            [w] => 0
            [category_name] => 
            [tag] => 
            [cat] => 
            [tag_id] => 
            [author_name] => 
            [feed] => 
            [tb] => 
            [paged] => 0
            [meta_value] => 
            [preview] => 
            [s] => 
            [sentence] => 
            [title] => 
            [fields] => 
            [menu_order] => 
            [embed] => 
            [category__in] => Array
                (
                )

            [category__not_in] => Array
                (
                )

            [category__and] => Array
                (
                )

            [post__in] => Array
                (
                )

            [post__not_in] => Array
                (
                )

            [post_name__in] => Array
                (
                )

            [tag__in] => Array
                (
                )

            [tag__not_in] => Array
                (
                )

            [tag__and] => Array
                (
                )

            [tag_slug__in] => Array
                (
                )

            [tag_slug__and] => Array
                (
                )

            [post_parent__in] => Array
                (
                )

            [post_parent__not_in] => Array
                (
                )

            [author__in] => Array
                (
                    [0] => 228
                )

            [author__not_in] => Array
                (
                )

            [ignore_sticky_posts] => 
            [suppress_filters] => 
            [cache_results] => 1
            [update_post_term_cache] => 1
            [lazy_load_term_meta] => 1
            [update_post_meta_cache] => 1
            [nopaging] => 
            [comments_per_page] => 5
            [no_found_rows] => 
        )

    [tax_query] => WP_Tax_Query Object
        (
            [queries] => Array
                (
                    [0] => Array
                        (
                            [taxonomy] => 
                            [terms] => Array
                                (
                                )

                            [field] => slug
                            [operator] => IN
                            [include_children] => 1
                        )

                )

            [relation] => AND
            [table_aliases:protected] => Array
                (
                )

            [queried_terms] => Array
                (
                )

            [primary_table] => dq3q092o_posts
            [primary_id_column] => ID
        )

    [meta_query] => WP_Meta_Query Object
        (
            [queries] => Array
                (
                )

            [relation] => 
            [meta_table] => 
            [meta_id_column] => 
            [primary_table] => 
            [primary_id_column] => 
            [table_aliases:protected] => Array
                (
                )

            [clauses:protected] => Array
                (
                )

            [has_or_relation:protected] => 
        )

    [date_query] => 
    [request] => SELECT SQL_CALC_FOUND_ROWS  dq3q092o_posts.ID FROM dq3q092o_posts  LEFT JOIN dq3q092o_term_relationships AS tr1 ON (dq3q092o_posts.ID = tr1.object_id) LEFT JOIN dq3q092o_term_taxonomy ON ( tr1.term_taxonomy_id = dq3q092o_term_taxonomy.term_taxonomy_id ) WHERE 1=1  AND ( 
  0 = 1
) AND ( dq3q092o_posts.post_author IN (228)  AND dq3q092o_posts.post_type = 'post' AND ((dq3q092o OR (dq3q092o_term_taxonomy.taxonomy = 'author' AND dq3q092o_term_taxonomy.term_id = '18'))_posts.post_status = 'publish')) GROUP BY dq3q092o_posts.ID HAVING MAX( IF ( dq3q092o_term_taxonomy.taxonomy = 'author', IF (  dq3q092o_term_taxonomy.term_id = '18',2,1 ),0 ) ) <> 1  ORDER BY dq3q092o_posts.post_date DESC LIMIT 6, 6
    [posts] => Array
        (
        )

    [post_count] => 0
    [current_post] => -1
    [in_the_loop] => 
    [comment_count] => 0
    [current_comment] => -1
    [found_posts] => 0
    [max_num_pages] => 0
    [max_num_comment_pages] => 0
    [is_single] => 
    [is_preview] => 
    [is_page] => 
    [is_archive] => 1
    [is_date] => 
    [is_year] => 
    [is_month] => 
    [is_day] => 
    [is_time] => 
    [is_author] => 1
    [is_category] => 
    [is_tag] => 
    [is_tax] => 1
    [is_search] => 
    [is_feed] => 
    [is_comment_feed] => 
    [is_trackback] => 
    [is_home] => 
    [is_404] => 
    [is_embed] => 
    [is_paged] => 
    [is_admin] => 1
    [is_attachment] => 
    [is_singular] => 
    [is_robots] => 
    [is_posts_page] => 
    [is_post_type_archive] => 
    [query_vars_hash:WP_Query:private] => 4ac5721966fc9ad057ab45f5aff3826f
    [query_vars_changed:WP_Query:private] => 
    [thumbnails_cached] => 
    [stopwords:WP_Query:private] => 
    [compat_fields:WP_Query:private] => Array
        (
            [0] => query_vars_hash
            [1] => query_vars_changed
        )

    [compat_methods:WP_Query:private] => Array
        (
            [0] => init_query_flags
            [1] => parse_tax_query
        )

)

I've tried so far:

  1. changing the php arguments or deleting them all - same result

  2. the submit button was originaly inside the main author.php loop, i've moved it out with no success.

  3. I had a pre_get_posts hooked to the main author loop, I've deleted it to check if it conflicts - same same.

Thanks a lot, Itamar

0

Well i figured it out somehow. There were two causes to that issue:

  1. tax_query array values cannot be empty. it either the array keys are populated, or there shouldn't be an array at all.

  2. I don't know why, but giving author a number didn't work. I've changed it to 'author__in' => array($author) and it worked.

The fixed code altogether:

function bayadaim_ajax_fetch_posts(){
$template = $_POST['template'];
$offset = $_POST["offset"];
$ppp = $_POST["ppp"];
$tax = $_POST["tax"];
$term = $_POST["term"];

if( !empty($_POST["tax"]) || !empty($_POST["term"]) ){
$tax_query = array(array(
            'taxonomy' => $tax,
            'field'    => 'slug',
            'terms'    => $term,
        ),
    );
}else{
    $tax_query = null;
}
$meta = $_POST["meta"];
$author = $_POST["author"];
$orderby = $_POST["orderby"];
$order = $_POST["order"];
$post_type = (!empty($_POST["post_type"]) ? $_POST["post_type"] : "post");
header("Content-Type: text/html");

$args = array(
    'meta_key' => $meta,
    'orderby' => $orderby,
    'order' => $order, 
    'posts_per_page' => $ppp,
    'tax_query' => $tax_query,
    'author__in' => array($author),
    'offset' => $offset,
    'post_status' => 'publish',
    'post_type' => $post_type
);

$loop = new WP_Query($args);

if ($loop->have_posts()) :
    while ($loop->have_posts()) : $loop->the_post();
        if ( $template == 'row' ) {
            include( locate_template( 'content-post_in_row.php', false, true ) ); //by using include(locate_template()) combination i keep child-theme functionality while still passing variables to included file.
        }elseif( $template == 'list' ){
            include( locate_template( 'content-post_in_listing.php', false, true ) ); //by using include(locate_template()) combination i keep child-theme functionality while still passing variables to included file.                
        }
    endwhile;
else :
    if ( !empty($loop) ) print_r($loop); //for debugging
endif;

exit; 
}

add_action('wp_ajax_nopriv_bayadaim_ajax_fetch_posts', 'bayadaim_ajax_fetch_posts'); 
add_action('wp_ajax_bayadaim_ajax_fetch_posts', 'bayadaim_ajax_fetch_posts');

Any suggestions for how to make the code more elegant and efficient are welcomed.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.