WordPress - Display data table list by shortcode | WordPress Dùng shortcode hiển thị data table list ở front end

Post Reply
tthlan
Quản trị viên
Posts: 68
Joined: Tue Aug 23, 2016 8:13 am

WordPress - Display data table list by shortcode | WordPress Dùng shortcode hiển thị data table list ở front end

Post by tthlan » Mon Oct 28, 2019 10:21 am

Dùng shortcode hiển thị data table list ở front end
1) Tạo plugin

Code: Select all

<?php
/**
* Name: My shortcode data list table
* Description: My shortcode data list table
* Version: 1.0.0
* Author: Tran Thi Hoang Lan
**/


if (!defined( 'MY_DATA_LIST_TABLE_PLUGIN' ) )
  define('MY_DATA_LIST_TABLE_PLUGIN', __FILE__);

require plugin_dir_path( __FILE__ ) . 'my-plugin-loader.php';

function custom_shortcode(){
    echo("---custom shortcode 1 ---");

    $plugin_loader = new My_Plugin_Loader();
    $plugin_loader->run();
    echo do_shortcode("[data_table_list_transcript]");

}

add_shortcode("my_shortcode_1", "custom_shortcode");
Giả sử add shortcode my_shortcode_1 trong sample-page
Hook của my_shortcode_1 sẽ gọi My_Plugin_Loader
2) My_Plugin_Loader

Code: Select all

<?php

/**
 * Name: The file that defines the core plugin class
 *
 * A class definition that includes attributes and functions used across both the
 * public-facing side of the site and the admin area.
 * Version: 1.0
 */

/**
 * The core plugin class.
 *
 * This is used to define internationalization, admin-specific hooks, and
 * public-facing site hooks.
 *
 * Also maintains the unique identifier of this plugin as well as the current
 * version of the plugin.

 * @since      1.0.0
 * @author     Lan Tran
 */

class My_Plugin_Loader {

    /**
     * The loader that's responsible for maintaining and registering all hooks that power
     * the plugin.
     *
     * @since    1.0.0
     * @access   protected
     * @var      Plugin_Loader    $loader    Maintains and registers all hooks for the plugin.
     */
    protected $loader;

    /**
     * The unique identifier of this plugin.
     *
     * @since    1.0.0
     * @access   protected
     * @var      string    $plugin_name    The string used to uniquely identify this plugin.
     */
    protected $plugin_name;

    /**
     * The current version of the plugin.
     *
     * @since    1.0.0
     * @access   protected
     * @var      string    $version    The current version of the plugin.
     */
    protected $version;

    /**
     * Define the core functionality of the plugin.
     *
     * Set the plugin name and the plugin version that can be used throughout the plugin.
     * Load the dependencies, define the locale, and set the hooks for the admin area and
     * the public-facing side of the site.
     *
     * @since    1.0.0
     */
    public function __construct() {

        $plugin_data = get_file_data(MY_DATA_LIST_TABLE_PLUGIN, array('Version' => 'Version', 'Plugin Name' => 'Name'), false);
        $plugin_version = $plugin_data['Version'];
        $plugin_name = $plugin_data['Plugin Name'];

        if ( defined( 'PLUGIN_VERSION' ) ) {
            $this->version = PLUGIN_VERSION;
        } else {
            $this->version = $plugin_version;
        }
        $this->plugin_name = $plugin_name;

        $this->load_dependencies();
        $this->define_public_hooks();

    }

    /**
     * Load the required dependencies for this plugin.
     *
     * Include the following files that make up the plugin:
     *
     * - Plugin_Loader. Orchestrates the hooks of the plugin.
     * - Plugin_i18n. Defines internationalization functionality.
     * - Plugin_Admin. Defines all hooks for the admin area.
     * - Plugin_Public. Defines all hooks for the public side of the site.
     *
     * Create an instance of the loader which will be used to register the hooks
     * with WordPress.
     *
     * @since    1.0.0
     * @access   private
     */
    private function load_dependencies() {

        require_once 'class-plugin-loader.php';
        require_once 'class-plugin-public.php';
        require_once 'my-table-list.php';

        $this->loader = new Plugin_Loader();

    }

    /**
     * Register all of the hooks related to the public-facing functionality
     * of the plugin.
     *
     * @since    1.0.0
     * @access   private
     */
    private function define_public_hooks() {

        $plugin_public = new Plugin_Public( $this->get_plugin_name(), $this->get_version() );

        //$this->loader->add_action( 'wp_enqueue_scripts', $plugin_public, 'enqueue_styles' );
        //$this->loader->add_action( 'wp_enqueue_scripts', $plugin_public, 'enqueue_scripts' );
        //$this->loader->add_action( 'wp_loaded', $plugin_public, 'other_actions' );

        $plugin_public->other_actions();

    }

