Кнопка показать еще wordpress. Вывод записей WordPress бесконечным списком

Программы 14.10.2023
Программы

Ajax Load More is the ultimate WordPress infinite scroll plugin for lazy loading posts, single posts, pages, comments and more with Ajax powered queries.

Build complex custom WordPress queries with the Ajax Load More shortcode builder then add the generated shortcode to your page via the content editor or directly into your template files.

Ajax Load More is compatible for endless scrolling with popular eCommerce plugins such as WooCommerce and Easy Digital Downloads.

Особенности
  • Shortcode Builder — Create your own custom Ajax Load More shortcode by adjusting the various WordPress query parameters in our easy-to-use shortcode builder (see Shortcode Parameters).
  • Query Parameters — Ajax Load More allows you to query WordPress by many different content types. Query by Post Type, Post Format, Date, Category, Tags, Custom Taxonomies, Search Term, Authors and more!
  • Repeater Templates — Edit and extend the functionality of Ajax Load More by creating your own repeater template to match the look and feel of your website (see screenshots).
  • Multiple Instances — You can include multiple instances of Ajax Load More on a single page, post or template.
  • Ajax Filtering — The Ajax Load More custom filtering method will allow you to filter and update your Ajax query results.
  • Multisite Compatibility — Manage repeater templates across all sites in your network.
  • Setting Panel — Customize your version of Ajax Load More by updating various plugin settings.
  • repeater — Choose a repeater template (Add-on available). Default = ‘default’
  • post_type — Comma separated list of post types. Default = ‘post’
  • sticky_posts — Preserve sticky post ordering in Ajax listing. Default = false
  • post_format — Query by post format. Default = null
  • category — A comma separated list of categories to include by slug. Default = null
  • category__and — A comma separated list of categories to include by ID. Default = null
  • category__not_in — A comma separated list of categories to exclude by ID. Default = null
  • tag — A comma separated list of tags to include by slug. Default = null
  • tag__and — A comma separated list of tags to include by ID. Default = null
  • tag__not_in — A comma separated list of tags to exclude by ID. Default = null
  • taxonomy — Query by custom taxonomy name. Default = null
  • taxonomy_terms — Comma separated list of custom taxonomy terms(slug). Default = null
  • taxonomy_operator
  • taxonomy_relation — The logical relationship between each taxonomy when there is more than one. (AND/OR). Default = ‘AND’
  • day — Day of the week. Default = null
  • month — Month of the year. Default = null
  • year — Year of post. Default = null
  • taxonomy_operator — Operator to compare Taxonomy Terms against (IN/NOT IN). Default = ‘IN’
  • meta_key — Custom field key(name). Default = null
  • meta_value — Custom field value. Default = null
  • meta_compare — Operator to compare meta_key and meta_value against. Default = ‘IN’
  • meta_type — Custom field type. Default = ‘CHAR’
  • meta_relation — Used with multiple custom field entries (AND/OR). Default = ‘AND’
  • author — Comma separated list of authors by id. Default = null
  • post__in — Comma separated list of post ID’s to include in query. Default = null
  • post__not_in — Comma separated list of post ID’s to exclude from query. Default = null
  • search — Query search term (‘s’). Default = null
  • custom_args — A semicolon separated list of value:pair arguments. e.g. tag_slug__and:design,development; event_display:upcoming. Default = null
  • post_status — Select status of the post. Default = ‘publish’
  • order — Display posts in ASC(ascending) or DESC(descending) order. Default = ‘DESC’
  • orderby — Order posts by date, title, name, menu order, author, post ID or comment count. Default = ‘date’
  • offset — Offset the initial query (number). Default = ’0′
  • posts_per_page — Number of posts to load with each Ajax request. Default = ’5′
  • scroll — Load more posts as the user scrolls the page (true/false). Default = ‘true’
  • scroll_distance — The distance from the bottom of the screen to trigger the loading of posts while scrolling. Default = ‘150’
  • scroll_container — Constrain Ajax Load More infinite scrolling to a parent container. Default = null
  • max_pages — Maximum number of pages to load while user is scrolling (activated on when scroll = true). Default = ‘0’
  • pause_override — Allow scrolling to override the Pause parameter and trigger the loading of posts on scroll. Default = null
  • pause — Do not load posts until user clicks the Load More button (true/false). Default = ‘false’
  • transition — Choose a posts reveal transition (fade/masonry/none). Default = ‘fade’
  • transition_container — Display the Ajax Load More (.alm-reveal) loading container. Default = ‘true’
  • transition_container_classes — Add classes to the .alm-reveal transition div.
  • masonry_selector — The target classname of each masonry item. Default = null
  • masonry_animation — Select a loading transition type for Masonry items. (default/zoom-out/slide-up/slide-down/none). Default = default
  • masonry_horizontalorder — Maintain horizontal order. Default = true
  • images_loaded — Wait for all images to load before displaying ajax loaded content (true/false). Default = ‘false’
  • destroy_after — Remove ajax load more functionality after ‘n’ number of pages have been loaded. Default = null
  • progress_bar — Display progress bar indicator at the top of the window while loading Ajax content. Default = ‘false’
  • progress_bar_color — Enter the hex color of the progress bar. Default = ‘ed7070’
  • button_label — The label text for Load More button. Default = ‘Older Posts’
  • — Update the text of the Load More button while content is loading. Default = null
  • container_type — Override the global Container Type that was set on ALM Settings page. Default = null
  • css_classes — Add custom CSS classes to the Ajax Load More container. Default = null
  • id — A unique ID for the Ajax Load More instance.
  • nested — Is this a nested Ajax Load More instance. Default = false
