Ajax подгрузка постов WordPress

Содержание

  • 1. Ajax подгрузка постов WordPress.
  • 2. Структура плагина.
  • 3. Backend. ajaxer.php
  • 4. Frontend. ajaxer-script.js
  • 5. Стили. ajaxer-style.css
  • 6. Как пользоваться плагином

1. Ajax подгрузка постов WordPress

Ajax подгрузка постов WordPress это необходимы функционал на современном сайте. Сейчас в современном мире все стремятся сделать свой сайт более интерактивным и удобным. Для тех кто на знает, ajax это технология обмена данными между клиентом и сервером без перезагрузки страницы.

В этой статье я хочу рассказать вам, как сделать ajax подгрузку постов на WordPress.

Фото: Ajax подгрузка постов WordPress

2. Структура плагина

Лучше всего данный код оформлять в виде плагина. Итак начнем.

Создадим папку под названием ajaxer и в этой папке 3 файла:

ajaxer.php — backend
ajaxer-script.js — frontend
ajaxer-style.css — стили

3. Backend. ajaxer.php

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

61

62

63

64

65

66

67

68

69

70

<?php

/*

Plugin Name: Ajaxer

Text Domain: asp01

Domain Path: /languages

Description: Show post by Ajax

Version: 1.0.0

Author: Alex Kuimov

*/

add_action(‘wp_head’,‘sp_scripts’);

functionsp_scripts(){

wp_register_script(‘ajaxer-script’,plugins_url(‘ajaxer-script.js’,__FILE__));

wp_enqueue_script(‘ajaxer-script’);

wp_localize_script(‘ajaxer-script’,‘ajax_object’,array(‘ajax_url’=>admin_url(‘admin-ajax.php’)));

}

add_action(‘wp_enqueue_scripts’,‘sp_styles’);

functionsp_styles(){

    wp_register_style(‘ajaxer-style’,plugins_url(‘ajaxer-style.css’,__FILE__),false,false,‘all’);

    wp_enqueue_style(‘ajaxer-style’);

}

functionsp_show_posts(){

    $count=sanitize_text_field($_POST[‘count’]);

    $first_show=sanitize_text_field($_POST[‘first_show’]);

    $posts_per_page=get_option(‘posts_per_page’);

    $count=$count+  $posts_per_page;

    $args=array(

        ‘orderby’     =>‘id’,

        ‘order’       =>‘DESC’,

        ‘post_type’   =>‘post’,

        ‘post_status’=>‘publish’,

        

    );

    if($first_show==‘y’){

        $args[‘posts_per_page’]=$posts_per_page;

    }else{

        $args[‘posts_per_page’]=$count;

    }    

    query_posts($args);

    global$wp_query;

  

    $all_post_count=$wp_query->found_posts;

    $current_post_count=0;

    while(have_posts()):the_post();

        $current_post_count++;

        get_template_part(‘template-parts/single’);

    endwhile;

    wp_reset_postdata();

  

    if($all_post_count!=$current_post_count){

        echo‘<div class=»sp_ajax_show_more»>Загрузить еще</div>’;

    }

}

add_action(‘wp_ajax_sp_show_posts’,‘sp_show_posts’);

add_action(‘wp_ajax_nopriv_sp_show_posts’,‘sp_show_posts’);

?>

4. Frontend. ajaxer-script.js

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

jQuery(document).ready(function($){

    count=0;//count posts

    step=parseInt($(‘.sp_ajax_result’).attr(‘data-step’));

    functionsp_show_posts(){

        jQuery.post(

            ajax_object.ajax_url,{

                ‘action’:‘sp_show_posts’,

                ‘first_show’:‘y’,

            },

            function(data){

                $(‘.sp_ajax_result’).html(data.substring(0,data.length1));

            }

        );

    }

    sp_show_posts();

    $(‘body’).on(«click»,«.sp_ajax_show_more»,function(event){

        

        count=count+step;

        

        jQuery.post(

            ajax_object.ajax_url,{

                ‘action’:‘sp_show_posts’,

                ‘count’:count,

            },

            function(data){

                $(‘.sp_ajax_result’).html(data.substring(0,data.length1));

            }

        );

        

        returnfalse;

    });

});

5. Стили. ajaxer-style.css

1

2

3

.sp_ajax_show_more{

    cursor:pointer;

}

6. Как пользоваться плагином

Ищем файл темы в котором выводится список постов. К примеру index.php. В этом файле находим место с циклом вордпрес. Оборачиваем цикл в div с классом sp_ajax_result и задаем data атрибут data-step=’2′ (это шаг с которым будут добавляться посты).

Пример:

1

2

3

4

5

6

7

8

9

<div class=«sp_ajax_result»datastep=«2»>

<?phpif(have_posts()):

while(have_posts()):the_post();?>

<?php/*Тут выводятся посты*/?>

<?phpendwhile;?>

<?phpendif;?>

</div>

Скачать готовый плагин