    /**
     * Run the loader to execute all of the hooks with WordPress.
     *
     * @since    1.0.0
     */
    public function run() {
        $this->loader->run();
        do_action('after_my_plugin_loader');
    }

    /**
     * The name of the plugin used to uniquely identify it within the context of
     * WordPress and to define internationalization functionality.
     *
     * @since     1.0.0
     * @return    string    The name of the plugin.
     */
    public function get_plugin_name() {
        return $this->plugin_name;
    }

    /**
     * The reference to the class that orchestrates the hooks with the plugin.
     *
     * @since     1.0.0
     * @return    Plugin_Loader    Orchestrates the hooks of the plugin.
     */
    public function get_loader() {
        return $this->loader;
    }

    /**
     * Retrieve the version number of the plugin.
     *
     * @since     1.0.0
     * @return    string    The version number of the plugin.
     */
    public function get_version() {
        return $this->version;
    }

}
My_Plugin_Loader load
$this->load_dependencies(); các file cần dùng và gọi Plugin_Loader
$this->define_public_hooks(); sẽ gọi tiếp tới Plugin_Public > other_actions
3) Plugin_Loader

Code: Select all

<?php

/**
 * Register all actions and filters for the plugin.
 *
 * Maintain a list of all hooks that are registered throughout
 * the plugin, and register them with the WordPress API. Call the
 * run function to execute the list of actions and filters.
 *
 */

class Plugin_Loader {

    /**
     * The array of actions registered with WordPress.
     *
     * @since    1.0.0
     * @access   protected
     * @var      array    $actions    The actions registered with WordPress to fire when the plugin loads.
     */
    protected $actions;

    /**
     * The array of filters registered with WordPress.
     *
     * @since    1.0.0
     * @access   protected
     * @var      array    $filters    The filters registered with WordPress to fire when the plugin loads.
     */
    protected $filters;

    /**
     * Initialize the collections used to maintain the actions and filters.
     *
     * @since    1.0.0
     */
    public function __construct() {

        var_dump("Plugin_Loader");

        $this->actions = array();
        $this->filters = array();

    }

    /**
     * Add a new action to the collection to be registered with WordPress.
     *
     * @since    1.0.0
     * @param    string               $hook             The name of the WordPress action that is being registered.
     * @param    object               $component        A reference to the instance of the object on which the action is defined.
     * @param    string               $callback         The name of the function definition on the $component.
     * @param    int                  $priority         Optional. The priority at which the function should be fired. Default is 10.
     * @param    int                  $accepted_args    Optional. The number of arguments that should be passed to the $callback. Default is 1.
     */
    public function add_action( $hook, $component, $callback, $priority = 10, $accepted_args = 1 ) {
        var_dump( $hook, $component, $callback, $priority, $accepted_args  );
        $this->actions = $this->add( $this->actions, $hook, $component, $callback, $priority, $accepted_args );
    }

    /**
     * Add a new filter to the collection to be registered with WordPress.
     *
     * @since    1.0.0
     * @param    string               $hook             The name of the WordPress filter that is being registered.
     * @param    object               $component        A reference to the instance of the object on which the filter is defined.
     * @param    string               $callback         The name of the function definition on the $component.
     * @param    int                  $priority         Optional. The priority at which the function should be fired. Default is 10.
     * @param    int                  $accepted_args    Optional. The number of arguments that should be passed to the $callback. Default is 1
     */
    public function add_filter( $hook, $component, $callback, $priority = 10, $accepted_args = 1 ) {
        $this->filters = $this->add( $this->filters, $hook, $component, $callback, $priority, $accepted_args );
    }

    /**
     * A utility function that is used to register the actions and hooks into a single
     * collection.
     *
     * @since    1.0.0
     * @access   private
     * @param    array                $hooks            The collection of hooks that is being registered (that is, actions or filters).
     * @param    string               $hook             The name of the WordPress filter that is being registered.
     * @param    object               $component        A reference to the instance of the object on which the filter is defined.
     * @param    string               $callback         The name of the function definition on the $component.
     * @param    int                  $priority         The priority at which the function should be fired.
     * @param    int                  $accepted_args    The number of arguments that should be passed to the $callback.
     * @return   array                                  The collection of actions and filters registered with WordPress.
     */
    private function add( $hooks, $hook, $component, $callback, $priority, $accepted_args ) {

        $hooks[] = array(
            'hook'          => $hook,
            'component'     => $component,
            'callback'      => $callback,
            'priority'      => $priority,
            'accepted_args' => $accepted_args
        );

        return $hooks;

    }

