Ajax фильтр и загрузить больше на пользовательских сообщений - PullRequest
0 голосов
/ 31 января 2019

Я пытаюсь создать список завершенных проектов с помощью кнопки ajax load more и сортировки категорий для пользовательских сообщений.Я нашел этот учебник для начала https://rudrastyh.com/wordpress/ajax-load-more-with-filters.html

В индексном файле я изменил код из категорий, выбранных из учебника, упомянутых выше, в список категорий.В файле functions.php я добавил «post_type» => «projects», но в запросе отображается только сообщение Hello World.

index.php

<?php
  if( $terms = get_terms( array(
  'taxonomy' => 'category', // to make it simple I use default categories
  'orderby' => 'name'
  ) ) ) :
  //if categories exist, display the dropdown
  echo '<div class="project-categories"><ul>';
    foreach ( $terms as $term ) :
     echo '<li class="cat-item"><a href="' . $term->get_term_link . '">' . $term->name . '</a></li>'; // ID of the category as an option value
    endforeach;
  echo '</ul></div>';
 endif;
?>

<?php
  if ( have_posts() ) :
?>
<div id="misha_posts_wrap"><?php

  while ( have_posts() ) : the_post();

  get_template_part( 'templates/content', get_post_format() );

  endwhile;
?></div><?php

 global $wp_query; // you can remove this line if everything works for you

 // don't display the button if there are not enough posts
 if (  $wp_query->max_num_pages > 1 ) :
  echo '<div id="misha_loadmore">More posts</div>';
 endif;

 else:

  get_template_part( 'templates/content', 'none' );

 endif;
?>
</div><!-- #misha_posts_wrap -->

functions.php

add_action( 'wp_enqueue_scripts', 'misha_script_and_styles');

function misha_script_and_styles() {
// absolutely need it, because we will get $wp_query->query_vars and 
$wp_query->max_num_pages from it.
global $wp_query;

// when you use wp_localize_script(), do not enqueue the target script immediately
wp_register_script( 'misha_scripts', get_stylesheet_directory_uri() . '/assets/scripts/script.js', array('jquery') );

// now the most interesting part
// we have to pass parameters to myloadmore.js script but we can get the parameters values only in PHP
// you can define variables directly in your HTML but I decided that the most proper way is wp_localize_script()
wp_localize_script( 'misha_scripts', 'misha_loadmore_params', array(
    'ajaxurl' => site_url() . '/wp-admin/admin-ajax.php', // WordPress AJAX
    'posts' => json_encode( $wp_query->query_vars ), // everything about your loop is here
    'current_page' => $wp_query->query_vars['paged'] ? $wp_query->query_vars['paged'] : 1,
    'max_page' => $wp_query->max_num_pages
) );

wp_enqueue_script( 'misha_scripts' );
 }


 add_action('wp_ajax_loadmore', 'misha_loadmore_ajax_handler'); // 
 wp_ajax_{action}
 add_action('wp_ajax_nopriv_loadmore', 'misha_loadmore_ajax_handler'); // 
 wp_ajax_nopriv_{action}

function misha_loadmore_ajax_handler(){

// prepare our arguments for the query
$args = json_decode( stripslashes( $_POST['query'] ), true );
$args['paged'] = $_POST['page'] + 1; // we need next page to be loaded
$args['post_status'] = 'publish';

// it is always better to use WP_Query but not here
query_posts( $args );

if( have_posts() ) :

    // run the loop
    while( have_posts() ): the_post();

        get_template_part( 'templates/content', 
get_post_format() );

    endwhile;

endif;
die; // here we exit the script and even no wp_reset_query() required!
}



add_action('wp_ajax_mishafilter', 'misha_filter_function');
add_action('wp_ajax_nopriv_mishafilter', 'misha_filter_function');

function misha_filter_function(){

// example: date-ASC
$order = explode( '-', $_POST['misha_order_by'] );

$args = array(
    'post_type' => 'projects',
    'posts_per_page' => $_POST['misha_posts_per_page'], // -1 to show all posts
    'orderby' => $order[0], // example: date
    'order' => $order[1], // example: ASC
);


query_posts( $args );

global $wp_query;

if( have_posts() ) :

    ob_start(); // start buffering because we do not need to print the posts now

    while( have_posts() ): the_post();

        get_template_part( 'templates/content', get_post_format() );

    endwhile;

    $content = ob_get_contents(); // we pass the posts to variable
    ob_end_clean(); // clear the buffer

endif;

// no wp_reset_query() required

echo json_encode( array(
    'posts' => serialize( $wp_query->query_vars ),
    'max_page' => $wp_query->max_num_pages,
    'found_posts' => $wp_query->found_posts,
    'content' => $content
) );

die();
 }

Я хотел бы отображать 6 постов на странице для пользовательских проектов постов.Также я хотел бы, чтобы в списке категорий отображались также пустые категории и опция «просмотреть все проекты».Но я застрял и надеюсь на вашу помощь.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...