Wordpress Widget not saving - php

I'm trying to save a simple widget, however everytime I hit save, it does not save the values. Instead the form is refreshed to a default value.
The code is below.
What I have found is that the value of $instance in the update() function is an empty array i.e. array() why is this??
<?php
defined('ABSPATH') or die("Cannot access pages directly.");
defined("DS") or define("DS", DIRECTORY_SEPARATOR);
add_action( 'widgets_init', create_function( '', 'register_widget("Page_Widget");' ) );
add_action( 'admin_head', 'page_widget_admin_head' );
$pw_class = new Page_Widget();
add_action( 'wp_ajax_nopriv_pw_get_option', array($pw_class, 'get_options'));
add_action( 'wp_ajax_pw_get_option', array($pw_class, 'get_options'));
function page_widget_admin_head()
{
if(basename($_SERVER['SCRIPT_NAME']) != 'widgets.php'){return false; }
echo '<style> .titler { width:80px; display:inline-block; }</style>';
echo '<script type="text/javascript">
jQuery(function($){
$(".post_type_select").live("change", function(){
the_opt = $(this).val();
el = $(this);
$.post(ajaxurl, "action=pw_get_option&pw_post_type="+the_opt, function(data){
el.siblings(".posts_select").html(data);
})
});
});</script>';
}
/**
*
* #author byrd
* Document Widget
*/
class Page_Widget extends WP_Widget
{
/**
* Constructor
*
* Registers the widget details with the parent class
*/
function __construct()
{
// widget actual processes
parent::__construct( $id = 'page_widget', $name = 'Page Widget', $options = array( 'description' => 'A Widget for grabbing page ids' ) );
}
function form($instance)
{
// outputs the options form on admin
$post_type_str = '<span class="titler">Post Type: </span><select name="pw_post_type" class="post_type_select">';
$post_types = get_post_types(array('public' => true),' objects');
$i = 1;
$pw_post_type = '';
$pw_post_id = '';
error_log(var_export($instance, true));
if ( $instance ) {
$pw_post_type = esc_attr( $instance[ 'pw_post_type' ] );
$pw_post_id = esc_attr( $instance[ 'pw_post_id' ] );
}
foreach ($post_types as $post_type ) {
$name = $post_type->labels->name;
$var = $post_type->name;
if($i == 1){$first = $var; }
if($pw_post_type == $var){$selected = 'selected="selected"'; }else{$selected = ''; }
$post_type_str .= '<option '.$selected.' value="'.$var.'">'. $name. '</option>';
$i++;
}
$options = $this->get_options($first, $pw_post_id);
$post_type_str .= '</select><br/><span class="titler">Post Name: </span><select name="pw_post_id" class="posts_select">'.$options.'</select>';
echo $post_type_str;
}
function get_options($post_type = false, $pw_post_id = '', $ajax = false)
{
if(!$post_type){ $post_type = $_POST['pw_post_type']; $ajax = true; }
$args = array('numberposts' => -1, 'post_type' => $post_type);
$str = '';
$posts_array = get_posts( $args );
foreach( $posts_array as $post )
{
if($pw_post_id == $post->ID){$selected = 'selected="selected"'; }else{ $selected = ''; }
$str .= '<option '.$selected.' value="'.$post->ID.'">'.$post->post_title.'</option>';
}
if($ajax){ echo $str; exit(); }
else{ return $str; }
}
function update($new_instance, $old_instance)
{
error_log(var_export($new_instance, true));
error_log(var_export($old_instance, true));
// processes widget options to be saved
$instance = wp_parse_args($old_instance, $new_instance);
return $new_instance;
}
function widget($args, $instance)
{
// outputs the content of the widget
}
}

Looks like you asked this a while ago, but I'll answer in case others follow along.
Make sure you're using:
$field_name = $this->get_field_name('your_field_name');
when creating field names for your widget form items. The field names need to conform to WordPress' naming conventions. Otherwise, you'll get nothing back from the form post.

Change your class name which is
class Page_Widget extends WP_Widget
to this
class WP_Widget_Page_Widget extends WP_Widget
and also change this line
add_action( 'widgets_init', create_function( '', 'register_widget("Page_Widget");' ) );
to
add_action( 'widgets_init', create_function( '', 'register_widget("WP_Widget_Page_Widget ");' ) );
This will work insaAllah.

Related

Change subcategory URL(slug) in Wordpress

