wp_list_table bulk actions not working properly - php

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

Related

Dynamically added custom fields not displayed on WooCommerce email notifications

I have a different kind of scenario then the typical custom fields (I suppose). I am not getting custom values (fields) from user in the form rather I have an implementation which adds:
ColorName
Size
City
These are from a custom product flow which adds custom attributes to the cart, here is how I am doing that:
add_action('wp_ajax_wdm_add_user_custom_data_options', 'wdm_add_user_custom_data_options_callback');
add_action('wp_ajax_nopriv_wdm_add_user_custom_data_options', 'wdm_add_user_custom_data_options_callback');
function wdm_add_user_custom_data_options_callback()
{
// print_r($_POST);
$productIDM = $_POST['product_id'];
// case swith
switch ($productIDM) {
case "Ace Dura Silk":
$productID = 3254;
break;
case "Ace Matt Finish":
$productID = 3232;
break;
case "Ace Plastic Emulsion":
$productID = 3276;
break;
case "Ace Weather Defender":
$productID = 2991;
break;
case "Overall Plasticoat":
$productID = 3112;
break;
}
$colorname = $_POST['colorname'];
$cityname = $_POST['cityname'];
$size = $_POST['size'];
$price = $_POST['price'];
global $woocommerce;
$woocommerce->cart->add_to_cart( $productID, 1 );
// die();
// echo 'I am in...';
$result = array(
'status' => true
);
echo json_encode($result);
}
add_filter('woocommerce_add_cart_item_data','wdm_add_item_data',1,10);
function wdm_add_item_data($cart_item_data, $product_id) {
global $woocommerce;
$new_value = array();
$new_value['_custom_options'] = $_POST['custom_options'];
if(empty($cart_item_data)) {
return $new_value;
} else {
return array_merge($cart_item_data, $new_value);
}
}
add_filter('woocommerce_get_cart_item_from_session', 'wdm_get_cart_items_from_session', 1, 3 );
function wdm_get_cart_items_from_session($item,$values,$key) {
if (array_key_exists( '_custom_options', $values ) ) {
$item['_custom_options'] = $values['_custom_options'];
}
return $item;
}
add_filter('woocommerce_cart_item_name','add_usr_custom_session',1,3);
function add_usr_custom_session($product_name, $values, $cart_item_key ) {
$return_string = $product_name . "<div class='cart_subitems_custom'><br /><small>".$values['_custom_options']['colorname']."</small><br /><small>".$values['_custom_options']['cityname']."</small><br /><small>".$values['_custom_options']['size']."</small></div>" ; //. "<br />" . print_r($values['_custom_options']);
return $return_string;
}
add_action('woocommerce_add_order_item_meta','wdm_add_values_to_order_item_meta',1,2);
function wdm_add_values_to_order_item_meta($item_id, $values) {
global $woocommerce,$wpdb;
wc_add_order_item_meta($item_id,'_colorname',$values['_custom_options']['colorname']);
wc_add_order_item_meta($item_id,'_cityname',$values['_custom_options']['cityname']);
wc_add_order_item_meta($item_id,'_size',$values['_custom_options']['size']);
}
add_action( 'woocommerce_before_calculate_totals', 'update_custom_price', 1, 1 );
function update_custom_price( $cart_object ) {
foreach ( $cart_object->cart_contents as $cart_item_key => $value ) {
// Version 2.x
//$value['data']->price = $value['_custom_options']['custom_price'];
// Version 3.x / 4.x
if($value['_custom_options']['price'] == null){
echo"";
}else{
$value['data']->set_price($value['_custom_options']['price']);
}
}
}
I am getting these custom values almost everywhere except Email Notification.
Here is what normal product order edit shows:
Here is how I am getting the custom product in order edit page:
I have tried all the solution I can possibly find (filter & action hooks) but nothing works for me.
I have tried first answer from this:
add_action( 'woocommerce_checkout_create_order_line_item', 'custom_checkout_create_order_line_item', 20, 4 );
function custom_checkout_create_order_line_item( $item, $cart_item_key, $values, $order ) {
if( isset( $values['colorname'] ) )
$item->add_meta_data( __('DCM Shade'), $values['_colorname'] );
}
Also the common method I found everywhere:
function custom_woocommerce_email_order_meta_fields( $fields, $sent_to_admin, $order ) {
// Get meta
$color = $order->get_meta( 'colorname', true );
// NOT empty
if( ! empty( $color ) ) {
$fields['colorname'] = array(
'label' => __( 'Shade' ),
'value' => $color,
);
}
// Get (other) meta
$shipping_email = $order->get_meta( '_cityname', true );
// NOT empty
if ( ! empty( $shipping_email ) ) {
$fields['_cityname'] = array(
'label' => __( 'City' ),
'value' => $shipping_email,
);
}
return $fields;
}
add_filter( 'woocommerce_email_order_meta_fields', 'custom_woocommerce_email_order_meta_fields', 10, 3 );
But I can't get the custom fields.
What am I doing wrong can please anyone please guide me.

