Add "insert button" on toolbar tinymce editor - wordpress

I want to add an "insert button" on my toolbar tinymce editor.
An example of what I want :
An example of what I want
With the toolbar button, I would like to create a button in my editor and change its style. (Like the gutenberg editor does)
gutenberg editor
To use the tinymce editor, I have this code :
function wpc_boutons_tinymce($buttons) {
$buttons[] = 'underline';
$buttons[] = 'fontselect';
$buttons[] = 'fontsizeselect';
$buttons[] = 'edit-block';
return $buttons;
}
add_filter("mce_buttons_3", "wpc_boutons_tinymce");
$content = '';
$editor_id = 'mycustomeditor';
$settings = array(
'wpautop' => false,
'media_buttons' => false,
'quicktags' => array(
'buttons' => 'strong,em,del,ul,ol,li,block,close'
),
);
wp_editor( $content, $editor_id, $settings );
I didn't find how to do, can you help me ?

Here is my implemented code Follow the step
Paste the code in your theme functions.php
add_action( 'init', 'wptuts_buttons' );
function wptuts_buttons() {
add_filter( "mce_external_plugins", "wptuts_add_buttons" );
add_filter( 'mce_buttons', 'wptuts_register_buttons' );
}
function wptuts_add_buttons( $plugin_array ) {
$plugin_array['wptuts'] = get_template_directory_uri() . '/wptuts-editor-buttons/wptuts-plugin.js';
return $plugin_array;
}
function wptuts_register_buttons( $buttons ) {
array_push( $buttons, 'dropcap', 'showrecent' ); // dropcap', 'recentposts
return $buttons;
}
require( 'wptuts-editor-buttons/wptuts.php' );
Create a folder in your theme root file named wptuts-editor-buttons
Then create a file in wptuts-editor-buttons named wptuts.php and paste the code
<?php
add_shortcode( 'recent-posts', 'wptuts_recent_posts' );
function wptuts_recent_posts( $atts ) {
extract( shortcode_atts( array(
'numbers' => '5',
), $atts ) );
$rposts = new WP_Query( array( 'posts_per_page' => $numbers, 'orderby' => 'date' ) );
if ( $rposts->have_posts() ) {
$html = '<h3>Recent Posts</h3><ul class="recent-posts">';
while( $rposts->have_posts() ) {
$rposts->the_post();
$html .= sprintf(
'<li>%s</li>',
get_permalink($rposts->post->ID),
get_the_title(),
get_the_title()
);
}
$html .= '</ul>';
}
wp_reset_query();
return $html;
}
Also, You need to create a js file in wptuts-editor-buttons > wptuts-plugin.js and paste the code
(function() {
tinymce.create('tinymce.plugins.Wptuts', {
init : function(ed, url) {
ed.addButton('dropcap', {
title : 'DropCap',
cmd : 'dropcap',
image : url + '/dropcap.jpg'
});
ed.addButton('showrecent', {
title : 'Add recent posts shortcode',
cmd : 'showrecent',
image : url + '/images.jpg'
});
ed.addCommand('dropcap', function() {
var selected_text = ed.selection.getContent();
var return_text = '';
return_text = '<span class="dropcap">' + selected_text + '</span>';
ed.execCommand('mceInsertContent', 0, return_text);
});
ed.addCommand('showrecent', function() {
var number = prompt("How many posts you want to show ? "),
shortcode;
if (number !== null) {
number = parseInt(number);
if (number > 0 && number <= 20) {
shortcode = '[recent-post number="' + number + '"/]';
ed.execCommand('mceInsertContent', 0, shortcode);
}
else {
alert("The number value is invalid. It should be from 0 to 20.");
}
}
});
},
// ... Hidden code
});
// Register plugin
tinymce.PluginManager.add( 'wptuts', tinymce.plugins.Wptuts );
})();
Whole the Solution I followed the article
https://code.tutsplus.com/tutorials/guide-to-creating-your-own-wordpress-editor-buttons--wp-30182

