Как добавить пагинацию в мой пользовательский виджет? Elementor // How to add pagination to my custom widget? Elementor

Рейтинг: 0Ответов: 1Опубликовано: 15.05.2023

Есть мой плагин, который отображает каталог товаров, но без пагинации. Вот код, используемый в моем плагине elementor: myproduct.php.

<?php 
namespace Elementor;
 
if ( ! defined( 'ABSPATH' ) ) exit; // Exit if accessed directly

// Download
class qqqqqqq {
 
   public function get_name() {
      return 'audio_product';
   }
 
   public function get_title() {
      return esc_html__( 'Audio Product', 'qqqqqqq' );
   }
 
   public function get_icon() { 
        return 'eicon-gallery-masonry';
   }
 
   public function get_categories() {
      return [ 'qqqqqqq-elements' ];
   }

   protected function _register_controls() {

      $this->start_controls_section(
         'audio_product_section',
         [
            'label' => esc_html__( 'Audio Product', 'qqqqqqq' ),
            'type' => Controls_Manager::SECTION,
         ]
      );
      
      $this->add_control(
         'category',
         [
            'label' => esc_html__( 'Category', 'qqqqqqq' ),
            'type' => Controls_Manager::SELECT2, 
            'title' => esc_html__( 'Select a category', 'qqqqqqq' ),
            'multiple' => true,
            'options' => tijarah_get_terms_dropdown_array([
               'taxonomy' => 'product_cat',
               'hide_empty' => false,
            ]),
         ]
      );

      $this->add_control(
         'ppp',
         [
            'label' => __( 'Number of Items', 'qqqqqqq' ),
            'type' => Controls_Manager::SLIDER,
            'range' => [
               'no' => [
                  'min' => 0,
                  'max' => 100,
                  'step' => 1,
               ],
            ],
            'default' => [
               'size' => 9,
            ]
         ]
      );

      $this->add_control(
         'order',
         [
            'label' => __( 'order', 'qqqqqqq' ),
            'type' => \Elementor\Controls_Manager::SELECT,
            'default' => 'DESC',
            'options' => [
               'ASC'  => __( 'Ascending', 'qqqqqqq' ),
               'DESC' => __( 'Descending', 'qqqqqqq' )
            ],
         ]
      );
          
          $this->add_control(
                'paginate',
                [
                    'label' => __( 'Pagination' ),
                    'type' => Controls_Manager::SWITCHER,
                    'default' => '',
                ]
            );

      $this->end_controls_section();

   }

   protected function render( $instance = [] ) {
 
      // get our input from the widget settings.
       
      $settings = $this->get_settings_for_display(); ?>
          

         
         <div class="download_items row justify-content-center">
            
            <?php
            $category = !empty( $settings['category'] ) ? $settings['category'] : 'All';

            $download = new \WP_Query( array( 
               'post_type' => 'product',
               'posts_per_page' => $settings['ppp']['size'],
               'order' => $settings['order'],
               'paginate' => $settings['paginate'],
               'tax_query'     => array(
                    array(
                        'taxonomy'  => 'product_cat',
                        'field'     => 'id', 
                        'terms'     => $category
                    )
                )
   ));
 

 
            /* Start the Loop */
            while ( $download->have_posts() ) : $download->the_post(); ?>       

               <!-- Item -->
               <div class="col-xl-4 col-md-6">
                  <?php get_template_part( 'template-parts/product-type/audio', 'item' ); ?>
               </div>


            <?php 
            endwhile; 
         wp_reset_postdata();
                 
         ?>
         </div>
                 

   <?php
   }
 
}

Plugin::instance()->widgets_manager->register_widget_type( new qqqqqqq ); 

Я добавил этот код:

$this->add_control(
                'paginate',
                [
                    'label' => __( 'Pagination' ),
                    'type' => Controls_Manager::SWITCHER,
                    'default' => '',
                ]
            );

В админ меню появлился выбор - ставить пагинацию или нет. Но на самом деле пагинация не работает. Какой код нужно ввести, чтобы он заработал?

P.S. Если это поможет решить проблему, есть также этот файл, связанный с виджетом. elementor.php:

<?php

if ( ! defined( 'ABSPATH' ) ) exit;