make list table with output array value in option table wordpress

class Kv_subscribers_list extends WP_List_Table {
function __construct(){
global $status, $page;
parent::__construct( array(
'singular' => 'option',
'plural' => 'options',
'ajax' => false
) );
}
function column_default($item, $column_name){
switch($column_name){
case 'option_id':
case 'option_name':
case 'option_value':
return $item[$column_name];
default:
return print_r($item,true); //Show the whole array for troubleshooting purposes
}
}
function column_cb($item){
return sprintf(
'<input type="checkbox" name="%1$s[]" value="%2$s" />',
/*$1%s*/ $this->_args['singular'],
/*$2%s*/ $item['option_id']
);
}
function get_columns(){
$columns = array(
'cb' => '<input type="checkbox" />',
'option_id'=>__('الرقم'),
'option_name'=>__('المصدر'),
'option_value'=>__('النقطة'),
);
return $columns;
}
public function get_sortable_columns() {
$sortable_columns = array(
'option_id' => array('option_id',true),
'option_name' => array('option_name',true)
);
return $sortable_columns;
}
public function get_bulk_actions() {
$actions = array(
'delete' => 'حذÙ',
'email' => 'Email'
);
return $actions;
}
public function process_bulk_action() {
global $wpdb;
$options_tbl = $wpdb->prefix.'options';
if( 'delete'===$this->current_action() ) {
foreach($_POST['option'] as $single_val){
$wpdb->delete( $options_tbl, array( 'option_id' => (int)$single_val ) );
}
$redirect_url = get_admin_url( null, 'admin.php?page=options' );
wp_safe_redirect($redirect_url);
wp_die('Items deleted (or they would be if we had items to delete)!');
}
if( 'email'===$this->current_action() ) {
$result_email_ar = implode("-",$_POST['option']);
$redirect_url = get_admin_url( null, 'admin.php?page=kvcodes&ids='.$result_email_ar );
wp_safe_redirect($redirect_url);
wp_die(' ');
}
}
function prepare_items() {
global $wpdb; //This is used only if making any database queries
$database_name = $wpdb->prefix.'options' ;
$per_page = 10;
$query = "SELECT * FROM $wpdb->options WHERE option_name LIKE 'agl_data_%_%' ";
$columns = $this->get_columns();
$hidden = array();
$sortable = $this->get_sortable_columns();
$this->_column_headers = array($columns, $hidden, $sortable);
$this->process_bulk_action();
$data = $wpdb->get_results($query, ARRAY_A );
function usort_reorder($a,$b){
$orderby = (!empty($_REQUEST['orderby'])) ? $_REQUEST['orderby'] : 'title'; //If no sort, default to title
$order = (!empty($_REQUEST['order'])) ? $_REQUEST['order'] : 'asc'; //If no order, default to asc
$result = strcmp($a[$orderby], $b[$orderby]); //Determine sort order
return ($order==='asc') ? $result : -$result; //Send final sort direction to usort
}
usort($data, 'usort_reorder');
$current_page = $this->get_pagenum();
$total_items = count($data);
$data = array_slice($data,(($current_page-1)*$per_page),$per_page);
$this->items = $data;
$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
'total_pages' => ceil($total_items/$per_page) //WE have to calculate the total number of pages
) );
}
}//class
function o_add_menu_items(){
//add_menu_page('Plugin List Table', 'Sub', 'activate_plugins', 'options', 'o_render_list_page');
add_menu_page( 'تقرير التتبع', 'تقرير التتبع', 'manage_options', 'options', 'o_render_list_page', 'dashicons-welcome-widgets-menus', 81 );
}
add_action('admin_menu', 'o_add_menu_items');
function ns_contact_form_csv_pull() {
global $wpdb;
$table = 'ns_contact_form';// table name
$file = 'سجلات_التتبع_csv'; // csv file name
$results = $wpdb->get_results("SELECT * FROM $wpdb->options WHERE option_name LIKE 'agl_data_%_%' ",ARRAY_A );
if(count($results) > 0){
foreach($results as $result){
$result = array_values($result);
$result = implode(", ", $result);
$csv_output .= $result."\n";
}
}
$filename = $file."_".date("Y-m-d_H-i",time());
header("Content-type: application/vnd.ms-excel");
header("Content-disposition: csv" . date("Y-m-d") . ".csv");
header( "Content-disposition: filename=".$filename.".csv");
print $csv_output;
exit;
}
add_action('wp_ajax_csv_pull','ns_contact_form_csv_pull');
function o_render_list_page() {
$mydownloads = new Kv_subscribers_list();
$title = __("سجلات نظام التتبع","my_plugin_slug");
?>
<div class="wrap">
<h1>
<?php echo esc_html( $title );?>
<!-- Check edit permissions -->
<a href="<?php echo admin_url( 'admin-ajax.php?action=csv_pull' ); ?>" class="page-title-action">
<?php echo esc_html_x('تصدير كاÙØ© البيانات', 'my-plugin-slug'); ?>
</a>
<?php
?>
</h1>
</div>
<?php $mydownloads->views(); ?>
<form method="post">
<?php
$mydownloads->prepare_items();
$mydownloads->display();
?>
</form>
<?php
}
above is code that filter an data stores in options table
option_value field is contain an array data
example :
a:14:{s:8:"latitude";s:10:"51.5841086";s:9:"longitude";s:17:"89.21324279999999";s:8:"altitude";s:3:"NaN";s:8:"accuracy";s:4:"1612";s:16:"altitudeAccuracy";s:3:"NaN";s:7:"heading";s:3:"NaN";s:5:"speed";s:3:"NaN";s:10:"error_code";s:0:"";s:13:"error_message";s:0:"";s:8:"php_time";i:1529454899;s:8:"php_date";s:19:"2018-06-20 00:34:59";s:15:"php_date_format";s:11:"Y-m-d H:i:s";s:7:"user_id";s:1:"0";s:9:"user_mail";s:1:"0";}
ineed to get this option_value array and make a table of the variable
column header = altitude|
longitude|
altitude
value = altitude => 21.5841086|
longitude => 39.21324279999999|
altitude => NaN
please some one help me to adjust my code above to fit data in array column header and row data