Related

Wordpress plugin can not added to the page

I am new with wordpress, I create a image uploader which followed a youtube video. But I found that it is only showed when I create new page. I can not add the uploader to the new page.
This is my code:
For php file
namespace image_uploader;
function register_metaboxes() {
add_meta_box('image_metabox','Image Uploader', __NAMESPACE__ . '\image_uploader_callback');
}
add_action('add_meta_boxes', __NAMESPACE__ . '\register_metaboxes');
function register_admin_script() {
wp_enqueue_script('wp_img_upload', plugins_url('image-upload.js', __FILE__), array('jquery', 'media-upload'), '1.0', true);
}
add_action('admin_enqueue_scripts', __NAMESPACE__ . '\register_admin_script');
function image_uploader_callback( $post_id ) {
wp_nonce_field( basename( __FILE__ ), 'image_nonce' );
$image_stored_meta = get_post_meta( $post_id );
?>
<div class="image-preview-wrapper">
<img id="image-preview" src="<?php if ( isset ( $image_stored_meta['image_meta'] ) ) echo $image_stored_meta['image_meta'][0]; ?>" style="max-width: 250px;">
<input type="hidden" name="image_meta" id="image-meta">
<button type="button" id="image-upload-button" class="button">Upload Image</button>
<button type="button" id="image-remove-button" class="button">Remove Image</button>
</div>
<button id="nextPage">move to the next page</button>
<?php
}
function save_custom_meta( $post_id, $post, $update ) {
// Checks save status
$is_autosave = wp_is_post_autosave( $post_id );
$is_revision = wp_is_post_revision( $post_id );
$is_valid_nonce = ( isset( $_POST[ 'image_nonce' ] ) && wp_verify_nonce( $_POST[ 'image_nonce' ], basename( __FILE__ ) ) ) ? 'true' : 'false';
// Exits script depending on save status
if ( $is_autosave || $is_revision || !$is_valid_nonce ) {
return;
}
// Checks for input and sanitizes/saves if needed
if( isset( $_POST[ 'image_meta' ] ) ) {
$image_data = json_decode( stripslashes( $_POST[ 'image_meta' ] ), true );
if(is_object($image_data)) {
$image_data = array(
'id' => intval($image_data[0]->id),
'src' => esc_url_raw($image_data[0]->url),
'width' => intval($image_data[0]->width),
'height' => intval($image_data[0]->height)
);
} else {
$image_data=[];
}
update_post_meta( $post_id, 'image_meta', sanitize_text_field( $_POST[ 'image_meta' ] ) );
}
}
add_action( 'save_post', __NAMESPACE__ . '\save_custom_meta', 10, 3 );
add_filter('wp_handle_upload_prefilter','tc_handle_upload_prefilter');
function tc_handle_upload_prefilter($file)
{
$img=getimagesize($file['tmp_name']);
$fixedSize = array('width' => '400', 'height' => '600');
$width= $img[0];
$height =$img[1];
if ($width != $fixedSize['width'] )
return array("error"=>"Image dimensions are too small. Minimum width is {$fixedSize['width']}px. Uploaded image width is $width px");
elseif ($height != $fixedSize['height'])
return array("error"=>"Image dimensions are too small. Minimum height is {$fixedSize['height']}px. Uploaded image height is $height px");
else
return $file;
}
for js file
addEventListener("DOMContentLoaded", function() {
console.log('DOMContentLoaded');
var addButton = document.getElementById('image-upload-button');
var removeButton = document.getElementById('image-remove-button');
var image = document.getElementById('image-preview');
var hidden = document.getElementById('image-meta');
var next = document.getElementById('nextPage');
image.setAttribute('required', 'required');
var uploader = wp.media({
title: 'Select an image',
button: {
text: 'Use this image'
},
multiple: false
});
addButton.addEventListener('click', function(e) {
e.preventDefault();
if(uploader) {
uploader.open();
}
});
uploader.on('select', function() {
var attachment = uploader.state().get('selection').first().toJSON();
image.setAttribute('src', attachment.url);
hidden.setAttribute('value', JSON.stringify({id: attachment.id, url: attachment.url}));
});
removeButton.addEventListener('click', function(e) {
image.removeAttribute('src');
hidden.removeAttribute('value');
});
next.addEventListener('click', function(e) {
e.preventDefault();
window.location.href = "http://google.com";
});
});
I did a lot of research, but still can not figure it out.
Please give me some advices, thanks a lot!