    /**
     * Register the filters and actions with WordPress.
     *
     * @since    1.0.0
     */
    public function run() {

        foreach ( $this->filters as $hook ) {
            add_filter( $hook['hook'], array( $hook['component'], $hook['callback'] ), $hook['priority'], $hook['accepted_args'] );
        }

        foreach ( $this->actions as $hook ) {
            add_action( $hook['hook'], array( $hook['component'], $hook['callback'] ), $hook['priority'], $hook['accepted_args'] );
        }

    }

}
4) Plugin_Public

Code: Select all

<?php
/**
 * The public-facing functionality of the plugin.
 *
 * Defines the plugin name, version, and two examples hooks for how to
 * enqueue the public-facing stylesheet and JavaScript.
 *
 */
class Plugin_Public {

    /**
     * The ID of this plugin.
     *
     * @since    1.0.0
     * @access   private
     * @var      string    $plugin_name    The ID of this plugin.
     */
    private $plugin_name;

    /**
     * The version of this plugin.
     *
     * @since    1.0.0
     * @access   private
     * @var      string    $version    The current version of this plugin.
     */
    private $version;

    /**
     * Initialize the class and set its properties.
     *
     * @since    1.0.0
     * @param      string    $plugin_name       The name of the plugin.
     * @param      string    $version    The version of this plugin.
     */
    public function __construct( $plugin_name, $version ) {

        $this->plugin_name = $plugin_name;
        $this->version = $version;
    }

    /**
     * Register the stylesheets for the public-facing side of the site.
     *
     * @since    1.0.0
     */
    public function enqueue_styles() {

        /**
         * This function is provided for demonstration purposes only.
         *
         * An instance of this class should be passed to the run() function
         * defined in Elementlms_Learning_Plans_Loader as all of the hooks are defined
         * in that particular class.
         *
         * The Elementlms_Learning_Plans_Loader will then create the relationship
         * between the defined hooks and the functions defined in this
         * class.
         */

        wp_enqueue_style( $this->plugin_name, plugin_dir_url( __FILE__ ) . 'css/elementlms-learning-plans-public.css', array(), $this->version, 'all' );

    }

    /**
     * Register the JavaScript for the public-facing side of the site.
     *
     * @since    1.0.0
     */
    public function enqueue_scripts() {

        /**
         * This function is provided for demonstration purposes only.
         *
         * An instance of this class should be passed to the run() function
         * defined in Elementlms_Learning_Plans_Loader as all of the hooks are defined
         * in that particular class.
         *
         * The Elementlms_Learning_Plans_Loader will then create the relationship
         * between the defined hooks and the functions defined in this
         * class.
         */

        wp_enqueue_script( $this->plugin_name, plugin_dir_url( __FILE__ ) . 'js/elementlms-learning-plans-public.js', array( 'jquery' ), $this->version, false );

    }
    /**
     * This function loads other actions for the front-end part of the plugin
     *
     * @since    1.0.1
     */
    public function other_actions() {
        $myListTable = new My_Example_List_Table();
        add_shortcode('data_table_list_transcript', array($myListTable, 'data_table_list_frontend'));
    }

}
Plugin_Public có other_actions sẽ tạo shortcode data_table_list_transcript
data_table_list_transcript hook sẽ gọi My_Example_List_Table > data_table_list_frontend
5) My_Example_List_Table

Code: Select all

<?php
/*
Plugin Name: Test List Table Example
*/

if ( ! class_exists( 'WP_List_Table' ) ) {
    require_once(ABSPATH.'wp-admin/includes/class-wp-list-table.php' );
    require_once(ABSPATH.'wp-admin/includes/screen.php' );
    require_once(ABSPATH.'wp-admin/includes/class-wp-screen.php' );
    require_once(ABSPATH.'wp-admin/includes/template.php' );
}

