如何在自定义插件菜单页面上加载wordpress自定义表格

时间:2016-05-21 01:43:54

标签: php wordpress

为了让球滚动,我使用这个sitepoint template将一个自定义表放在一个管理选项页面上的插件中...到目前为止一直很好,但是插件的设计是为了生活在它的自己的页面...事情是我需要它存在于现有的页面上...虽然我试图将代码移动到特定的文件但它似乎根本没有。当然还有更多代码,我只是列出了在管理菜单中创建菜单页面的相关部分....所以我问如何将其添加到现有页面/操作中而不是创建新页面?

...
class SP_Plugin {

  // class instance
  static $instance;

  // customer WP_List_Table object
  public $customers_obj;

  // class constructor
  public function __construct() {
    add_filter( 'set-screen-option', [ __CLASS__, 'set_screen' ], 10, 3 );
    add_action( 'admin_menu', [ $this, 'plugin_menu' ] );
  }


  public static function set_screen( $status, $option, $value ) {
    return $value;
  }

  public function plugin_menu() {

    $hook = add_menu_page(
      'Sitepoint WP_List_Table Example',
      'SP WP_List_Table',
      'manage_options',
      'wp_list_table_class',
      [ $this, 'plugin_settings_page' ]
    );

    add_action( "load-$hook", [ $this, 'screen_option' ] );

  }


  /**
   * Plugin settings page
   */
  public function plugin_settings_page() {
    ?>
    <div class="wrap">
      <h2>WP_List_Table Class Example</h2>

      <div id="poststuff">
        <div id="post-body" class="metabox-holder columns-2">
          <div id="post-body-content">
            <div class="meta-box-sortables ui-sortable">
              <form method="post">
                <?php
                $this->customers_obj->prepare_items();
                $this->customers_obj->display(); ?>
              </form>
            </div>
          </div>
        </div>
        <br class="clear">
      </div>
    </div>
  <?php
  }

  /**
   * Screen options
   */
  public function screen_option() {

    $option = 'per_page';
    $args   = [
      'label'   => 'Records',
      'default' => 5,
      'option'  => 'customers_per_page'
    ];

    add_screen_option( $option, $args );

    $this->customers_obj = new Customers_List();
  }


  /** Singleton instance */
  public static function get_instance() {
    if ( ! isset( self::$instance ) ) {
      self::$instance = new self();
    }

    return self::$instance;
  }

}


add_action( 'plugins_loaded', function () {
  SP_Plugin::get_instance();
} );

用于初始化插件的管理页面的代码:

add_action('load_admin_faucet_page', 'plugin_settings_page');

function faucet_admin_page_container(){
require '../../../myfolder/myfile.php';
}  

从那时起,我认为它将变得如此简单:

add_action('load_admin_faucet_page', 'plugin_settings_page')

但是......没有骰子,我们在这里。

编辑1:根据要求,这是我 尝试加载myfile.php的整个受影响的代码部分(不是所有内容,只是扩展wp_list_table的类 - 我会保留操作现在的主要插件文件)...现在我只是试图将它保存在主插件文件上并将其加载到该特定页面上。

function load_admin_faucet_page(){
    add_menu_page('Faucet Settings', 'Faucet', 'manage_options', 'bitcoinfaucet-settings', 'faucet_admin_page_container', 'dashicons-welcome-view-site', 1);
}




function faucet_admin_page_container(){
require '../../myfile.php';
}  

...


add_action('admin_menu', 'load_admin_faucet_page');
add_action('load_admin_faucet_page', 'plugin_settings_page')



//allow redirection, even if my theme starts to send output to the browser
add_action('init', 'do_output_buffer');
function do_output_buffer() {
        ob_start();
}
...


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

class Customers_List extends WP_List_Table {

  /** Class constructor */
  public function __construct() {

    parent::__construct( array(
      'singular' => __( 'Record', 'sp' ), //singular name of the listed records
      'plural'   => __( 'Records', 'sp' ), //plural name of the listed records
      'ajax'     => false //does this table support ajax?
    ) );

  }


