Запрос Ajax WP не дает никаких результатов на author.php
У меня есть вызов Ajax для загрузки большего количества сообщений при нажатии кнопки. Ajax генерирует новый запрос WP_ в соответствии с некоторыми аргументами, которые он получает из формы, а затем отправляет posts
, который возвращается на страницу.
Он хорошо работает на моей домашней странице и в одном из архивов таксономии. Я думал, что построил его правильно таким образом, чтобы он работал где угодно, но, по-видимому, что-то идет не совсем так author.php
. Код у него не очень тонкий, я знаю, извините.
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:
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
)
)
Я пытался до сих пор:
Изменение аргументов php или их удаление - тот же результат
Кнопка отправки изначально находилась внутри основного author.php петля, я убрал ее, но безуспешно.
У меня был
pre_get_posts
, подключенный к основному циклу автора, я удалил его, чтобы проверить, конфликтует ли он - то же самое.
Спасибо лот, Итамар
1 answers
Ну, я как-то это понял. У этой проблемы было две причины:
tax_query
значения массива не могут быть пустыми. это либо ключи массива заполнены, либо массива вообще не должно быть.Я не знаю почему, но дать
author
номер не сработало. Я изменил его на'author__in' => array($author)
, и это сработало.
Фиксированный код в целом:
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');
Любые предложения о том, как сделать код более элегантным и эффективным, являются приветствуется.