The data in my custom settings page can't be saved - php

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();

Related

Can't save option of a media upload file using SettingsApi form worpdress

I am new into settings api , but still can't find much about media uploader from wp.
I have followed a tutorial but I am stuck at the point where I cannot save the image src into option.
Im sorry in advance for writting this much code , I don't know how I can reproduce my problem and I wanna cover all the aspects for a good answer. I will provide a image as well for a visual view.
Thank you.
Image: https://prnt.sc/6p9gfxc51FDA
AdminClass.php
public $settings; // class that builds the fields oop;
public $callbacks; // class that handle callbacks;
public function register() {
// instantiate classes;
$this->settings = new SettingsApi();
$this->callbacks = new AdminCallbacks();
}
public function setFields(){
$args = array(
array(
'id' => 'promo_image1',
'title' => 'Promotional Image',
'callback' => array( $this->callbacks, 'ss_PromoImage' ),
'page' => SS_PLUGIN,
'section' => 'ss_options_zone',
'args' => array(
'label_for' => 'promo_image1',
'class' => 'ss_image_field'
)
)
);
$this->settings->setFields( $args );
}
SettingsApi
public $settings = array();
public $fields = array();
public function registerCustomFields(){
// add setting
foreach ( $this->settings as $setting ):
register_setting(
$setting["option_group"],
$setting["option_name"],
( isset( $setting["callback"] ) ? $setting["callback"] : '' )
);
endforeach;
// add settings field
foreach ( $this->fields as $field ):
add_settings_field(
$field["id"],
$field["title"],
( isset( $field["callback"] ) ? $field["callback"] : '' ),
$field["page"],
$field["section"],
( isset( $field["args"] ) ? $field["args"] : '' )
);
endforeach;
}
public function setFields( array $fields ){
$this->fields = $fields;
return $this;
}
CallbackClass.php
public function ss_PromoImage() {
// Set variables
// $value is always empty and I dont know why
$value = esc_attr( get_option ('promo_image1') );
$default_image = SS_PLUGIN_URL . 'assets/images/sales.png';
if ( !empty($value ) ) {
$image_attributes = wp_get_attachment_image_src( $value );
$src = $image_attributes[0];
update_option( $value , $src );
$value = $src;
} else {
$src = $default_image;
$value = '';
}
$text = __( 'Upload', '' );
// Print HTML field
echo '
<div class="upload">
<img style="max-width: 300px;" data-src="' . ( !empty($value) ? $value : $src ) . '" src="' . ( !empty($value) ? $value : $src ) . '" />
<div>
<input type="hidden" class="value_option" name="'. $value .'" value="' . $value . '" />
<button type="button" class="upload_image_button button">' . $text . '</button>
<button type="button" class="remove_image_button button">Remove</button>
</div>
</div>
';
?>
<script>
jQuery(document).ready(function($){
// The "Upload" button
$('.upload_image_button').click(function() {
var send_attachment_bkp = wp.media.editor.send.attachment;
var button = $(this);
wp.media.editor.send.attachment = function(props, attachment) {
$(button).parent().prev().attr('src', attachment.url);
$(button).find('.value_option').val(attachment.id);
wp.media.editor.send.attachment = send_attachment_bkp;
}
wp.media.editor.open(button);
return false;
});
// The "Remove" button (remove the value from input type='hidden')
$('.remove_image_button').click(function() {
var src = $(this).parent().prev().attr('src', '');
});
});
</script>
<?php
}
and here is the output:
<form method="post" action="options.php">
<?php
settings_errors();
settings_fields( 'ss_options_group' );
do_settings_sections( SS_PLUGIN );
submit_button();
?>
</form>

Change Custom Meta Box in post into Page

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.

Wordpress plugin - options page not found