  /**
   * Retrieve customers data from the database
   *
   * @param int $per_page
   * @param int $page_number
   *
   * @return mixed
   */
  public static function get_customers( $per_page = 5, $page_number = 1 ) {

    global $wpdb;

    $sql = "SELECT * FROM table";

    if ( ! empty( $_REQUEST['orderby'] ) ) {
      $sql .= ' ORDER BY ' . esc_sql( $_REQUEST['orderby'] );
      $sql .= ! empty( $_REQUEST['order'] ) ? ' ' . esc_sql( $_REQUEST['order'] ) : ' ASC';
    }

    $sql .= " LIMIT $per_page";
    $sql .= ' OFFSET ' . ( $page_number - 1 ) * $per_page;


    $result = $wpdb->get_results( $sql, 'ARRAY_A' );

    return $result;
  }





 /**
   *  Associative array of columns
   *
   * @return array
   */
  function get_columns() {
    $columns = array(
      'cb'      => '<input type="checkbox" />',
      'id' => __( 'Id Number', 'sp' ),      
      'date' => __( 'Date', 'sp' ),
      'user'    => __( 'Address', 'sp' ),
      'amount' => __( 'Amount', 'sp'),
      'message'    => __( 'Message', 'sp' ),


    );

    return $columns;
  }


  /**
   * Columns to make sortable.
   *
   * @return array
   */
  public function get_sortable_columns() {
    $sortable_columns = array(
      'user' => array( 'user', false ),
      'date' => array( 'date', false ),
      'id' => array( 'id', true )
    );

    return $sortable_columns;
  }


  /**
   * Returns the count of records in the database.
   *
   * @return null|string
   */
  public static function record_count() {
    global $wpdb;

    $sql = "SELECT COUNT(*) FROM table";

    return $wpdb->get_var( $sql );
  }


  /** Text displayed when no customer data is available */
  public function no_items() {
    _e( 'No customers avaliable.', 'sp' );
  }


  /**
   * Render a column when no column specific method exist.
   *
   * @param array $item
   * @param string $column_name
   *
   * @return mixed
   */

  public function column_default( $item, $column_name ) {
    switch ( $column_name ) {
      case 'id':
      case 'user':
      case 'amount':
      case 'date':
      case 'message':
        return $item[ $column_name ];
      default:
        return print_r( $item, true ); //Show the whole array for troubleshooting purposes
    }
  }




  /**
   * Render the bulk edit checkbox
   *
   * @param array $item
   *
   * @return string
   */
  function column_cb( $item ) {
    return sprintf(
      '<input type="checkbox" name="my_CheckBoxes[]" value="%s" />', $item['id']

    );
  }





  /**
   * Method for name column
   *
   * @param array $item an array of DB data
   *
   * @return string
   */
  function column_name( $item ) {

    $delete_nonce = wp_create_nonce( 'sp_delete_customer' );
    $reset_nonce = wp_create_nonce( 'sp_reset_payouts' );

    $title = '<strong>' . $item['name'] . '</strong>';

    $actions = [
      'delete' => sprintf( '<a href="?page=%s&action=%s&customer=%s&_wpnonce=%s">Delete</a>', esc_attr( $_REQUEST['page'] ), 'delete', absint( $item['id'] ), $delete_nonce ),

      'reset' => sprintf( '<a href="?page=%s&action=%s&customer=%s&_wpnonce=%s">Reset</a>', esc_attr( $_REQUEST['page'] ), 'reset', absint( $item['id'] ), $reset_nonce )

    ];

    return $title . $this->row_actions( $actions );
  }




  /**
   * Returns an associative array containing the bulk action
   *
   * @return array
   */
  public function get_bulk_actions() {

    $actions = array(
      'bulk-delete' => 'Delete',
      'bulk-reset' => 'Reset'
    );

    return $actions;
  }