class My_Example_List_Table extends WP_List_Table {
    var $example_data = array(
            array( 'ID' => 1,'booktitle' => 'Quarter Share', 'author' => 'Nathan Lowell',
                   'isbn' => '978-0982514542' ),
            array( 'ID' => 2, 'booktitle' => '7th Son: Descent','author' => 'J. C. Hutchins',
                   'isbn' => '0312384378' ),
            array( 'ID' => 3, 'booktitle' => 'Shadowmagic', 'author' => 'John Lenahan',
                   'isbn' => '978-1905548927' ),
            array( 'ID' => 4, 'booktitle' => 'The Crown Conspiracy', 'author' => 'Michael J. Sullivan',
                   'isbn' => '978-0979621130' ),
            array( 'ID' => 5, 'booktitle'     => 'Max Quick: The Pocket and the Pendant', 'author'    => 'Mark Jeffrey',
                   'isbn' => '978-0061988929' ),
            array('ID' => 6, 'booktitle' => 'Jack Wakes Up: A Novel', 'author' => 'Seth Harwood',
                  'isbn' => '978-0307454355' )
        );
    function __construct(){
        global $status, $page;
            parent::__construct( array(
                'singular'  => __( 'book', 'mylisttable' ),     //singular name of the listed records
                'plural'    => __( 'books', 'mylisttable' ),   //plural name of the listed records
                'ajax'      => false        //does this table support ajax?
        ) );
        add_action( 'admin_head', array( &$this, 'admin_header' ) );
    }
    function admin_header() {
        $page = ( isset($_GET['page'] ) ) ? esc_attr( $_GET['page'] ) : false;
        if( 'my_list_test' != $page )
        return;
        echo '<style type="text/css">';
        echo '.wp-list-table .column-id { width: 5%; }';
        echo '.wp-list-table .column-booktitle { width: 40%; }';
        echo '.wp-list-table .column-author { width: 35%; }';
        echo '.wp-list-table .column-isbn { width: 20%;}';
        echo '</style>';
    }
    function no_items() {
        _e( 'No books found, dude.' );
    }
    function column_default( $item, $column_name ) {
        switch( $column_name ) {
            case 'booktitle':
            case 'author':
            case 'isbn':
                return $item[ $column_name ];
            default:
                return print_r( $item, true ) ; //Show the whole array for troubleshooting purposes
        }
    }
    function get_sortable_columns() {
        $sortable_columns = array(
            'booktitle'  => array('booktitle',false),
            'author' => array('author',false),
            'isbn'   => array('isbn',false)
        );
        return $sortable_columns;
    }
    function get_columns(){
            $columns = array(
                'cb'        => '<input type="checkbox" />',
                'booktitle' => __( 'Title', 'mylisttable' ),
                'author'    => __( 'Author', 'mylisttable' ),
                'isbn'      => __( 'ISBN', 'mylisttable' )
            );
            return $columns;
        }
    function usort_reorder( $a, $b ) {
        // If no sort, default to title
        $orderby = ( ! empty( $_GET['orderby'] ) ) ? $_GET['orderby'] : 'booktitle';
        // If no order, default to asc
        $order = ( ! empty($_GET['order'] ) ) ? $_GET['order'] : 'asc';
        // Determine sort order
        $result = strcmp( $a[$orderby], $b[$orderby] );
        // Send final sort direction to usort
        return ( $order === 'asc' ) ? $result : -$result;
    }
    function column_booktitle($item){
        $actions = array(
                    'edit'      => sprintf('<a href="?page=%s&action=%s&book=%s">Edit</a>',$_REQUEST['page'],'edit',$item['ID']),
                    'delete'    => sprintf('<a href="?page=%s&action=%s&book=%s">Delete</a>',$_REQUEST['page'],'delete',$item['ID']),
                );
        return sprintf('%1$s %2$s', $item['booktitle'], $this->row_actions($actions) );
    }
    function get_bulk_actions() {
        $actions = array(
            'delete'    => 'Delete'
        );
        return $actions;
    }
    function column_cb($item) {
        return sprintf(
            '<input type="checkbox" name="book[]" value="%s" />', $item['ID']
        );
    }
    function prepare_items() {


        $columns  = $this->get_columns();
        $hidden   = array();
        $sortable = $this->get_sortable_columns();
        $this->_column_headers = array( $columns, $hidden, $sortable );
        usort( $this->example_data, array( &$this, 'usort_reorder' ) );

        $per_page = 5;
        $current_page = $this->get_pagenum();

        $a = [array('a'=>1),array('b'=>1),array('c'=>1),array('d'=>1)];
        $found_data = [];
        $found_data = array_slice( $this->example_data, 0,$per_page );


        $total_items = count( $this->example_data );
        // only ncessary because we have sample data
        $found_data = array_slice( $this->example_data,( ( $current_page-1 )* $per_page ), $per_page );
        //$found_data = array_slice( $this->example_data, $per_page );

        $this->set_pagination_args( array(
            'total_items' => $total_items,                  //WE have to calculate the total number of items
            'per_page'    => $per_page                     //WE have to determine how many items to show on a page
        ) );
        $this->items = $found_data;
        //$this->items = $this->example_data;
    }
    /**
     * This function will display the data table listing on the front-end via a shortcode
     *
     * @return void
     */
    public function data_table_list_frontend() {

        $option = 'per_page';
        $args = array(
                'label' => 'Books',
                'default' => 4,
                'option' => 'books_per_page'
                );
        add_screen_option( $option, $args );

        $this->prepare_items();

        ?>
        <form method="post">
            <input type="hidden" name="page" value="ttest_list_table">
            <?php
                $this->search_box( 'search', 'search_id' );
                $this->display();
            ?>
        </form>
        <?php
    }
} //class
Chúc thành công !!!

Image

Post Reply