// get posts dropdown
function qqqqqqq_get_posts_dropdown_array($args = [], $key = 'ID', $value = 'post_title') {
  $options = [];
  $posts = get_posts($args);
  foreach ((array) $posts as $term) {
    $options[$term->{$key}] = $term->{$value};
  }
  return $options;
}

// get terms dropdown
function qqqqqqq_get_terms_dropdown_array($args = [], $key = 'term_id', $value = 'name') {
  $options = [];
  $terms = get_terms($args);

  if (is_wp_error($terms)) {
    return [];
  }

  foreach ((array) $terms as $term) {
    $options[$term->{$key}] = $term->{$value};
  }

  return $options;
}

function qqqqqqq_add_elementor_widget_categories( $elements_manager ) {

        $elements_manager->add_category(
                'qqqqqqq-elements',
                [
                        'title' => esc_html__( 'qqqqqqq Elements', 'qqqqqqq' ),
                        'icon' => 'fa fa-plug',
                ]
        );

}
add_action( 'elementor/elements/categories_registered', 'qqqqqqq_add_elementor_widget_categories' );

//Elementor init

class qqqqqqq_ElementorCustomElement {
 
   private static $instance = null;
 
   public static function get_instance() {
      if ( ! self::$instance )
         self::$instance = new self;
      return self::$instance;
   }
 
   public function init(){
      add_action( 'elementor/widgets/widgets_registered', array( $this, 'widgets_registered' ) );
   }

   public function widgets_registered() {
 
    // We check if the Elementor plugin has been installed / activated.
    if(defined('ELEMENTOR_PATH') && class_exists('Elementor\Widget_Base')){      
         include_once(plugin_dir_path( __FILE__ ).'/widgets/widget-accordion.php');
         include_once(plugin_dir_path( __FILE__ ).'/widgets/widget-ajax-search.php');
         include_once(plugin_dir_path( __FILE__ ).'/widgets/widget-audio-products.php');
         include_once(plugin_dir_path( __FILE__ ).'/widgets/widget-banner.php');
         include_once(plugin_dir_path( __FILE__ ).'/widgets/widget-banner2.php');
         include_once(plugin_dir_path( __FILE__ ).'/widgets/widget-blog.php');
         include_once(plugin_dir_path( __FILE__ ).'/widgets/widget-button.php');
         include_once(plugin_dir_path( __FILE__ ).'/widgets/widget-counter.php');
         include_once(plugin_dir_path( __FILE__ ).'/widgets/widget-download.php');
         include_once(plugin_dir_path( __FILE__ ).'/widgets/widget-featured.php');
         include_once(plugin_dir_path( __FILE__ ).'/widgets/widget-newest.php');
         include_once(plugin_dir_path( __FILE__ ).'/widgets/widget-cta.php');
         include_once(plugin_dir_path( __FILE__ ).'/widgets/widget-partner.php');
         include_once(plugin_dir_path( __FILE__ ).'/widgets/widget-photo-products.php');
         include_once(plugin_dir_path( __FILE__ ).'/widgets/widget-pricing-woocommerce.php');
         include_once(plugin_dir_path( __FILE__ ).'/widgets/widget-pricing.php');
         include_once(plugin_dir_path( __FILE__ ).'/widgets/widget-products.php');
         include_once(plugin_dir_path( __FILE__ ).'/widgets/widget-infobox.php');
         include_once(plugin_dir_path( __FILE__ ).'/widgets/widget-team.php');
         include_once(plugin_dir_path( __FILE__ ).'/widgets/widget-testimonials.php');
         include_once(plugin_dir_path( __FILE__ ).'/widgets/widget-title.php');
         include_once(plugin_dir_path( __FILE__ ).'/widgets/widget-video-products.php');
         include_once(plugin_dir_path( __FILE__ ).'/widgets/widget-video.php');
      }
        }

}
 
qqqqqqq_ElementorCustomElement::get_instance()->init();

Какой код я должен вставить и где, чтобы заставить работать пагинацию в моем виджете elementor?

Ответы

▲ 0