Wordpress sortable column by IP address

I have been able to add a sortable column to my Wordpress userpage that displays the users last know IP address.
The problem I seem to be having is getting the column to sort by the IP's numbers and not the usernames alphabetically.
I feel im missing something simple and could use another set of eyes.
<?php
class Register_IP_Multisite {
public function __construct() {
add_action( 'init', array( &$this, 'init' ) );
}
public function init() {
add_action( 'user_register', array( $this,'log_ip') );
add_action( 'edit_user_profile', array( $this,'edit_user_profile') );
add_action( 'manage_users_custom_column', array( $this,'columns'), 10, 3);
add_filter( 'manage_users_sortable_columns', array( $this ,'users_sortable_columns_wsp') );
add_filter( 'request', array( $this ,'users_orderby_column_wsp') );
add_filter( 'plugin_row_meta', array( $this ,'donate_link'), 10, 2 );
if ( is_multisite() ) {
add_filter('wpmu_users_columns', array( $this ,'column_header_signup_ip'));
} else {
add_filter('manage_users_columns', array( $this ,'column_header_signup_ip'));
}
}
public function log_ip($user_id){
$ip = $_SERVER['REMOTE_ADDR']; //Get the IP of the person registering
update_user_meta($user_id, 'signup_ip', $ip); //Add user metadata to the usermeta table
}
public function edit_user_profile() {
$user_id = (int) $_GET['user_id'];
?>
<h3><?php _e('Signup IP Address', 'register-ip-mutisite'); ?></h3>
<p style="text-indent:15px;"><?php
$ip_address = get_user_meta($user_id, 'signup_ip', true);
echo $ip_address;
?></p>
<?php
}
public function column_header_signup_ip($column_headers) {
$column_headers['signup_ip'] = __('IP Address', 'register-ip-multisite');
return $column_headers;
}
public function users_sortable_columns_wsp($column_headers) {
$customwsp = array(
// meta column id => sortby value used in query
'signup_ip' => 'user_ip_address',
);
return wp_parse_args($customwsp, $column_headers);
}
public function users_orderby_column_wsp( $varswsp ) {
if ( isset( $varswsp['orderby'] ) && 'signup_ip' == $varswsp['orderby'] ) {
$varswsp = array_merge( $varswsp, array(
'meta_key' => 'signup_ip',
'orderby' => 'meta_value'
) );
}
return $varswsp;
}
public function columns($value, $column_name, $user_id) {
global $modewsp;
$modewsp = empty( $_REQUEST['mode'] ) ? 'list' : $_REQUEST['mode'];
if ( $column_name == 'signup_ip' ) {
$ip = get_user_meta($user_id, 'signup_ip', true);
if ($ip != ""){
$theip = $ip;
if ( has_filter('ripm_show_ip') ) {
$theip = apply_filters('ripm_show_ip', $theip);
}
return $theip;
} else {
$theip = '<em>'.__('None Recorded', 'register-ip-multisite').'</em>';
return $theip;
}
}
$user_ip_address = strtotime(get_date_from_gmt($user->signup_ip));
return $value;
}
}
new Register_IP_Multisite();