I have problem with slug(URL) in category/subcategory. Now i have: http://my-page.pl/animal-category/animal-subcategory. How can i delete "animal-category" for every subcategory ?
It should look like that:
http://my-page.pl/animal-category/
http://my-page.pl/animal-subcategory/
http://my-page.pl/animal-subcategory/single-page
Maybe it's simple question, but I cant find answer anywhere :)
Check below code it will help you
// Add 'cat_redirect' query variable in query_vars
add_filter('query_vars', 'no_parent_cat_query_vars');
function no_parent_cat_query_vars($query_vars) {
$query_vars[] = 'cat_redirect';
return $query_vars;
}
// Redirect if 'cat_redirect' is set
add_filter('request', 'no_parent_cat_request');
function no_parent_cat_request($query_vars) {
if(isset($query_vars['cat_redirect'])) {
$cat_link = trailingslashit(get_option( 'home' )) . user_trailingslashit( $query_vars['cat_redirect'], 'category' );
status_header(301);
header("Location: $cat_link");
exit();
}
return $query_vars;
}
// Remove category
add_filter('category_link', 'category_url_without_parent',1000,2);
function category_url_without_parent($cat_link, $cat_id)
{
$category = &get_category( $cat_id );
if ( is_wp_error( $category ) ) return $category;
$catname = $category->slug;
$cat_link = trailingslashit(get_option( 'home' )) . user_trailingslashit( $catname, 'category' );
return $cat_link;
}
// Add custom category rewrite rule
add_filter('category_rewrite_rules', 'remove_category_parent_rule');
function remove_category_parent_rule($cat_rewrite) {
global $wp_rewrite;
$cat_rewrite=array();
$cat_list=get_categories(array('hide_empty'=>false));
foreach($cat_list as $category) {
$catname = $category->slug;
$cat_rewrite['('.$catname.')/(?:feed/)?(feed|rdf|rss|rss2|atom)/?$'] = 'index.php?category_name=$matches[1]&feed=$matches[2]';
$cat_rewrite['('.$catname.')/page/?([0-9]{1,})/?$'] = 'index.php?category_name=$matches[1]&paged=$matches[2]';
$cat_rewrite['('.$catname.')/?$'] = 'index.php?category_name=$matches[1]';
}
$old_base = $wp_rewrite->get_category_permastruct();
$old_base = str_replace( '%category%', '(.+)', $old_base );
$old_base = trim($old_base, '/');
$cat_rewrite[$old_base.'$'] = 'index.php?cat_redirect=$matches[1]';
return $cat_rewrite;
}

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>

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

Two different WordPress hooks with the same callback

