web-dev-qa-db-fra.com

Ajax WP Query ne renvoie aucun résultat sur author.php

J'ai un appel Ajax pour charger plus de messages sur un clic de bouton. L'Ajax génère un nouveau WP_Query en fonction de certains arguments tirés d'un formulaire, puis envoie la variable posts à la page.

Cela fonctionne bien sur ma page d'accueil et l'une des archives de taxonomie. Je pensais l'avoir construit correctement d'une manière qui fonctionnerait n'importe où, mais apparemment, quelque chose ne va pas très bien sur author.php. Le code n'est pas très mince, je sais, désolé.

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');

Le tableau WP_Query a renvoyé:

    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
        )

)

J'ai déjà essayé:

  1. changer les arguments php ou les supprimer tous - même résultat

  2. le bouton d'envoi était à l'origine dans la boucle principale author.php, je l'ai déplacé sans succès.

  3. J'ai eu un pre_get_posts accroché à la boucle auteur principale, je l'ai supprimé pour vérifier s'il y a conflit - idem.

Merci beaucoup, Itamar

1
Ituk

Eh bien, je l'ai compris d'une manière ou d'une autre. Ce problème avait deux causes:

  1. Les valeurs du tableau tax_query ne peuvent pas être vides. soit les clés du tableau sont remplies, soit il ne devrait pas y en avoir du tout.

  2. Je ne sais pas pourquoi, mais donner author un nombre n'a pas fonctionné. Je l'ai changé pour 'author__in' => array($author) et cela a fonctionné.

Le code fixe en tout:

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');

Toutes les suggestions pour rendre le code plus élégant et efficace sont les bienvenues.

0
Ituk