Example Ajax Load More Shortcode Example Demos
  • Default — Out of the box functionality and styling.
  • Advanced Custom Fields — Infinite scroll Advanced Custom Fields data with Ajax Load More.
  • Attachments — Endless scroll post attachments.
  • Destroy After — Remove Ajax Load More functionality after ‘n’ number of pages.
  • Event Listing — Ordering and listing events by custom field date.
  • Filtering — Reset and filter an Ajax Load More instance.
  • Flexbox — Creating a responsive Ajax Load More grid with Flexbox.
  • Infinite Scroll — A look at the new loading functionality and styles.
  • Images Loaded — Download images before displaying ajax loaded content.
  • Masonry — Creating a flexible grid layout with Masonry JS.
  • Multiple Instances — Include multiple Ajax Load More’ on a single page.
  • Paging URLs — Generate unique paging URLs for every Ajax Load More query with the SEO add-on.
  • — Posts will not load until initiated by the user.
  • Preloaded Posts — Easily preload an initial set of posts before completing any Ajax requests to the server.
  • Progress Bar — Display a progress bar load indicator with each Ajax request.
  • Search Results — Returning results based on search terms.
  • Scroll Container — Constrain Ajax Load More to a parent container.
  • SEO & Paging — Combine these two add-ons to create one powerful navigation system.
  • Slideshow Gallery — Create a gallery of posts with Ajax Load More and the Paging add-on.
  • Table Layout — Ajax Load More will display query results in a table format.

Все мы видели архивы, в которых при выборе месяца нас перекидывало на страницу с записями за этот месяц. В WordPress такой вывод архивных ссылок реализуется с помощью функции wp_get_archives() . Аналогичный архив записей получается и при выводе обычных рубрик WordPress, только записи группируются по категориям.

Сегодня я хочу рассказать вам, как сделать динамическую архивную страницу . "Динамическая" значит, что при выборе месяца, результаты будут показываться на той же странице , при помощи AJAX - технологии Javascript. Так как библиотека jQuery предоставляет удобный API по работе с Ajax, то будем использовать этот фреймворк. К тому же, куда сегодня без jQuery? Он ведь используется сплошь и рядом, и наверняка в вашем проекте он уже подключен.

Перед написанием этой статьи я сделал динамическую архивную страницу для этого блога, предлагаю взглянуть (ДЕМО) .

Чтобы реализовать динамический архив нам нужно пройти 4 этапа:

Я буду показывать создание динамической страницы архивов на примере базовой темы WordPress: "twentyten".

1. Подключение jQuery в WordPress

Правильный вариант подключения jQuery скрипта - это использование функции wp_enqueue_script() . Такое подключение обезопасит вас от конфликтов с подключением этого же скрипта в плагинах. Скрипт будет подключен один раз.

Вставлять этот код нужно в файл темы functions.php.

Вариант 2

В первом варианте мы подключили скрипт с нашего сервера, имеющийся в файлах WordPress. Однако, можно изменить ссылку на файл jQuery и подключить его с CDN Google. Преимущество такого подхода в том, что, если в браузере посетителя уже загружен этот файл, то при заходе на ваш сайт браузер уже не будет загружать скрипт/ Загрузка страницы увеличится. Кроме того, в CDN скрипт отдается в сжатом виде, за счет чего файл легче на несколько килобайт:

Function my_scripts_method() { wp_deregister_script("jquery"); wp_register_script("jquery", "//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"); wp_enqueue_script("jquery"); } add_action("wp_enqueue_scripts", "my_scripts_method");

Вариант 3

Самый древний и так называемый "жесткий" вариант подключения jQuery - это прописать ссылку на него в файле шаблона header.php , внутри тега . Вставляем такой html код:

2. Загрузим картинку пред-загрузчик

В период ожидания, когда запрос отправляется серверу с помощью AJAX нам нужно показать картинку, уведомив пользователя, что что-то происходит. Такие картинки вы наверняка видели в сети и не раз, альтернативой такой картинки выступает текст: "Загрузка...".

Чтобы в дальнейшем у нас была такая картинка, давайте скачаем её, например, от сюда: Анимированные gif (сервис мне понравился), переименуем её в ajax-loader.gif и загрузим в папку images , которая находится в каталоге нашей темы WordPress. В итоге у нас получиться такой пусть до картинки: http://example.com/wp-content/themes/twentyten/images/ajax-loader.gif . Ниже мы его используем в коде.

3. Создание шаблона постоянной страницы

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

"Шаблон архивов" - это название нашего шаблона, которое мы увидим в админ-панели WordPress, при создании постоянной страницы.

Давайте создадим новый файл в папке темы, с названием tpl_archive.php и вставим туда вышеприведенный код. Затем зайдем в админ-панель WordPress и создадим постоянную страницу, назначив ей, только что созданный, шаблон.

Теперь, заполним этот файл необходимым кодом.

1. В первую очередь, нам нужно вывести выпадающие списки , создадим мы их с помощью функций WordPress: wp_get_archives() и wp_dropdown_categories() :

Месяцы - Рубрики

get_header(); и get_footer(); получают шапку и подвал шаблона соответственно. get_sidebar(); я вырезал намеренно, чтобы он не мешался в понимании кода. Остальная часть кода выводит выпадающие списки Месяцев и Рубрик.

Пустой блок - это контейнер куда будут выводится результаты запроса, т.е. записи.

2. Оформим выпадающие списки через CSS, для этого добавим такой код сразу после вызова шапки ():

#archive_browser >

На этом этапе у меня получилось следующее:


3. Добавим JavaScript код , который будет выполнять запрос к серверу и выводить его в блок archive_pot (код добавляем после css стилей):

Рекомендуем почитать

Наверх