I made a plugin that converts any uri to a hyperlink, if it finds hyper-link it will ignore it and only convert the no hyper-links uri.
In the plugin admin page I set two options, first to convert links only for the front-end, and the second option is to convert uri when ever a post/comment saved to database.
// permanently means before save to database
if ( $this->plugin_options['uri2links_convert_method'] == 'permanently' ) {
add_action( 'wp_insert_post_data', array($this, 'make_post_url_clickable' ) );
//add_action( 'preprocess_comment', array($this, 'make_comment_url_clickable' ) );
}
else {
add_filter( 'the_content', array($this, 'make_post_url_clickable' ) );
//add_filter( 'preprocess_comment', array($this, 'make_comment_url_clickable' ) );
}
My problem here if I set the plugin option to convert uri for front-end it will ignore hyper-links and convert the other uri, but if I set it to convert before save to database it 'll not ignore hyper-links and treat them as normal uri witch make the results look like this:
<a class="sdf" href=" <a href="http://test.test-75.1474.stackoverflow.com/" >http://test.test-75.1474.stackoverflow.com/ </a>
<a class="sdf" href=" <a href="https://www.stackoverflow.com" >https://www.stackoverflow.com </a>
The complete plugin source code:
<?php
/*
Plugin name: URIs to a click-able links
Plugin URI:
Description: Convert URI's to a click-able links
Author: h Abdou
Author URI: habdou.me
Version: 1.0
*/
// The admin page for the plugin
require_once( 'uri2links-menu.php' );
class Uri2Links {
protected $css = '';
protected $rel = '';
protected $target = '';
protected $convert_links = '';
protected $convert_emails = '';
protected $plugin_options = array();
protected $url_match_pattern = '/[a-zA-Z0-9\.\/\?\:#\-_=#]+\.([a-zA-Z0-9\.\/\?\:#\-_=#])+/';
protected $email_match_pattern = '/^[a-zA-Z0-9_.+-]+#[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$/';
//protected $links_match_pattern = '/<a(?:"[^"]*"[\'"]*|\'[^\']*\'[\'"]*|[^\'">])+>^[a-zA-Z0-9_.+-]+#[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$<\/a>/';
protected $links_match_pattern = '/<a[^>]*>(.*?)<\/a>/';
protected $links_matched = array();
public function __construct() {
//$this->plugin_options = get_option( 'uri2links_plugin_options' );
$this->plugin_options = array( 'uri2links_convertLinksEmails' => array( 'Links', 'Emails' ), 'uri2links_convert_method' => 'permanently' );
$this->css = isset( $this->plugin_options['uri2links_custom_css'] ) ? ' class="' . $this->plugin_options['uri2links_custom_css'] . '"' : '';
$this->rel = isset( $this->plugin_options['uri2links_rel_attr'] ) ? ' rel="' . $this->plugin_options['uri2links_rel_attr'] . '"' : '';
if ( isset( $this->plugin_options['uri2links_open_links_method'] ) && $this->plugin_options['uri2links_open_links_method'] == 'new')
$this->target = ' target="_blank"';
$this->convert_links = isset( $this->plugin_options['uri2links_convertLinksEmails'][0] ) ? $this->plugin_options['uri2links_convertLinksEmails'][0] : '';
$this->convert_emails = isset( $this->plugin_options['uri2links_convertLinksEmails'][1] ) ? $this->plugin_options['uri2links_convertLinksEmails'][1] : '';
if ( $this->plugin_options['uri2links_convert_method'] == 'permanently' ) {
add_action( 'wp_insert_post_data', array($this, 'make_post_url_clickable' ) );
//add_action( 'preprocess_comment', array($this, 'make_comment_url_clickable' ) );
}
else {
add_filter( 'the_content', array($this, 'make_post_url_clickable' ) );
//add_filter( 'preprocess_comment', array($this, 'make_comment_url_clickable' ) );
}
// The admin page for the plugin
new Uri2LinksMenu;
}
// Convert all URI in a post to hyper-links.
public function make_post_url_clickable( $content ) {
$links = $this->hash_links( $content );
if ( $this->convert_links == 'Links' ) {
$content = preg_replace($this->url_match_pattern, ' <a href="\\0"' . $this->css . $this->rel . $this->target . ' >\\0</a> ', $content);
}
if ( $this->convert_emails == 'Emails' ) {
$content = preg_replace($this->email_match_pattern, ' <a href="mailto:\\0"' . $this->css . $this->rel . $this->target . ' >\\0</a> ', $content);
}
// Replace back the hashed 'a' tags to the original status.
foreach ( $links as $link_hash => $link_text ) {
$content = str_replace( $link_hash, $link_text, $content );
}
return $content;
}
// Same as 'make_post_url_clickable' but this for comments
public function make_comment_url_clickable( $content ) {
$links = hash_links( $content['comment_content']['comment_content'] );
if ( $this->convert_links == 'Links' ) {
$content['comment_content'] = preg_replace($this->url_match_pattern, ' <a href="\\0"' . $this->css . $this->rel . $this->target . ' >\\0</a> ', $content['comment_content']);
}
if ( $this->convert_emails == 'Emails' ) {
$content['comment_content'] = preg_replace($this->email_match_pattern, ' <a href="mailto:\\0"' . $this->css . $this->rel . $this->target . ' >\\0</a> ', $content['comment_content']);
}
foreach ( $links as $link_hash => $link_text ) {
$content['comment_content'] = str_replace( $link_hash, $link_text, $content['comment_content'] );
}
return $content;
}
// hash all 'a' tags so 'make_*_url_clickable' will ignore them.
public function hash_links( &$content ) {
$links = array();
if ( preg_match_all( $this->links_match_pattern, $content, $matches ) ) {
$array_size = sizeof( $matches[0] );
for ( $i = 0; $i < $array_size; ++$i ) {
$link_hash = md5( $matches[0][$i] );
$links[$link_hash] = $matches[0][$i];
$content = str_replace( $matches[0][$i], $link_hash, $content );
}
}
//die('hash_links called!');
return $links;
}
}
new Uri2Links;
?>
I just want to mention that WordPress already got the make_clickable() function that takes text uri to HTML links.
To activate it for the post content we only need this simple plugin:
<?php
/** Plugin Name: Make text uri to HTML links in the post content **/
add_filter( 'the_content', 'make_clickable', 9 );
By default this function runs on the comment text:
add_filter( 'comment_text', 'make_clickable', 9 );

Categories