Notepad sticky plugin

I have this following code to give a textarea to a front end user to use it as notes on a page to write things to remember. But this code saves only one sticky note that can be edited whenever the user wants. My questions is if there is a way to save the content somewhere and have a new one every time submit is pressed. or a add new sticky button.
require_once( plugin_dir_path( __FILE__ ) . 'wp-ajax.php' );
class notepad_stikey extends WP_Ajax {
var $user;
var $username;
function __construct() {
parent::__construct();
add_action('init', array( &$this, 'setup') );
}
function setup() {
$this->user = get_current_user_id();
$this->username = get_userdata( $this->user )->user_login;
$this->notes = get_user_meta( $this->user, 'notepad_stikey', true );
$this->ph = ' '; //placeholder
if (empty( $this->notes )) {
$this->notes = $this->ph;
}
add_action('wp_enqueue_scripts', array( &$this, 'scripts') );
}
function scripts() {
wp_enqueue_script( 'notepad_stikey', plugins_url( 'notepad_stikey.js', __FILE__ ), array( 'jquery' ) );
wp_localize_script( 'notepad_stikey', 'notepad_stikey', array( 'ajaxurl' => admin_url( 'admin-ajax.php' ) ) );
}
function an_change_notepad_stikey() {
$notes = trim( $_POST['notes'] );
//if notes is empty, delete
if ( empty($notes) ) {
if ( delete_user_meta( $this->user, 'notepad_stikey' ) )
die( 'notes deleted' );
}
//notes are the same, notes = placeholder, or resaving empty notes
if ( $notes == $this->notes || $notes == $this->ph || ( empty($notes) && $this->notes == $this->ph) )
die();
//update
if ( update_user_meta( $this->user, 'notepad_stikey', $notes ) )
die( 'updated' );
//hopefully, we don't get this far. if we do, something is wrong
die( 'uh oh. notes could not be saved' );
}
}
global $notepad_stikey;
$notepad_stikey = new notepad_stikey();
add_action( 'widgets_init', 'notepad_stikey_load' );
function notepad_stikey_load() {
register_widget( 'notepad_stikey_Widget' );
}
class notepad_stikey_Widget extends WP_Widget {
function notepad_stikey_Widget() {
$widget_ops = array('classname' => 'notepad_stikey', 'description' => __( 'notepad_stikey. Only one instance please. Else this will break.', 'notepad_stikey' ) );
$control_ops = array( 'id_base' => 'notepad_stikey' );
parent::WP_Widget( 'notepad_stikey', __( 'notepad_stikey', 'notepad_stikey' ), $widget_ops, $control_ops );
}
function widget( $args, $instance ) {
extract( $args, EXTR_SKIP );
echo $before_widget;
global $notepad_stikey;
$username = $notepad_stikey->username;
$notes = $notepad_stikey->notes;
//overwrite title
$instance['title'] = 'Notepad for '. $username;
echo $instance['hide_title'] ? '' : $before_title . $instance['title'] . $after_title;
echo "<div id='notepad_stikey' class='$username' style='border: 1px solid #eee; padding: 10px 15px;min-height: 100px;'>";
echo $notes;
echo '</div><span style="float:left;color:#008;" id="notepad_stikey_response"></span><small style="float:right;">click box above to edit</small>';
echo $after_widget;
} //end widget()
function update($new_instance, $old_instance) {
$instance = $old_instance;
$instance['title'] = esc_attr( $new_instance['title'] );
$instance['hide_title'] = (bool) $new_instance['hide_title'] ? 1 : 0;
return $instance;
} //end update()
function form( $instance ) {
$instance = wp_parse_args( (array) $instance, array( 'hide_title' => 0 ) );
extract( $instance );
?>
<p>
<input type="checkbox" class="checkbox" id="<?php echo $this->get_field_id('hide_title'); ?>" name="<?php echo $this->get_field_name('hide_title'); ?>"<?php checked( $hide_title ); ?> />
<label for="<?php echo $this->get_field_id('hide_title'); ?>"><?php _e('Hide Title?', 'notepad_stikey' );?></label>
</p>
<?php
} //end form()
}
if (!class_exists('WP_Ajax')) {
class WP_Ajax {
function __construct( $ajax_prefix = 'a', $nopriv_prefix = 'n' ) {
$regex = "/^($ajax_prefix)?($nopriv_prefix)?_|^($nopriv_prefix)? ($ajax_prefix)?_/";
$methods = get_class_methods( $this );
foreach ( $methods as $method ) {
if ( preg_match( $regex, $method, $matches ) ) {
if ( count( $matches ) > 1 ) {
$action = preg_replace( $regex, '', $method );
if ( count( $matches ) == 3 ) {
add_action( "wp_ajax_$action", array( $this, $method ) );
add_action( "wp_ajax_nopriv_$action", array( $this, $method ) );
} else {
if ( $matches[1] == $ajax_prefix ) {
add_action( "wp_ajax_$action", array( $this, $method ) );
} else {
add_action( "wp_ajax_nopriv_$action", array( $this, $method ) );
}
}
}
}
}
}
}
}
jQuery(document).ready(function($) {
$('#notepad_stikey').click(function(e) {
tag = e.target.tagName;
if ( tag != 'TEXTAREA' && tag != 'INPUT' ) {
contents = $(this).html();
$(this).html( '<textarea rows="5" cols="50" style="display:block;width:98%;height:100px;">' + contents + '</textarea><input type="submit" class="save" style="position:relative;z-index:99" />' );
}
});
$('#notepad_stikey input.save').live( 'click', function() {
new_contents = $(this).siblings('textarea').val();
$('#notepad_stikey').html( new_contents );
change_notepad_stikey( new_contents );
return false;
});
function change_notepad_stikey( notes ) {
$('#notepad_stikey_response').text( '...' );
$.post(notepad_stikey.ajaxurl,
{
'action' : 'change_notepad_stikey',
'notes' : notes
}, function(response) {
//if (response != '') {
//alert( response );
$('#notepad_stikey_response').text( response );
//}
}, 'text' );
}
});

get the modified date of post meta box

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>

Categories