I was coding my very first plugin in order to share the posts on Facebook and Instagram, and I was writing the plugin options page.
I get always the error "Options page not found".
I thought that register_setting in the callback function could make the trick, but it didn't.
What am I doing wrong?
Here my code:
<?php
class Socialize {
public function __construct() {
// Hook into the admin menu
add_action( 'admin_menu', array( $this, 'create_plugin_settings_page' ) );
add_action( 'admin_init', array( $this, 'setup_sections' ) );
add_action( 'admin_init', array( $this, 'setup_fields' ) );
}
public function setup_fields() {
add_settings_field( 'facebook_account', 'Facebook Username', array( $this, 'fb_account_callback' ), 'smashing_fields', 'facebook_section' );
add_settings_field( 'facebook_password', 'Facebook Password', array( $this, 'fb_pwd_callback' ), 'smashing_fields', 'facebook_section' );
add_settings_field( 'instagram_account', 'Instagram Username', array( $this, 'insta_account_callback' ), 'smashing_fields', 'instagram_section' );
add_settings_field( 'instagram_password', 'Instagram Password', array( $this, 'insta_pwd_callback' ), 'smashing_fields', 'instagram_section' );
}
public function setup_sections() {
add_settings_section( 'facebook_section', 'Facebook Account', array( $this, 'section_callback' ), 'smashing_fields' );
add_settings_section( 'instagram_section', 'Instagram Account', array( $this, 'section_callback' ), 'smashing_fields' );
}
public function fb_account_callback( $arguments ) {
echo '<input name="fb_account" id="fb_account" type="text" value="' . get_option( 'facebook_account' ) . '" />';
register_setting( 'smashing_fields', 'facebook_account' );
}
public function fb_pwd_callback( $arguments ) {
echo '<input name="fb_pwd" id="fb_pwd" type="password" value="' . get_option( 'facebook_password' ) . '" />';
register_setting( 'smashing_fields', 'facebook_password' );
}
public function insta_account_callback( $arguments ) {
echo '<input name="insta_account" id="insta_account" type="text" value="' . get_option( 'instagram_account' ) . '" />';
register_setting( 'smashing_fields', 'instagram_account' );
}
public function insta_pwd_callback( $arguments ) {
echo '<input name="insta_pwd" id="insta_pwd" type="password" value="' . get_option( 'instagram_password' ) . '" />';
register_setting( 'smashing_fields', 'instagram_password' );
}
public function section_callback( $arguments ) {
switch ( $arguments['id'] ) {
case 'facebook_section':
echo 'This is the Facebook section';
break;
case 'instagram_section':
echo 'This is the Instagram section';
break;
}
}
public function create_plugin_settings_page() {
// Add the menu item and page
$page_title = 'Free Socialize';
$menu_title = 'Free Socialize';
$capability = 'manage_options';
$slug = 'smashing_fields';
$callback = array( $this, 'plugin_settings_page_content' );
$icon = 'dashicons-admin-plugins';
$position = 100;
add_menu_page( $page_title, $menu_title, $capability, $slug, $callback, $icon, $position );
}
public function plugin_settings_page_content() { ?>
<div class="wrap">
<h2>Free Socialize Settings Page</h2>
<form method="post" action="options.php">
<?php
settings_fields( 'smashing_fields' );
do_settings_sections( 'smashing_fields' );
submit_button();
?>
</form>
</div> <?php
}
}
new Socialize();
?>
I can't comment to gain clarification so apologies if I've misunderstood but would you not need to use add_plugins_page() in this instance?
<?php
add_plugins_page( $page_title, $menu_title, $capability, $menu_slug, $function);
?>
Docs: https://codex.wordpress.org/Function_Reference/add_plugins_page
Hope that helps and I've understood :)

Wordpress dynamic Options Page from arrays and actually save?