Woocommerce - Sorting Custom Product Category Meta

I want to sort the custom meta content that I have created for the product category. Content is usually text. My aim is to sort the empty ones in order to easily detect them. If text is available, it can give priority to letter length. I can't get any changes with the following codes. Thanks.
function list_fill( $columns, $column, $id ) {
if ( $column = 'my_custom_column' ) {
$columns = esc_html( get_term_meta($id, '_my_custom_data', true) );
}
return $columns;
}
add_action( 'manage_product_cat_custom_column', 'list_fill' , 10, 3);
function sortlist( $columns ) {
$columns['my_custom_column'] = 'my_custom_column';
return $columns;
}
add_filter( 'manage_edit-product_cat_sortable_columns', 'sortlist' );
function sortlist_orderby( $query ) {
$orderby = $query->get( 'orderby');
if( 'my_custom_column' == $orderby ) {
$query->set('meta_key','_my_custom_data');
$query->set('orderby','meta_value');
}
}
add_action( 'pre_get_posts', 'sortlist_orderby' );
This is how i usualy register new column.
// Add New column
function my_add_new_columns($columns) {
$new_columns = array(
'my_custom_column' => esc_html__( 'Custom Column', 'text_domain' ),
);
return array_merge($columns,$new_columns);
}
add_filter( 'manage_edit-product_cat_columns', 'my_add_new_columns',10,1 );
The rest of the code should be fine but in case here is a full example how i register column, populate values and sort.
// Add New column
function my_add_new_columns($columns) {
$new_columns = array(
'custom_column' => esc_html__( 'Custom Column', 'text_domain' ),
);
return array_merge($columns,$new_columns);
}
add_filter( 'manage_edit-product_cat_columns', 'my_add_new_columns',10,1 );
// Add data to sort
function custom_column_data($argument, $columnName, $termID) {
if ( $columnName == 'custom_column' ) {
echo get_term_meta( $termID, '_product_cat_thumb', true );
}
}
add_action('manage_product_cat_custom_column','custom_column_data',10,3);
//Make column sortable
function custom_sortable_column() {
$columns['custom_column'] = 'custom_column';
return $columns;
}
add_filter( 'manage_edit-product_cat_sortable_columns', 'custom_sortable_column' );
//Config how your sorting should work
function custom_column_orderby($query) {
$orderby = $query->get( 'orderby' );
if ( 'custom_column' == $orderby ) {
$query->set('meta_key','_product_cat_thumb');
$query->set('orderby','meta_value');
}
}
add_action( 'pre_get_posts', 'custom_column_orderby' );

can not add woocommerce order filter by vendors