  /**
   * Handles data query and filter, sorting, and pagination.
   */
  public function prepare_items() {

    $this->_column_headers = $this->get_column_info();

    /** Process bulk action */
    $this->process_bulk_action();

    $per_page     = $this->get_items_per_page( 'customers_per_page', 5 );
    $current_page = $this->get_pagenum();
    $total_items  = self::record_count();

    $this->set_pagination_args( [
      '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 = self::get_customers( $per_page, $current_page );
  }



  /**
   * Delete a customer record.
   *
   * @param int $id customer ID
   */
  public static function delete_customer( $id ) {
    global $wpdb;

    $wpdb->delete(
      "table",
      array( 'id' => $id ),
      array('%d' )
    );
  }


  /**
   * Reset Message To Null.
   *
   * @param int $id customer ID
   */
  public static function reset_record( $id ) {
    global $wpdb;

    $wpdb->update(
      "table",
      array('message' => NULL),
      array('id' => $id )
    );
  }



  public function process_bulk_action() {

    //Detect when a bulk action is being triggered...
     if ( 'delete' === $this->current_action()){

      // In our file that handles the request, verify the nonce.
      $nonce = esc_attr( $_REQUEST['_wpnonce'] );

      if ( ! wp_verify_nonce( $nonce, 'sp_delete_customer' ) ) {
        die( 'Go get a life script kiddies' );
      }
      else {
        self::delete_customer( absint( $_GET['customer'] ) );
        wp_redirect( esc_url( add_query_arg() ) );
        exit;
      }

}
    //Detect when a Reset is being triggered...
     if ( 'reset' === $this->current_action()){

      // In our file that handles the request, verify the nonce.
      $nonce = esc_attr( $_REQUEST['_wpnonce'] );

      if ( ! wp_verify_nonce( $nonce, 'sp_reset_payouts' ) ) {
        die( 'Go get a life script kiddies' );
      }
      else {
        self::reset_record( absint ( $_GET['customer']));
        wp_redirect( esc_url( add_query_arg() ) );
        exit;
      }
}





    // // If the delete bulk action is triggered
    if ( ( isset( $_POST['action'] ) && $_POST['action'] == 'bulk-delete' )
         || ( isset( $_POST['action2'] ) && $_POST['action2'] == 'bulk-delete' )
    ) {

      $delete_ids = esc_sql( $_POST['my_CheckBoxes'] );

      // loop over the array of record IDs and delete them
      foreach ( $delete_ids as $id ) {
        self::delete_customer( $id );
      }
      wp_redirect( esc_url( add_query_arg() ) );
      exit;
    }


    //If the delete bulk action is triggered
    if ( ( isset( $_POST['action'] ) && $_POST['action'] == 'bulk-reset' )
         || ( isset( $_POST['action2'] ) && $_POST['action2'] == 'bulk-reset' )
    ) {

      $reset_ids = esc_sql( $_POST['my_CheckBoxes'] );

      // loop over the array of record IDs and delete them
      foreach ( $reset_ids as $id ) {
        self::reset_record( $id );

      }

      wp_redirect( esc_url( add_query_arg() ) );
      exit;
    }


  }

}





class SP_Plugin {

  // class instance
  static $instance;

  // customer WP_List_Table object
  public $customers_obj;

  // class constructor
  public function __construct() {
    add_filter( 'set-screen-option', [ __CLASS__, 'set_screen' ], 10, 3 );
    add_action( 'admin_menu', [ $this, 'plugin_menu' ] );
  }


  public static function set_screen( $status, $option, $value ) {
    return $value;
  }

  public function plugin_menu() {

    $hook = add_menu_page(
      'Sitepoint WP_List_Table Example',
      'SP WP_List_Table',
      'manage_options',
      'wp_list_table_class',
      [ $this, 'plugin_settings_page' ]
    );

    add_action( "load-$hook", [ $this, 'screen_option' ] );

  }


  /**
   * Plugin settings page
   */
  public function plugin_settings_page() {
    ?>
    <div class="wrap">
      <h2>WP_List_Table Class Example</h2>

      <div id="poststuff">
        <div id="post-body" class="metabox-holder columns-2">
          <div id="post-body-content">
            <div class="meta-box-sortables ui-sortable">
              <form method="post">
                <?php
                $this->customers_obj->prepare_items();
                $this->customers_obj->display(); ?>
              </form>
            </div>
          </div>
        </div>
        <br class="clear">
      </div>
    </div>
  <?php
  }

  /**
   * Screen options
   */
  public function screen_option() {

    $option = 'per_page';
    $args   = [
      'label'   => 'Records',
      'default' => 5,
      'option'  => 'customers_per_page'
    ];

    add_screen_option( $option, $args );

    $this->customers_obj = new Customers_List();
  }


  /** Singleton instance */
  public static function get_instance() {
    if ( ! isset( self::$instance ) ) {
      self::$instance = new self();
    }

    return self::$instance;
  }

}


add_action( 'plugins_loaded', function () {
  SP_Plugin::get_instance();
} );

0 个答案:

没有答案