I need to create a plugin to save custom values to options.php.
I want to create the fields in arrays and that works.
Where I get lost is this:
The form will not actually save the settings in the WP database.
How do I create additional sections?
I know it has to do with add_settings_section(), etc. But I cannot find how to do this with arrayed inputs. Please advice. ;-)
My code so far:
<?php
// Create WordPress admin menu
function stonehenge_menu_page(){
$page_title = 'Stonehenge Options';
$menu_title = 'Stonehenge Options';
$capability = 'manage_options';
$menu_slug = 'stonehenge_slug';
$function = 'stonehenge_render_page';
$icon_url = 'dashicons-admin-plugins';
$position = 99;
add_menu_page( $page_title, $menu_title, $capability, $menu_slug, $function, $icon_url, $position );
// Call update_stonehenge function to update database
add_action( 'admin_init', 'update_stonehenge' );
}
// Create function to register plugin settings in the database
function update_stonehenge() {
register_setting( 'stonehenge-settings', 'stonehenge' );
}
function stonehenge_render_page() {
$section_1 = array(
'Field 1' => array( // $name Name of the field
'field' => 'field_1', // $field
'label' => 'Field 1', // $label Label of the field
'type' => 'text', // $type input type (text, textarea, option, etc.)
),
'Field 2' => array( // $field Name of the field
'field' => 'field_2', // $field
'label' => 'Field 2', // $label Label of the field
'type' => 'text', // $type input type (text, textarea, option, etc.)
),
'Field 3' => array( // $field Name of the field
'field' => 'field_3', // $field
'label' => 'Field 3', // $label Label of the field
'type' => 'text', // $type input type (text, textarea, option, etc.)
),
);
## START OF MAIN PAGE
echo '<h1>Stonehenge Options Fields</h1>';
?>
<form method="post" action="options.php">
<?php settings_fields( 'stonehenge-settings' ); ?>
<?php do_settings_sections( 'stonehenge-settings' ); ?>
<!-- >## SECTION 1 should start here </!-->
<br><h2>Section 1</h2>
<table>
<?php
foreach ($section_1 as $var) {
$prefix = 'stonehenge_';
$option_label = $var['label'];
$option_name = $var['field'];
$option_field = 'stonehenge_'.$var['field'];
$option_value = get_option( $option_field);
$option_input = '<input type="' .$var['type']. '"name="'.$option_field.'" id="'.$option_field.'" value="'.$option_value.'"> ';
$label_for = '<label for='.$field.'>' . $var['label'] . '</label>';
?>
<tr><th scope="row" align="left"><?php echo $option_label; ?></th>
<td><?php echo $option_input; ?></td>
<td>Database Field = <?php echo $option_field; ?></td>
</tr>
<?php } ?>
</table>
<!-- >## SECTION 2 should start here </!-->
<br><h2>Section 2</h2>
<table>
</table>
<?php submit_button(); ?>
</form>
<?php
}
SOLVED!
Turns out it was rather simple, if done correctly. :-) Now I can just add an array and all the rest is created dynamically. Whoop! Whoop!
Inputs are stored in options.php as stonehenge_section_fieldname and cal be easily called with get_option('stonehenge_section_fieldname');
Here's the code so far, if anyone is interested.
// Define common constants for stabiliy.
if (!defined("STONEHENGE_PLUGIN_VERSION")) define("STONEHENGE_PLUGIN_VERSION", "2.0.0");
if (!defined("STONEHENGE_PLUGIN_DIR_PATH")) define("STONEHENGE_PLUGIN_DIR_PATH", plugins_url('' , __FILE__));
// TO DO: Add MultiSite compatibility for network Activation.
// Current version only works if activated per blog.
// Let's load the language files.
load_plugin_textdomain('stonehenge', false, basename( dirname( __FILE__ ) ) . '/languages/' );
Class Stonehenge_Fields {
// Add additional Arrays to dynamically create more inputs. That's it!
static $stonehenge_fields = array(
'Facebook' => array(
'Page URL' => 'text',
'App ID' => 'text',
'Admin ID' => 'text',
),
/* 'Section' => array(
'Field 1' => 'text',
'Field 2' => 'textarea',
'Field 3' => 'checkbox',
),
*/
);
}
// TO DO: Add a hook to remove all option fields upon deactivation of the Plugin.
//delete_option('stonehenge_website_name');
// Call stonehenge_menu function to load Admin Menu in the Dashboard.
add_action( 'admin_menu', 'stonehenge_menu_page' );
// Let's create WordPress Admin Menu
function stonehenge_menu_page(){
$page_title = __('Stonehenge Custom Fields & Data Settings', 'stonehenge');
$menu_title = __('Stonehenge Fields', 'stonehenge');
$capability = 'manage_options';
$menu_slug = 'stonehenge';
$function = 'stonehenge_options_page';
$icon_url = 'dashicons-admin-plugins';
$position = 99;
add_menu_page( $page_title, $menu_title, $capability, $menu_slug, $function, $icon_url, $position );
}
function stonehenge_register_settings() {
// Let's create and register the Sections.
$sections = Stonehenge_Fields::$stonehenge_fields;
foreach ($sections as $section => $key) {
add_settings_section($section, $section, 'stonehenge_callback', __FILE__ );
// Let's create and register the input fields in options.php (acutal input fields are created in function stonehenge_options_page. )
foreach ($key as $name => $type) {
$prefix = 'stonehenge';
$field = str_replace(' ', '_', strtolower( $prefix.'_'.$section.'_'.$name ) );
$label = ucfirst($section.' '.$name);
$value = get_option($prefix.'_'.$section.'_'.$name);
$input = '<input type="' .$type. '"name="'.$field.'" id="'.$field.'" value="'.$value.'"> ';
$label_for = '<label for='.$field.'>' . $label . '</label>';
add_option($field, $value);
register_setting('stonehenge_options_group',$field, 'stonehenge_callback');
}
}
}
add_action( 'admin_init', 'stonehenge_register_settings' );
// Let's create the Main Page.
function stonehenge_options_page()
{
?>
<div class="wrap">
<h1><?php _e('Stonehenge Custom Fields & Data Settings', 'stonehenge'); ?></h1>
<form method="post" action="options.php">
<?php settings_fields( 'stonehenge_options_group' ); ?>
<table cellspacing="4" cellpadding"3">
<?php
//Let's create the Sections
$sections = Stonehenge_Fields::$stonehenge_fields;
foreach ($sections as $section => $key) {
$section_label = ucfirst($section);
echo ('<th scope="row" colspan="2" align="left"><br><h2>'.$section_label.' '.__('Settings','stonehenge').'</h2></th>');
// Let's create the actual Labels and input Fields
foreach ($key as $name => $type) {
$prefix = 'stonehenge';
$field = str_replace(' ', '_', strtolower( $prefix.'_'.$section.'_'.$name ) );
$label = ucfirst($section.' '.$name);
$value = get_option($field);
// TO DO: Create switch arguments for different input types, such as Checkbox, Radio, Textarea, Password, etc.
$input = '<input type="' .$type. '"name="'.$field.'" id="'.$field.'" value="'.$value.'"> ';
// Using <label for> Makes it clickable. Very handy!
$label_for = '<label for='.$field.'>' . $label . '</label>';
?><tr><th scope="row" align="left"><?php echo $label_for; ?></th><td><?php echo $input; ?></td></tr><?php
}
}?>
</table>
<?php submit_button(); ?>
</form>
</div>
<?php
}
// That's all Folks! :-)
?>

wp_list_table bulk actions not working properly

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 ]
);
}
}

Categories