woocommerce order page in, I want to filter orders by vendor. I am using the wcfm marketplace plugin.
Vendor name appears here. but when I filter, the orders are not listed.
please help :(woocommerce order page
function wcmp_admin_filter_by_vendor() {
global $typenow;
if ($typenow == 'shop_order') {
$admin_dd_html = '<select name="admin_order_vendor" id="dropdown_admin_order_vendor"><option value="">'.__("Show All Vendors", "dc-woocommerce-multi-vendor").'</option>';
$vendors = get_wcmp_vendors();
if($vendors) :
foreach ($vendors as $vendor) {
$admin_dd_html .= '<option value="'.$vendor->term_id.'">'.$vendor->page_title.'</option>';
}
endif;
$admin_dd_html .= '</select>';
echo $admin_dd_html;
}
}
add_action( 'restrict_manage_posts', 'wcmp_admin_filter_by_vendor');
function get_vendor_parent_order($id) {
$vendor_orders = get_posts( array(
'numberposts' => -1,
'meta_key' => '_vendor_id',
'meta_value' => $id,
'post_type' => 'shop_order',
'post_status' => 'any',
) );
foreach( $vendor_orders as $vendor_order ) {
$parent_order = wp_get_post_parent_id( $vendor_order->ID );
$parent_orders[] = $parent_order;
}
return $parent_orders;
}
function filter_orders_by_vendor_in_admin_dashboard( $query ) {
if (current_user_can('administrator') && !empty($_REQUEST['admin_order_vendor'])) {
$vendor_term_id = isset($_GET['admin_order_vendor'])?$_GET['admin_order_vendor']:'';
$vendor = get_wcmp_vendor_by_term($vendor_term_id);
$parent_orders = get_vendor_parent_order($vendor->id);
$query['post__in'] = $parent_orders;
return $query;
}
return $query;
}
add_filter( 'wcmp_shop_order_query_request', 'filter_orders_by_vendor_in_admin_dashboard');
function remove_wcmp_order_hook() {
global $WCMp;
remove_action( 'manage_shop_order_posts_custom_column', array($WCMp->order, 'wcmp_show_shop_order_columns'), 99, 2 );
}
add_action('init', 'remove_wcmp_order_hook');
function wcmp_show_shop_order_columns($column, $post_id) {
global $WCMp;
switch ($column) {
case 'wcmp_suborder' :
$wcmp_suborders = $WCMp->order->get_suborders($post_id);
if ($wcmp_suborders) {
echo '<ul class="wcmp-order-vendor" style="margin:0px;">';
foreach ($wcmp_suborders as $suborder) {
$vendor = get_wcmp_vendor(get_post_field('post_author', $suborder->get_id()));
$vendor->ID = get_post_field('post_author', $suborder->get_id());
$vendor_term_id = isset($_GET['admin_order_vendor'])?$_GET['admin_order_vendor']:'';
$filter_vendor = get_wcmp_vendor_by_term($vendor_term_id);
$filter_vendor_id = isset($filter_vendor->id)?$filter_vendor->id:'';
if( $vendor->ID == $filter_vendor_id || $filter_vendor_id == '' ) {
$order_uri = apply_filters('wcmp_admin_vendor_shop_order_edit_url', esc_url('post.php?post=' . $suborder->get_id() . '&action=edit'), $suborder->get_id());
printf('<li><mark class="%s tips" data-tip="%s">%s</mark> <strong>#%s</strong> – <small class="wcmp-order-for-vendor">%s %s</small></li>', sanitize_title($suborder->get_status()), $suborder->get_status(), $suborder->get_status(), $order_uri, $suborder->get_order_number(), _x('for', 'Order table details', 'dc-woocommerce-multi-vendor'), $vendor->page_title
);
}
do_action('wcmp_after_suborder_details', $suborder);
}
echo '<ul>';
} else {
echo '<span class="na">–</span>';
}
break;
}
}
add_action('manage_shop_order_posts_custom_column', 'wcmp_show_shop_order_columns', 99, 2);

WooCommerce Variations as Radio Buttons

is it possible within WooCommerce to change the variations dropdown into radio buttons without having to work with a plugin? I would like to have the following setup on the variations section:
1 liter (10€)
2 liter (20€)
3 Liter (25€)
The price at the bottom should be automatically changed when you select an option.
Thank you
EDIT: added variation_check() and JS variation checking thanks to #ThomasB!
EDIT2: make sure variation_check() also checks for backorder status to allow selection when a product can be backordered.
The best way I managed to get this working is to add radio button markup directly after the select dropdowns and then hide the select dropdowns using CSS. You'll also need some custom JS to trigger the hidden select value changes so that your price will change according to the radio button you select.
Here's how I added the markup:
function variation_radio_buttons($html, $args) {
$args = wp_parse_args(apply_filters('woocommerce_dropdown_variation_attribute_options_args', $args), array(
'options' => false,
'attribute' => false,
'product' => false,
'selected' => false,
'name' => '',
'id' => '',
'class' => '',
'show_option_none' => __('Choose an option', 'woocommerce'),
));
if(false === $args['selected'] && $args['attribute'] && $args['product'] instanceof WC_Product) {
$selected_key = 'attribute_'.sanitize_title($args['attribute']);
$args['selected'] = isset($_REQUEST[$selected_key]) ? wc_clean(wp_unslash($_REQUEST[$selected_key])) : $args['product']->get_variation_default_attribute($args['attribute']);
}
$options = $args['options'];
$product = $args['product'];
$attribute = $args['attribute'];
$name = $args['name'] ? $args['name'] : 'attribute_'.sanitize_title($attribute);
$id = $args['id'] ? $args['id'] : sanitize_title($attribute);
$class = $args['class'];
$show_option_none = (bool)$args['show_option_none'];
$show_option_none_text = $args['show_option_none'] ? $args['show_option_none'] : __('Choose an option', 'woocommerce');
if(empty($options) && !empty($product) && !empty($attribute)) {
$attributes = $product->get_variation_attributes();
$options = $attributes[$attribute];
}
$radios = '<div class="variation-radios">';
if(!empty($options)) {
if($product && taxonomy_exists($attribute)) {
$terms = wc_get_product_terms($product->get_id(), $attribute, array(
'fields' => 'all',
));
foreach($terms as $term) {
if(in_array($term->slug, $options, true)) {
$id = $name.'-'.$term->slug;
$radios .= '<input type="radio" id="'.esc_attr($id).'" name="'.esc_attr($name).'" value="'.esc_attr($term->slug).'" '.checked(sanitize_title($args['selected']), $term->slug, false).'><label for="'.esc_attr($id).'">'.esc_html(apply_filters('woocommerce_variation_option_name', $term->name)).'</label>';
}
}
} else {
foreach($options as $option) {
$id = $name.'-'.$option;
$checked = sanitize_title($args['selected']) === $args['selected'] ? checked($args['selected'], sanitize_title($option), false) : checked($args['selected'], $option, false);
$radios .= '<input type="radio" id="'.esc_attr($id).'" name="'.esc_attr($name).'" value="'.esc_attr($option).'" id="'.sanitize_title($option).'" '.$checked.'><label for="'.esc_attr($id).'">'.esc_html(apply_filters('woocommerce_variation_option_name', $option)).'</label>';
}
}
}
$radios .= '</div>';
return $html.$radios;
}
add_filter('woocommerce_dropdown_variation_attribute_options_html', 'variation_radio_buttons', 20, 2);
function variation_check($active, $variation) {
if(!$variation->is_in_stock() && !$variation->backorders_allowed()) {
return false;
}
return $active;
}
add_filter('woocommerce_variation_is_active', 'variation_check', 10, 2);
And here's the JS I used:
$(document).on('change', '.variation-radios input', function() {
$('.variation-radios input:checked').each(function(index, element) {
var $el = $(element);
var thisName = $el.attr('name');
var thisVal = $el.attr('value');
$('select[name="'+thisName+'"]').val(thisVal).trigger('change');
});
});
$(document).on('woocommerce_update_variation_values', function() {
$('.variation-radios input').each(function(index, element) {
var $el = $(element);
var thisName = $el.attr('name');
var thisVal = $el.attr('value');
$el.removeAttr('disabled');
if($('select[name="'+thisName+'"] option[value="'+thisVal+'"]').is(':disabled')) {
$el.prop('disabled', true);
}
});
});
I don't know how to do that without a plugin, but I suggest you drop that requirement, and use the Woocommerce Radio Buttons plugin. This does exactly what you want:
You can use Variation Swatches for WooCommerce plugin. It worked for me.
I extended further the JavaScript part of cfx' answer to include cases of multiple variations. The idea is to hide and show available variations (radio buttons) based on the select inputs.
<script>
jQuery(document).on('change', '.variation-radios input', function() {
jQuery('.variation-radios input:checked').each(function(index, element) {
let el = jQuery(element);
jQuery('select[name="' + el.attr('name') + '"]').val(el.attr('value')).trigger('change');
recreateRadioInputs();
});
});
jQuery(document).on('woocommerce_update_variation_values', function() {
jQuery('.variation-radios input').each(function(index, element) {
let el = jQuery(element);
el.removeAttr('disabled');
if(jQuery('select[name="' + el.attr('name') + '"] option[value="' + el.attr('value') + '"]').is(':disabled')) {
$el.prop('disabled', true);
}
});
});
// recreate readio inputs based on the select inputs
function recreateRadioInputs() {
jQuery('.variation-radios input, .variation-radios label').hide();
jQuery('.variations select').each(function() {
let inputName = jQuery(this).attr('name');
jQuery(this).find('option').each(function() {
let inputVal = jQuery(this).val();
let radioInput = jQuery('.variation-radios input[value="' + inputVal + '"]');
jQuery('.variation-radios label[for="' + radioInput.attr('id') + '"]').show();
radioInput.show();
});
});
}
</script>

Extending WP_List_Table / handling checkbox options in plugin administration

I'm working on a WordPress plugin, and part of that plugin requires extending WP_List_Table and storing any of the items which are checked in that table to an option. I've managed to figure out how to properly setup and display the required table, but how do I handle storing the checked options?
Here's what I've got so far...
class TDBar_List_Table extends WP_List_Table {
// Reference parent constructor
function __construct() {
global $status, $page;
// Set defaults
parent::__construct( array(
'singular' => 'theme',
'plural' => 'themes',
'ajax' => false
));
}
// Set table classes
function get_table_classes() {
return array('widefat', 'wp-list-table', 'themes');
}
// Setup default column
function column_default($item, $column_name) {
switch($column_name) {
case 'Title':
case 'URI':
case'Description':
return $item[$column_name];
default:
return print_r($item, true);
}
}
// Displaying checkboxes!
function column_cb($item) {
return sprintf(
'<input type="checkbox" name="%1$s" id="%2$s" value="checked" />',
//$this->_args['singular'],
$item['Stylesheet'] . '_status',
$item['Stylesheet'] . '_status'
);
}
// Display theme title
function column_title($item) {
return sprintf(
'<strong>%1$s</strong>',
$item['Title']
);
}
// Display theme preview
function column_preview($item) {
if (file_exists(get_theme_root() . '/' . $item['Stylesheet'] . '/screenshot.png')) {
$preview = get_theme_root_uri() . '/' . $item['Stylesheet'] . '/screenshot.png';
} else {
$preview = '';
}
return sprintf(
'<img src="%3$s" style="width: 150px;" />',
$preview,
$item['Title'],
$preview
);
}
// Display theme description
function column_description($item) {
if (isset($item['Version'])) {
$version = 'Version ' . $item['Version'];
if (isset($item['Author']) || isset($item['URI']))
$version .= ' | ';
} else {
$version = '';
}
if (isset($item['Author'])) {
$author = 'By ' . $item['Author'];
if (isset($item['URI']))
$author .= ' | ';
} else {
$author = '';
}
if (isset($item['URI'])) {
$uri = $item['URI'];
} else {
$uri = '';
}
return sprintf(
'<div class="theme-description"><p>%1$s</p></div><div class="second theme-version-author-uri">%2$s%3$s%4$s',
$item['Description'],
$version,
$author,
$uri
);
}
// Setup columns
function get_columns() {
$columns = array(
'cb' => '<input type="checkbox" />',
'title' => 'Theme',
'preview' => 'Preview',
'description' => 'Description'
);
return $columns;
}
// Make title column sortable
function get_sortable_columns() {
$sortable_columns = array(
'title' => array('Title', true)
);
return $sortable_columns;
}
// Setup bulk actions
function get_bulk_actions() {
$actions = array(
'update' => 'Update'
);
return $actions;
}
// Handle bulk actions
function process_bulk_action() {
// Define our data source
if (defined('WP_ALLOW_MULTISITE') && WP_ALLOW_MULTISITE == true) {
$themes = get_allowed_themes();
} else {
$themes = get_themes();
}
if ('update' === $this->current_action()) {
foreach ($themes as $theme) {
if ($theme['Stylesheet'] . '_status' == 'checked') {
// Do stuff - here's the problem
}
}
}
}
// Handle data preparation
function prepare_items() {
// How many records per page?
$per_page = 10;
// Define column headers
$columns = $this->get_columns();
$hidden = array();
$sortable = $this->get_sortable_columns();
// Build the array
$this->_column_headers = array($columns, $hidden, $sortable);
// Pass off bulk action
$this->process_bulk_action();
// Define our data source
if (defined('WP_ALLOW_MULTISITE') && WP_ALLOW_MULTISITE == true) {
$themes = get_allowed_themes();
} else {
$themes = get_themes();
}
// Handle sorting
function usort_reorder($a,$b) {
$orderby = (!empty($_REQUEST['orderby'])) ? $_REQUEST['orderby'] : 'Title';
$order = (!empty($_REQUEST['order'])) ? $_REQUEST['order'] : 'asc';
$result = strcmp($a[$orderby], $b[$orderby]);
return ($order === 'asc') ? $result : -$result;
}
usort($themes, 'usort_reorder');
//MAIN STUFF HERE
//for ($i = 0; i < count($themes); $i++) {
//}
// Figure out the current page and how many items there are
$current_page = $this->get_pagenum();
$total_items = count($themes);
// Only show the current page
$themes = array_slice($themes,(($current_page-1)*$per_page),$per_page);
// Display sorted data
$this->items = $themes;
// Register pagination options
$this->set_pagination_args( array(
'total_items' => $total_items,
'per_page' => $per_page,
'total_pages' => ceil($total_items/$per_page)
));
}
}
Problem is, I can't get it to save properly. I select the rows I want, hit save and it just resets.
I assume you are talking about the checkboxes in your table listing, so this will be how to process bulk actions.
All you need to do is add two new methods to your class and initialize it in the prepare_items method. I use the code below in one of my plugins to delete or export, but you can just as easily run an update.
/**
* Define our bulk actions
*
* #since 1.2
* #returns array() $actions Bulk actions
*/
function get_bulk_actions() {
$actions = array(
'delete' => __( 'Delete' , 'visual-form-builder'),
'export-all' => __( 'Export All' , 'visual-form-builder'),
'export-selected' => __( 'Export Selected' , 'visual-form-builder')
);
return $actions;
}
/**
* Process our bulk actions
*
* #since 1.2
*/
function process_bulk_action() {
$entry_id = ( is_array( $_REQUEST['entry'] ) ) ? $_REQUEST['entry'] : array( $_REQUEST['entry'] );
if ( 'delete' === $this->current_action() ) {
global $wpdb;
foreach ( $entry_id as $id ) {
$id = absint( $id );
$wpdb->query( "DELETE FROM $this->entries_table_name WHERE entries_id = $id" );
}
}
}
Now, call this method inside prepare_items() like so:
function prepare_items() {
//Do other stuff in here
/* Handle our bulk actions */
$this->process_bulk_action();
}
There's a fantastic helper plugin called Custom List Table Example that makes figuring out the WP_List_Table class much easier.

Resources