Решено. Добавить в строку $download = new \WP_Query( array( это:

'posts_per_page' => 20,  // кол во товаров после которого начнется пагинация
'paged'          => get_query_var( 'paged' ) ?: 1,
  • добавить после wp_reset_postdata();?>

это:

<div class="text-center mt-5">
   <?php global $wp_query;
$restore_wp_query = $wp_query;
$wp_query         = $download;
the_posts_pagination( array(
            'mid_size'  => 2,
            'prev_next'    => true,
            'prev_text' => esc_html__( '&#10094; Prev', 'qqqqqqq' ),
            'next_text' => esc_html__( 'Next &#10095;', 'qqqqqqq' ),
        ) );
$wp_query = $restore_wp_query;
?>
 </div>

вот что в итоге получилось и пагинация заработала - все что добавлял добавлял в myproduct.php p.s.//( $this->add_control( 'paginate' - это я убрал, оно не понадобилось):

<?php 
namespace Elementor;
 
if ( ! defined( 'ABSPATH' ) ) exit; // Exit if accessed directly

// Download
class qqqqqqq {
 
   public function get_name() {
      return 'audio_product';
   }
 
   public function get_title() {
      return esc_html__( 'Audio Product', 'qqqqqqq' );
   }
 
   public function get_icon() { 
        return 'eicon-gallery-masonry';
   }
 
   public function get_categories() {
      return [ 'qqqqqqq-elements' ];
   }

   protected function _register_controls() {

      $this->start_controls_section(
         'audio_product_section',
         [
            'label' => esc_html__( 'Audio Product', 'qqqqqqq' ),
            'type' => Controls_Manager::SECTION,
         ]
      );
      
      $this->add_control(
         'category',
         [
            'label' => esc_html__( 'Category', 'qqqqqqq' ),
            'type' => Controls_Manager::SELECT2, 
            'title' => esc_html__( 'Select a category', 'qqqqqqq' ),
            'multiple' => true,
            'options' => tijarah_get_terms_dropdown_array([
               'taxonomy' => 'product_cat',
               'hide_empty' => false,
            ]),
         ]
      );

      $this->add_control(
         'ppp',
         [
            'label' => __( 'Number of Items', 'qqqqqqq' ),
            'type' => Controls_Manager::SLIDER,
            'range' => [
               'no' => [
                  'min' => 0,
                  'max' => 100,
                  'step' => 1,
               ],
            ],
            'default' => [
               'size' => 9,
            ]
         ]
      );

      $this->add_control(
         'order',
         [
            'label' => __( 'order', 'qqqqqqq' ),
            'type' => \Elementor\Controls_Manager::SELECT,
            'default' => 'DESC',
            'options' => [
               'ASC'  => __( 'Ascending', 'qqqqqqq' ),
               'DESC' => __( 'Descending', 'qqqqqqq' )
            ],
         ]
      );
          
    

      $this->end_controls_section();

   }

   protected function render( $instance = [] ) {
 
      // get our input from the widget settings.
       
      $settings = $this->get_settings_for_display(); ?>
          

         
         <div class="download_items row justify-content-center">
            
            <?php
            $category = !empty( $settings['category'] ) ? $settings['category'] : 'All';

            $download = new \WP_Query( array( 
               'post_type' => 'product',
               'posts_per_page' => 20,
               'paged'          => get_query_var( 'paged' ) ?: 1,
               'order' => $settings['order'],               
               'tax_query'     => array(
                    array(
                        'taxonomy'  => 'product_cat',
                        'field'     => 'id', 
                        'terms'     => $category
                    )
                )
   ));
 

 
            /* Start the Loop */
            while ( $download->have_posts() ) : $download->the_post(); ?>       

               <!-- Item -->
               <div class="col-xl-4 col-md-6">
                  <?php get_template_part( 'template-parts/product-type/audio', 'item' ); ?>
               </div>


            <?php 
            endwhile; 
         wp_reset_postdata();
                 
         ?>
         </div>


   <div class="text-center mt-5">
   <?php global $wp_query;
$restore_wp_query = $wp_query;
$wp_query         = $download;
the_posts_pagination( array(
            'mid_size'  => 2,
            'prev_next'    => true,
            'prev_text' => esc_html__( '&#10094; Prev', 'qqqqqqq' ),
            'next_text' => esc_html__( 'Next &#10095;', 'qqqqqqq' ),
        ) );
$wp_query = $restore_wp_query;
?>
 </div>              



   <?php
   }
 
}

Plugin::instance()->widgets_manager->register_widget_type( new qqqqqqq );