I've developed Meta Box plugin in a Custom Post as per this playlist. (I made some custermizations to that) In here he created a custom post using the plugin and do all the metabox operation on that relevant post.
It works fine. But my requirement is to display this meta box in a page.
Here is my code.
metabox.php (plugin code)
<?php
function wpl_owt_custom_init_cpt(){
$args = array(
'public' => true,
'label' => 'Books',
'supports' => array('title' , 'editor' , 'author' , 'thumbnail' , 'excerpt' , 'comments')
);
register_post_type('book' , $args);
}
add_action('init', 'wpl_owt_custom_init_cpt');
function wpl_owt_register_metabox_cpt(){
//custom post type
add_meta_box("owt-cpt-id" , "Contact Details" , "wpl_owt_book_function" , "book" , "normal" , "high");
}
add_action("add_meta_boxes_book" , "wpl_owt_register_metabox_cpt");
/**********Callback function for metabox at custom post type book******************/
function wpl_owt_book_function( $post ) {
//echo "<p>Custom metabox for custom post type</p>";
define("_FILE_", "_FILE_");
wp_nonce_field( basename(_FILE_), "wp_owt_cpt_nonce");
echo "<label for='txtPhoneNum'>Phone</label><br>";
$phone_num = get_post_meta($post->ID, "telNo" , true);
echo "<input type ='tel' name = 'txtPhoneNum' value = '" . $phone_num . "'' placeholder = 'Phone Number' /><br><br>";
echo "<label for='txtEmail'>Email</label><br>";
$email = get_post_meta($post->ID, "email" , true);
echo "<input type ='email' name = 'txtEmail' value = '" . $email . "'' placeholder = 'Email Address' /><br><br>";
echo "<label for='txtHours'>Hours of Operation</label><br>";
$hours = get_post_meta($post->ID, "hourofOps" , true);
echo "<input type ='text' name = 'txtHours' value = '" . $hours . "'' placeholder = 'Working Hours' /><br><br>";
}
add_action("save_post" , "wpl_owt_save_metabox_data" , 10 , 2);
function wpl_owt_save_metabox_data($post_id, $post){
//verify nonce
if(!isset($_POST['wp_owt_cpt_nonce']) || !wp_verify_nonce($_POST['wp_owt_cpt_nonce'], basename(_FILE_))){
return $post_id;
}
//verify slug value
$post_slug = "book";
if($post_slug != $post->post_type){
return;
}
//save value to db filed
$pub_tel = '';
if(isset($_POST['txtPhoneNum'])){
$pub_tel = sanitize_text_field($_POST['txtPhoneNum']);
}
else{
$pub_tel = '';
}
update_post_meta($post_id, "telNo", $pub_tel);
$pub_email = '';
if(isset($_POST['txtEmail'])){
$pub_email = sanitize_text_field($_POST['txtEmail']);
}
else{
$pub_email = '';
}
update_post_meta($post_id, "email", $pub_email);
$pub_hours = '';
if(isset($_POST['txtHours'])){
$pub_hours = sanitize_text_field($_POST['txtHours']);
}
update_post_meta($post_id, "hourofOps", $pub_hours);
}
?>
Can someone give me a solution to display the metabox in a page instead of a post.
please have a look as below:
<?php
function add_custom_meta_box()
{
$screens = ['page'];
foreach ($screens as $screen) {
add_meta_box(
'meta_box_id', // Unique ID
'Custom Meta Box Title', // Box title
'callback_function', // Content callback, must be of type callable
$screen // Post type
);
}
}
add_action('add_meta_boxes', 'add_custom_meta_box');
function callback_function($post)
{
/*Do something*/
}
I hope it would help you out
Replace
function wpl_owt_custom_init_cpt(){
$args = array(
'public' => true,
'label' => 'Books',
'supports' => array('title' , 'editor' , 'author' , 'thumbnail' , 'excerpt' , 'comments')
);
register_post_type('book' , $args);
}
add_action('init', 'wpl_owt_custom_init_cpt');
with this
add_action('add_meta_boxes', 'wpl_owt_register_metabox_cpt');
function wpl_owt_register_metabox_cpt()
{
global $post;
if(!empty($post))
{
$pageTemplate = get_post_meta($post->ID, '_wp_page_template', true);
if($pageTemplate == 'page-contact.php' )
{
add_meta_box(
'owt-cpt-id', // $id
'Contact Details', // $title
'wpl_owt_book_function', // $callback
'page', // $page
'normal', // $context
'high'); // $priority
}
}
}
and replace this
$post_slug = "book";
if($post_slug != $post->post_type){
return;
}
with this.
$post_slug = "page";
if($post_slug != $post->post_type){
return;
}
Hope this will work out.
Related
I want to add a phone number field in both Posts and Woocommerce. But I want just to show the phone number in the admin panel, not the front end.
I used this link from #mujuonly to do so.
Everything is Ok. I mean the phone number field is added to the comment form in posts and WooCommerce. The phone number is shown in the comment list of posts in the admin panel, The only problem is that the phone number is not shown in the WooCommerce comment list in the backend. Can anyone help me?
This is the code
// Add phone number field
function add_review_phone_field_on_comment_form() {
echo '<p class="comment-form-phone uk-margin-top"><label for="phone">' . __( 'Phone', 'text-domain' ) . '</label><span class="required">*</span><input class="uk-input uk-width-large uk-display-block" type="text" name="phone" id="phone"/></p>';
}
add_action( 'comment_form_logged_in_after', 'add_review_phone_field_on_comment_form' );
add_action( 'comment_form_after_fields', 'add_review_phone_field_on_comment_form' );
// Save phone number
add_action( 'comment_post', 'save_comment_review_phone_field' );
function save_comment_review_phone_field( $comment_id ){
if( isset( $_POST['phone'] ) )
update_comment_meta( $comment_id, 'phone', esc_attr( $_POST['phone'] ) );
}
function print_review_phone( $id ) {
$val = get_comment_meta( $id, "phone", true );
$title = $val ? '<strong class="review-phone">' . $val . '</strong>' : '';
return $title;
}
// Print phone number - remove if not needed to show in front end
/*
add_action('woocommerce_review_before_comment_meta', 'get_comment_phone' );
function get_comment_phone($comment){
echo print_review_phone($comment->comment_ID);
}
*/
// List in admin list table
add_filter('manage_edit-comments_columns', 'my_add_comments_columns');
function my_add_comments_columns($my_cols) {
$temp_columns = array(
'phone' => 'Phone'
);
$my_cols = array_slice($my_cols, 0, 3, true) + $temp_columns + array_slice($my_cols, 3, NULL, true);
return $my_cols;
}
add_action('manage_comments_custom_column', 'my_add_comment_columns_content', 10, 2);
function my_add_comment_columns_content($column, $comment_ID) {
global $comment;
switch ($column) :
case 'phone' : {
echo get_comment_meta($comment_ID, 'phone', true);
break;
}
endswitch;
}
add_filter('woocommerce_product_reviews_table_columns', 'woocommerce_product_reviews_table_columns');
function woocommerce_product_reviews_table_columns($my_cols) {
$my_cols['phone'] = __('Phone', 'woocommerce');
return $my_cols;
}
add_filter('woocommerce_product_reviews_table_column_phone_content', 'woocommerce_product_reviews_table_column_phone_content', 10, 2);
function woocommerce_product_reviews_table_column_phone_content($output, $item) {
$phone = get_comment_meta($item->comment_ID, 'phone', true);
return $phone;
}
Please try these two hooks for the WooCommerce reviews table additional columns
The data can not be saved
I am trying to make settings pages for each custom post type so that I can insert specified posts to archive pages of those post types.
I made this settings page using Wordpress Settings API.
But even after I input some values and clicked the save button.
The data can not be saved on DB and no data are displayed in these forms after refreshing the page.
I also confirmed the database has not created a record of the data. 'post_type_top' should be the option_name in DB.
Here is my class file to implement this settings page.
Does anyone figure out what kind of error this has?
I am temporarily commented out some sanitization process in my code.
<?php
class CreateSettingsPage
{
private $options;
private $post_type;
private $settings = array();
public function __construct()
{
add_action('admin_menu', array($this, 'add_settings_page'));
add_action('admin_init', array($this, 'settings_page_init'));
$this->post_type = $_GET['post_type'];
$this->settings = array(
'page' => 'post-type-settings-admin',
'page_title' => __('Post Type Settings', 'tcd-w'),
'page_slug' => 'post_type_top',
'option_name' => 'post_type_top',
'option_group' => 'post_type_top_option_group',
'sections' => array(
array(
'id_prefix' => 'post_type_settings',
'section_title' => __('Add Links to Post Type Top', 'tcd-w'),
'section_info' => __('Please input category page slug and post ids which are added to the post type top page', 'tcd-w'),
'fields' => array(
array(
'field_id' => 'input_category_slug',
'field_title' => 'input_category_slug',
'type' => 'input',
),
array(
'field_id' => 'input_post_ids',
'field_title' => 'input_post_ids',
'type' => 'input',
),
),
),
),
);
}
public function add_settings_page()
{
//put a menu within all custom types if apply
$post_types = get_post_types();
foreach ($post_types as $post_type) {
//check if there are any taxonomy for this post type
$post_type_taxonomies = get_object_taxonomies($post_type);
foreach ($post_type_taxonomies as $key => $taxonomy_name) {
$taxonomy_info = get_taxonomy($taxonomy_name);
if (empty($taxonomy_info->hierarchical) || $taxonomy_info->hierarchical !== TRUE)
unset($post_type_taxonomies[$key]);
}
if (count($post_type_taxonomies) == 0)
continue;
if ($post_type == 'post') {
add_submenu_page('edit.php', $this->settings['page_title'], $this->settings['page_title'], 'manage_options', $this->settings['page_slug'] . '_' . $post_type, array($this, 'create_admin_page'));
} elseif ($post_type == 'attachment') {
add_submenu_page('upload.php', $this->settings['page_title'], $this->settings['page_title'], 'manage_options', $this->settings['page_slug'] . '_' . $post_type, array($this, 'create_admin_page'));
} else {
add_submenu_page('edit.php?post_type=' . $post_type, $this->settings['page_title'], $this->settings['page_title'], 'manage_options', $this->settings['page_slug'] . '_' . $post_type, array($this, 'create_admin_page'));
}
}
}
public function create_admin_page()
{
$this->options = get_option($this->settings['option_name']); ?>
<div class="wrap">
<h2><?php echo $this->settings['page_title']; ?></h2>
<p></p>
<?php settings_errors(); ?>
<form method="post" action="options.php">
<?php
settings_fields($this->settings['option_group']);
do_settings_sections($this->settings['page']);
submit_button();
?>
</form>
</div>
<?php }
public function settings_page_init()
{
register_setting(
$this->settings['option_group'], // option_group
$this->settings['sections']['option_name'],
array($this, 'sanitize') // sanitize_callback
);
foreach ($this->settings['sections'] as $section) {
add_settings_section(
$section['id_prefix'] . '_section', // id
$section['section_title'], // title
array($this, 'section_info'), // callback
$this->settings['page'] // page
);
foreach ($section['fields'] as $field) {
add_settings_field(
$field['field_id'] . '_' . $this->post_type, // id
$field['field_title'], // title
array($this, $field['type']), // callback
$this->settings['page'], // page
$section['id_prefix'] . '_section', // section
$field
);
}
}
}
public function sanitize($input)
{
return $input;
// $sanitary_values = array();
// if (isset($input['custom_banner_url_0'])) {
// $sanitary_values['custom_banner_url_0'] = sanitize_text_field($input['custom_banner_url_0']);
// }
// if (isset($input['custom_banner_img_src_1'])) {
// $sanitary_values['custom_banner_img_src_1'] = esc_textarea($input['custom_banner_img_src_1']);
// }
// return $sanitary_values;
}
public function section_info()
{
echo $section['section_info'];
}
public function input($field)
{
printf(
'<input class="regular-text" type="text" name="%s[%s]" id="%s" value="%s">',
$this->settings['option_name'],
$field['field_id'] . '_' . $this->post_type,
$field['field_id'] . '_' . $this->post_type,
isset($this->options[$field['field_id'] . '_' . $this->post_type]) ? esc_attr($this->options[$field['field_id'] . '_' . $this->post_type]) : ''
);
}
public function textarea($field)
{
printf(
'<textarea class="large-text" rows="5" name="%s[%s]" id="%s">%s</textarea>',
$this->settings['option_name'],
$field['field_id'],
$field['field_id'],
isset($this->options[$field['field_id']]) ? esc_attr($this->options[$field['field_id']]) : ''
);
}
}
if (is_admin()) $post_type_settings = new CreateSettingsPage();
I have a plugin that adds a meta box with file upload form, the plugin works perfectly, displays the link of the image in the meta box (View Image), load the file, and once published the post, it views in the theme. (in the example I'm using an image file):
<?php
/* Plugin Name: Custom Meta Upload Template*/
add_action('post_edit_form_tag', 'post_edit_form_tag');
function post_edit_form_tag() {
echo ' enctype="multipart/form-data"';
}
function custom_upload() {
add_meta_box( 'meta_upload', __( 'Upload Image', 'meta_upload_domain' ),'meta_upload_callback', 'post' );}
add_action( 'add_meta_boxes', 'custom_upload' );
function meta_upload_callback( $post ) {
global $post;
$custom = get_post_custom($post->ID);
$download_image01 = get_post_meta($post->ID, '_image01', true);
echo '<p><label for="document_file">Upload document:</label><br />';
echo '<input type="file" name="document_file" id="document_file" /></p>';
echo '</p>';
if(!empty($download_image01) && $download_image01 != '0') {
echo '<p>View Image</p>';
}
}
function meta_upload_save( $post_id ) {
global $post;
if(strtolower($_POST['post_type']) === 'page') {
if(!current_user_can('edit_page', $post_id)) {
return $post_id;
}
}
else {
if(!current_user_can('edit_post', $post_id)) {
return $post_id;
}
}
if(!empty($_FILES['document_file'])) {
$file = $_FILES['document_file'];
$upload = wp_handle_upload($file, array('test_form' => false));
if(!isset($upload['error']) && isset($upload['file'])) {
$title = $file['name'];
$ext = strrchr($title, '.');
$title = ($ext !== false) ? substr($title, 0, -strlen($ext)) : $title;
$attachment = array(
'post_mime_type' => 'image',
'post_title' => addslashes($title),
'post_content' => '',
'post_status' => 'inherit',
'post_parent' => $post->ID
);
$attach_key = '_image01';
$attach_id = wp_insert_attachment($attachment, $upload['file']);
$existing_download = (int) get_post_meta($post->ID, $attach_key, true);
if(is_numeric($existing_download)) {
wp_delete_attachment($existing_download);
}
update_post_meta($post->ID, $attach_key, $attach_id);
}
}
}
add_action( 'save_post', 'meta_upload_save' );
and he called the file in the theme:
<?php
$download_image01 = get_post_meta($post->ID, '_image01', true);
if(!empty($download_image01) && $download_image01 != '0') { ?>
<div class="section-content">
<img src="<?php echo wp_get_attachment_url($download_image01); ?>" alt="" />
</div>
<?php }?>
I repeat, the plugin works, but the problem is that I can not place a button or a checkbox that deletes the file when, for example, I want to edit the post, and delete the file, and of course the link "View Image" disappears
Any idea!!
Whenever you want to edit these fields echo the value of the custom fields look like this...
<input type="" value="<img src="<?php echo wp_get_attachment_url($download_image01); ?>" alt="" />">
When you edit the post it's get the value and show the uploaded image's to you.
I don't know if that can help, but I use this code to exclude Attachment when I delete a Custom Post:
add_action('before_delete_post', 'delete_all_attached_media');
function delete_all_attached_media($post_id)
{
if (get_post_type($post_id) == "your-custom-post-type") {
$attachments = get_attached_media('', $post_id);
foreach ($attachments as $attachment) {
wp_delete_attachment($attachment->ID, 'true');
}
}
}
i'm searching for a way to display the modified date of a custom field / meta box. until now, i only know how to echo
the_modified_date('l, j.n.Y');
but this one only works with the entire post.
i'am using a meta_box for additional pdf files uploading, code:
<?php class PDF_Metabox_id1 {
function __construct() {
add_action( 'post_mime_types', array( $this, 'pdf_mime_type_id1' ) );
add_action( 'add_meta_boxes', array( $this, 'admin_scripts_id1' ), 5 );
add_action( 'add_meta_boxes', array( $this, 'metabox_add_id1' ) );
add_action( 'save_post', array( $this, 'pdf_save_postdata_id1') );
add_action( 'wp_ajax_refresh_pdf', array( $this, 'refresh_pdf_id1' ) ); }
function pdf_mime_type_id1() {
$post_mime_types['application/pdf'] = array( __( 'PDFs' ), __( 'Manage PDFs' ), _n_noop( 'PDF <span class="count">(%s)</span>', 'PDFs <span class="count">(%s)</span>' ) );
return $post_mime_types;
}
function admin_scripts_id1() {
wp_register_script( 'pdf_metabox_js', get_stylesheet_directory_uri() . '/js/pdf_metabox.js' );
}
function metabox_add_id1() {
$post_types = array( 'myposttype','anotherposttype' );
$context = 'normal'; $priority = 'low';
foreach( $post_types as $post_type ) {
add_meta_box( 'pdf_metabox_id1', __( 'PDF Box 1', 'pdf_metabox_id1' ), array( $this, 'pdf_metabox_id1' ), $post_type, $context, $priority );
wp_enqueue_media();
wp_enqueue_script( 'pdf_metabox_js' );
}
}
function pdf_metabox_id1( $post ) {
$original_post = $post; echo $this->pdf_metabox_html_id1( $post->ID ); $post = $original_post;
}
function pdf_item_id1( $id ) {
if(!$id) return; $pdf_url = esc_url_raw(wp_get_attachment_url($id)); $pdf = $pdf_url; return $pdf;
}
function pdf_metabox_html_id1( $post_id ) {
$current_value = ''; $post_meta = get_post_custom($post_id);
if( isset($post_meta['pdf_id_id1'][0] ) ) $current_value = $post_meta['pdf_id_id1'][0];
$return = ''; wp_nonce_field( plugin_basename( __FILE__ ), 'pdf_noncename' );
$return .= '<p>';
$return .= '<a title="'.__( 'PDF', 'pdf_metabox_id1' ).'" class="button button-primary insert-pdf-button" id="insert_pdf_button_id1" href="#" style="float:left">'.__( 'Upload / editiere PDF', 'pdf_metabox_id1' ).'</a><span id="pdf_spinner_id1" class="spinner" style="float:left"></span></p>';
$return .= '<div style="clear:both"></div>';
$return .= '<input type="hidden" name="pdf_id_id1" id="pdf_id_id1" value="'.$current_value.'">';
$return .= '<div style="clear:both"></div>';
$return .= '<div id="pdf_wrapper_id1">';
$pdf = $this->pdf_item_id1( $current_value ); if( empty( $pdf ) ) {
$return .= '<p>Diesem Feld ist kein PDF hinterlegt.</p>'; } else {
$return .= '<br />URL des PDF:<br /> ';
$return .= $pdf; }
$return .= '</div>';
return $return;
}
function pdf_save_postdata_id1($post_id){
if ( isset($_POST['post_type']) && 'post' == $_POST['post_type'] ) {
if ( !current_user_can( 'edit_post', $post_id ) ) return; } if ( !isset( $_POST['pdf_noncename'] ) || ! wp_verify_nonce( $_POST['pdf_noncename'], plugin_basename( __FILE__ ) ) ) return;
if(isset($_POST['pdf_id_id1']) ): update_post_meta($post_id, 'pdf_id_id1', sanitize_text_field( $_POST['pdf_id_id1'] ) );
else: if (isset($post_id)) {
delete_post_meta($post_id, 'pdf_id_id1'); }
endif;
}
function refresh_pdf_id1() {
if(isset($_POST['id'])){
$item = $_POST['id'];
if($item != '' && $item !=0){
$pdf = $this->pdf_item_id1( $item );
$ret = array();
if( !empty( $pdf ) ) {$ret['success'] = true;
$ret['pdf'] = $pdf; } else {
$ret['success'] = false; } } else {
$ret['success'] = true; $ret['pdf'] = ''; } } else {
$ret['success'] = false; } echo json_encode( $ret ); die();
}
}
$PDF_Metabox_id1 = new PDF_Metabox_id1();
in my theme i'm using:
$post_meta_id1 = get_post_custom(get_the_ID());
$pdf_id_id1 = $post_meta_id1['pdf_id_id1'][0];
$pdf_url_id1 = wp_get_attachment_url($pdf_id_id1);
...and now i want to display the modified date of this field. any ideas?
As per the comment
how do i save the modified date of this custom field and how do i get it?
You may need to check every custom field in loop one by one if any of custom fields doesnot matched with the current post data then save a new custom field to post_meta. then retrieve in your template/page.
Just an idea:
<?php
function attributes_save_postdata( $post_id ) {
$postcustom = get_post_custom( $post_id );
$is_modified = false;
foreach ( $postcustom as $key => $val ) {
var_dump( $val );
// check your post custom values and
$getpostmeta = get_post_meta( $post_id, 'your_meta_key', true );
// if database value ($getpostmeta) not equal to current post value($_POST['your_meta_key'])
if ( $getpostmeta != $_POST['your_meta_key'] ) {
$is_modified = true;
// if found any custom field updated set $modified = true
}
}
// if found any custom field updated add or update new date and time
if ( $is_modified ) {
$date = date( 'Y-m-d h:i:s' ); // example : 2016-02-02 12:00:00 current date and time
update_post_meta( $post_id, '_modifieddate', $date );
}
}
add_action( 'save_post', 'attributes_save_postdata' );
Then in your theme. get modified date.
$post_id = get_the_ID();
$getpostmeta = get_post_meta( $post_id, 'your_meta_key', true );
I think that wordpress built-in function about this would help you out even for the custom fields.
<p>Last modified: <?php the_modified_time(); ?></p>
I've been working with the wp_list_table class and creating my custom theme pages with add/edit/delete features on the row options. The problem i am having is with the bulk actions. The row actions are working just fine. Now here is where it gets weird.
If I am looking at my table in admin and I select the checkbox on a few rows, switch to bulk-delete action, then hit apply, I will not get any post data for those checkboxes. What I mean by that is the checkboxes are named as an array bulk-delete[] in html. and if I do a print_r($_request); the bulk-delete key is no present.
Now when I select a few checkboxes, and this time NOT switch to bulk-delete I just leave it saying "Bulk Actions", then hit apply, I will get the bulk-delete array but all the keys are empty.
For me totally freaking bazaar. But I am sure there is something really stupid that I missed. So here is the class in it's entirety. Please let me know what I missed.
[a secondary issue - I'd like to also show an "Country has been added" success message. Could you guys point me in the right direction for knowledge to read up on that]
Thanks in advance.
<?php
class country_class {
var $page_name = "lp-manage-countries";
public function __construct(){
//make sure the wp_list_table class has been loaded
if (!class_exists('WP_List_Table')) {
require_once(ABSPATH . 'wp-admin/includes/class-wp-list-table.php');
}
add_action( 'admin_post_add_country', array( $this, 'lp_admin_add_country') );
add_filter('set-screen-option', array( $this, 'lp_save_screen_options') , 10, 3);
//add_action( 'admin_post_bulk_action', array( $this, 'process_bulk_action') );
}
/**
* Sets the screen options up for table paging
*/
public function lp_screen_options() {
$lp_manage_countries_page = "toplevel_page_" . $this->page_name;
$screen = get_current_screen();
// get out of here if we are not on our settings page
if(!is_object($screen) || $screen->id != $lp_manage_countries_page)
return;
$args = array(
'label' => __('Countries per page'),
'default' => 25,
'option' => 'countries_per_page'
);
add_screen_option( 'per_page', $args );
}
/**
* Saves the screen option to the object class
*/
function lp_save_screen_options($status, $option, $value) {
if ( 'countries_per_page' == $option ) return $value;
return $status;
}
/**
* Installs the page and screen options
*/
public function install_countries_page(){
//Add the screen options first
add_action("load-toplevel_page_" . $this->page_name, array( $this, "lp_screen_options") );
add_menu_page('LP Countries', 'LP Countries', 'manage_options', 'lp-manage-countries', array($this, 'show_country_page'));
}
public function lp_admin_add_country(){
global $wpdb;
if( isset( $_REQUEST['country_name'] ) and !empty( $_REQUEST['country_name'] )){
$result = $wpdb->insert(
'countries',
array(
'name' => $_REQUEST['country_name']
)
);
if( $result !== false ){
wp_redirect(admin_url("admin.php?page=" . $this->page_name) );
exit;
}
}
}
/**
* Displays the page data
*/
public function show_country_page(){
if( isset( $_GET['action']) && ( $_REQUEST['action'] == "add" || $_REQUEST['action'] == "edit" )){
echo "<div class='wrap'>
<h1>Add Country</h1>
<form action='" . admin_url("admin-post.php", "http") . "' method='post'>
<input type=\"hidden\" name=\"action\" value=\"add_country\">
<table class=\"form-table\">
<tbody>
<tr>
<th scope=\"row\"><label for='country_name' xmlns=\"http://www.w3.org/1999/html\">Country Name:</label></th>
<td><input id='country_name' required class='regular-text type='text' value='' name='country_name'></input></td>
</tr>
</tbody>
</table>
<p class='submit'>
<input id='submit' class='button button-primary' type='submit' value='Save Country' name='submit'></input>
</p>
</form>";
} else {
echo "<div class=\"wrap\">
<h1>Manage Countries<a class=\"page-title-action\" href=\"".admin_url("admin.php?page=".$this->page_name."&action=add")."\">Add New</a></h1>
<form method='post'>";
//echo "<input type=\"hidden\" name=\"action\" value=\"bulk_action\">";
//Prepare Table of elements
$categories_list_table = new category_list_table();
$categories_list_table->prepare_items();
//Table of elements
$categories_list_table->display();
echo "</form>";
}
}
/**
* Creates the database for this page
*/
public function create_countries_table(){
global $wpdb;
$charset = $wpdb->get_charset_collate();
$sql = "CREATE TABLE IF NOT EXISTS `countries` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(45) NOT NULL,
`parent_id` int(11) DEFAULT NULL,
`image` varchar(45) DEFAULT NULL,
PRIMARY KEY (`id`)
) $charset; ";
$wpdb->query( $sql );
}
/**
* removes the page database when uninstalled
*/
public function drop_countries_table(){
global $wpdb;
$sql = "DROP TABLE `countries`;";
$wpdb->query($sql);
}
}
class category_list_table extends WP_List_Table {
public function __construct(){
parent::__construct( array(
'singular' => 'Country',
'plural' => 'Countries',
'ajax' => false)
);
}
public function get_columns(){
return $columns = array(
'cb' => '<input name="bulk-delete[]" type="checkbox" />',
'name' => __('Name'),
'parent_id' => __('Parent ID'),
'image' => __('Image')
);
}
function column_name($item) {
// create a nonce
$delete_nonce = wp_create_nonce( 'lp_delete_country' );
$edit_nonce = wp_create_nonce( 'lp_delete_country' );
$actions = array(
'edit' => sprintf('Edit', $_REQUEST['page'], 'edit', $item['id'], $edit_nonce),
'delete' => sprintf('Delete', $_REQUEST['page'], 'delete', $item['id'], $delete_nonce),
);
return sprintf('%1$s %2$s', $item['name'], $this->row_actions($actions) );
}
public function get_sortable_columns(){
return $sortable = array(
'id' => array('id',false),
'name' => array('name',false),
'parent_id' => array('parent_id', false),
'image' => array('image', false)
);
}
public function get_hidden_columns( ){
$screen = get_current_screen();
if ( is_string( $screen ) )
$screen = convert_to_screen( $screen );
return (array) get_user_option( 'manage' . $screen->id . 'columnshidden' );
}
public function prepare_items(){
global $wpdb, $_wp_column_headers;
$screen = get_current_screen();
/** Process bulk action */
$this->process_bulk_action();
/* Prepare the query */
$query = "SELECT * FROM `countries`";
/* Order Parameters */
$orderby = !empty($_GET["orderby"]) ? mysql_real_escape_string($_GET["orderby"]) : 'ASC';
$order = !empty($_GET["order"]) ? mysql_real_escape_string($_GET["order"]) : '';
if(!empty($orderby) & !empty($order)){ $query.=' ORDER BY '.$orderby.' '.$order; }
/* Pagination Params */
//Number of elements in your table?
$totalitems = $wpdb->query($query); //return the total number of affected rows
//How many to display per page?
$perpage = get_user_meta( get_current_user_id() , 'countries_per_page', true);
if( empty($perpage)){
$perpage = 25;
}
//Which page is this?
$paged = !empty($_GET["paged"]) ? mysql_real_escape_string($_GET["paged"]) : '';
//Page Number
if(empty($paged) || !is_numeric($paged) || $paged<=0 ){ $paged=1; }
//How many pages do we have in total?
$totalpages = ceil($totalitems/$perpage);
//adjust the query to take pagination into account
if(!empty($paged) && !empty($perpage)){
$offset=($paged-1)*$perpage;
$query.=' LIMIT '.(int)$offset.','.(int)$perpage;
}
/* Register pagination */
$this->set_pagination_args( array(
"total_items" => $totalitems,
"total_pages" => $totalpages,
"per_page" => $perpage
)
);
/* register the columns */
$columns = $this->get_columns();
$_wp_column_headers[$screen->id]=$columns;
/* Get the items */
$this->items = $wpdb->get_results($query, 'ARRAY_A');
$hidden_columns = $this->get_hidden_columns();
$sortable_columns = $this->get_sortable_columns();
parent::get_column_info();
$this->_column_headers = array( $columns, $hidden_columns, $sortable_columns);
}
public function column_default($item, $column_name) {
//return $item[$column_name];
switch ( $column_name ) {
case 'cb':
case 'name':
case 'parent_id':
case 'image':
return $item[ $column_name ];
default:
return $item[ $column_name ];
}
}
function no_items() {
_e( 'No Countries Found.' );
}
function column_cb( $item ) {
return sprintf(
'<input type="checkbox" name="bulk-delete[]" value="%s" />', $item['ID']
);
}
public function get_bulk_actions() {
$actions = [
'bulk-delete' => 'Delete'
];
return $actions;
}
public function process_bulk_action() {
$action = $this->current_action();
echo "action is [" . $action . "]";
if( !empty( $action ) ){
switch ($action){
case 'delete':
// In our file that handles the request, verify the nonce.
$nonce = esc_attr( $_REQUEST['_wpnonce'] );
if ( ! wp_verify_nonce( $nonce, 'lp_delete_country' ) ) {
die( 'Go get a life script kiddies' );
} else {
echo " running delete";
self::delete_country( absint( $_GET['country'] ) );
wp_redirect( esc_url( add_query_arg() ) );
exit;
}
case 'edit':
echo "we should be editing";
case 'bulk-delete':
// If the delete bulk action is triggered
echo "we triggered a bulk delete";
echo "<pre>";
print_r( $_REQUEST );
echo "</pre>";
if ( !empty( $_POST['bulk-delete'] ) ) {
$delete_ids = esc_sql( $_POST['bulk-delete'] );
// loop over the array of record IDs and delete them
foreach ( $delete_ids as $id ) {
$this->delete_country( $id );
}
wp_redirect( esc_url( add_query_arg() ) );
exit;
} else {
echo "Fucking empty";
}
default:
echo "<pre>";
print_r( $_REQUEST );
echo "</pre>";
//quietly exit;
}
} else {
echo "<pre>";
print_r( $_REQUEST );
echo "</pre>";
}
}
function delete_country( $id ) {
global $wpdb;
$wpdb->delete(
"countries",
[ 'id' => $id ]
);
}
}