Update post terms in each languages by code - wordpress

who can hellp with this, i need create post from code, by wp_insert_post
function, so what is going on:
I creating post on each existing laguages, then i update all needed fields and i need to set post term depened of current language.
I have terms (shelters) https://prnt.sc/pklSXojB2jZj - i need that post set to current lang shelter while create, but after creating i got - https://prnt.sc/pz2jFEq1OAMP , 2 posts set in one lang terms. Maybe who know whats goes wrong, below i provided 2 functions who do these actions, Thanks in advance:
function add_pet($form_data, $ready_data, $update_meta = false) {
$allLang = pll_languages_list();
if ($allLang) {
$postsArr = array();
foreach ($allLang as $lang) {
//Add new pet
$post_id = wp_insert_post(array(
'post_title' => $form_data['pet_name'],
'post_status' => 'publish',
'post_author' => $form_data['user_id'],
'post_type' => 'pets',
));
//Check if post created, update all needed fields, and update post terms (shelter)
if ($post_id) {
//Get all translation of term
$shelter_id = pll_get_term(intval($form_data['shelter']), $lang);
$update_meta['shelter'] = $shelter_id;
//In this function we update those terms
$update_success = update_pets_fields($post_id, $ready_data, $update_meta);
$postsArr[$lang] = $post_id;
pll_set_post_language($post_id, $lang);
$postDate = get_post($post_id)->post_date;
$unixDate = strtotime($postDate);
update_post_meta($post_id, 'pet_update_date', $unixDate);
}
}
//Save post translation
if ($postsArr) {
pll_save_post_translations($postsArr);
}
//Old code
// foreach ($allLang as $lang) {
// $cat_id = pll_get_term(intval($form_data['kind_of_animal']), $lang);
// $shelter_id = pll_get_term(intval($form_data['shelter']), $lang);
// $post_id = $postsArr[$lang];
// $update_meta['post_category'] = $cat_id;
// $update_meta['shelter'] = $shelter_id;
// $update_success = update_pets_fields($post_id, $ready_data, $update_meta);
// }
}
if (is_wp_error($post_id)) {
wp_send_json_error($post_id->get_error_message());
}
if ($update_success) {
wp_send_json_success('Post was created.');
} else {
wp_send_json_error('Post was not created.');
}
}
And function who update field
/Update pets fields
function update_pets_fields($post_id, $data, $update_meta = false) {
if (!$post_id) return;
//Update post meta data not acf
if (isset($update_meta) && !empty($update_meta['title'])) {
$post_update = array(
'ID' => $post_id,
'post_title' => $update_meta['title']
);
$result = wp_update_post($post_update);
if (is_wp_error($result)) {
wp_send_json_error('Fields was not updated');
}
}
if (isset($update_meta['shelter']) && !empty($update_meta['shelter']) && intval($update_meta['shelter'])) {
wp_remove_object_terms($post_id, 'uncategorized', 'sholters');
$shelter_id = intval($update_meta['shelter']);
wp_set_post_terms($post_id, array($shelter_id), 'sholters');
if (is_wp_error($result)) {
wp_send_json_error('Term not updated');
}
}
if (isset($update_meta['post_category']) && !empty($update_meta['post_category']) && intval($update_meta['post_category'])) {
wp_remove_object_terms($post_id, 'uncategorized', 'category');
wp_set_post_categories($post_id, intval($update_meta['post_category']));
if (is_wp_error($result)) {
wp_send_json_error('Category not updated');
}
}
if (isset($update_meta['thumbnail']) && !empty($update_meta['thumbnail']) && intval($update_meta['thumbnail'])) {
set_post_thumbnail($post_id, intval($update_meta['thumbnail']));
}
if (is_null($data)) {
wp_send_json_error('No data.');
}
foreach ($data as $field) {
if ($field[3] === 'where_is') {
$field_array['field_62169d3cffb5b'] = array(
$field[2] => $field[1],
);
} else {
$field_array = array(
$field[2] => $field[1],
);
}
if (!empty($field[1])) {
$result = update_field('field_621696a7ffb4e', $field_array, $post_id);
}
}
if ($result) {
return false;
} else {
return true;
}
}
I try update it in diferent variants but it does't work, i check ids that come in args all ids is right and all posts ids is right.But on at the exit we got 2 posts in 1 term

Related

Is there any function in Leandash to mark complete COURSE programmatically

I am working on Leandash Project , Now my requirement is some students have completed the course offline , So I have created a screen for a group leader in which the group leader can select group/user/course and also add date like this ( https://prnt.sc/1bfcq3a ) and can mark complete COURSE.
So my question is how do I mark complete COURSE. programmatically on link click.
here is my code , which is not working
jQuery(document).on('click', '.course_complete_save', function(event) {
event.preventDefault();
var selected_group_id = jQuery('#group_name_select_dropdown').val();
var selected_user_id = jQuery('#user_name_select_dropdown').val();
var selected_course_id = jQuery('#course_name_select_dropdown').val();
var mark_complete_date = jQuery('#input_date_field').val();
var params = {"mark_complete_date":mark_complete_date,"selected_group_id":selected_group_id,"selected_user_id":selected_user_id,"selected_course_id":selected_course_id,action:"mark_complete_course_ajax"}
jQuery.post(groupcustomisation.ajaxurl,params,function(data){
if(data){
jQuery(".mark_complete_success").empty().append("Mark Completed");
}else{
jQuery(".mark_complete_success").empty().append("No data Found");
}
});
});
<?php
add_action('wp_ajax_nopriv_mark_complete_course_ajax', 'mark_complete_course_ajax');
add_action('wp_ajax_mark_complete_course_ajax', 'mark_complete_course_ajax');
function mark_complete_course_ajax() {
$selected_group_id = $_POST['selected_group_id'];
$selected_user_id = $_POST['selected_user_id'];
$selected_course_id = $_POST['selected_course_id'];
$mark_complete_date = $_POST['mark_complete_date'];
learndash_process_mark_complete( $selected_user_id, $selected_course_id, true, $selected_course_id );
echo "1";
die();
}
Funny enough, i found myself needing solution to same problem minutes after you posted this yesterday and as you see, that function above failed to work and nothing useful online. In short, i spent the whole day on it trying to find why until i realized all lessons and quiz need to be marked as complete too and after writing the function that do exactly this based on my research on learndash source code as primary source, i decided to come back here and post the function just incase you haven't fix it
Usage: sci_learndash_mark_course_complete($course_id, $user_id)
Here's the function:
/**
* Mark learndash course as complete.
*
* #param int $id Course ID.
* #param int $user_id User ID.
*/
function sci_learndash_mark_course_complete($id, $user_id)
{
//retreive current course progress
$user_progress['course'][$id] = learndash_user_get_course_progress($user_id, $id, 'legacy');
if (isset($user_progress['course'][$id]['lessons'])) {
//update lessons progress to complete
$lesson_array = $user_progress['course'][$id]['lessons'];
$lessons = array_flip($lesson_array);
$lessons = array_fill_keys(array_keys($lesson_array), 1);
$user_progress['course'][$id]['lessons'] = $lessons;
}
//update topics progress to complete
if (isset($user_progress['course'][$id]['topics'])) {
foreach($user_progress['course'][$id]['topics'] as $ldtopic_key => $ldtopic){
if(count($ldtopic) > 0){
$new_ldtopic = array_flip($ldtopic);
$new_ldtopic = array_fill_keys(array_keys($ldtopic), 1);
$user_progress['course'][$id]['topics'][$ldtopic_key] = $new_ldtopic;
}
}
}
//update quiz progress to complete
if (isset($user_progress['quiz'][$id])) {
$quiz_array = $user_progress['course'][$id]['quiz'];
$quiz = array_flip($quiz_array);
$quiz = array_fill_keys(array_keys($quiz_array), 1);
$user_progress['course'][$id]['quiz'] = $quiz;
}else{
$quiz_list = [];
if ( isset($user_progress['course'][$id]['lessons']) && count($user_progress['course'][$id]['lessons']) > 0 ) {
$ld_lesson_keys = array_keys($user_progress['course'][$id]['lessons']);
foreach($ld_lesson_keys as $course_lesson_id){
$topic_quizzes = learndash_get_lesson_quiz_list( $course_lesson_id );
if (!empty($topic_quizzes)){
foreach ($topic_quizzes as $topic_quiz) {
$quiz_list[$topic_quiz['post']->ID] = 1;
}
}
}
}
if (!empty($quiz_list)){
$user_progress['quiz'][$id] = $quiz_list;
}
}
$processed_course_ids = [];
if ((isset($user_progress['course'])) && (!empty($user_progress['course']))) {
$usermeta = get_user_meta($user_id, '_sfwd-course_progress', true);
$course_progress = empty($usermeta) ? [] : $usermeta;
$course_changed = false; // Simple flag to let us know we changed the quiz data so we can save it back to user meta.
foreach ($user_progress['course'] as $course_id => $course_data_new) {
$processed_course_ids[intval($course_id)] = intval($course_id);
if (isset($course_progress[$course_id])) {
$course_data_old = $course_progress[$course_id];
} else {
$course_data_old = [];
}
$course_data_new = learndash_course_item_to_activity_sync($user_id, $course_id, $course_data_new,
$course_data_old);
$course_progress[$course_id] = $course_data_new;
$course_changed = true;
}
if (true === $course_changed) {
update_user_meta($user_id, '_sfwd-course_progress', $course_progress);
}
}
if ((isset($user_progress['quiz'])) && (!empty($user_progress['quiz']))) {
$usermeta = get_user_meta($user_id, '_sfwd-quizzes', true);
$quizz_progress = empty($usermeta) ? [] : $usermeta;
$quiz_changed = false; // Simple flag to let us know we changed the quiz data so we can save it back to user meta.
foreach ($user_progress['quiz'] as $course_id => $course_quiz_set) {
foreach ($course_quiz_set as $quiz_id => $quiz_new_status) {
$quiz_meta = get_post_meta($quiz_id, '_sfwd-quiz', true);
if (!empty($quiz_meta)) {
$quiz_old_status = !learndash_is_quiz_notcomplete($user_id, [$quiz_id => 1], false, $course_id);
// For Quiz if the admin marks a qiz complete we don't attempt to update an existing attempt for the user quiz.
// Instead we add a new entry. LD doesn't care as it will take the complete one for calculations where needed.
if ((bool)true === (bool)$quiz_new_status) {
if ((bool)true !== (bool)$quiz_old_status) {
if (isset($quiz_meta['sfwd-quiz_lesson'])) {
$lesson_id = absint($quiz_meta['sfwd-quiz_lesson']);
} else {
$lesson_id = 0;
}
if (isset($quiz_meta['sfwd-quiz_topic'])) {
$topic_id = absint($quiz_meta['sfwd-quiz_topic']);
} else {
$topic_id = 0;
}
// If the admin is marking the quiz complete AND the quiz is NOT already complete...
// Then we add the minimal quiz data to the user profile.
$quizdata = [
'quiz' => $quiz_id,
'score' => 0,
'count' => 0,
'question_show_count' => 0,
'pass' => true,
'rank' => '-',
'time' => time(),
'pro_quizid' => absint($quiz_meta['sfwd-quiz_quiz_pro']),
'course' => $course_id,
'lesson' => $lesson_id,
'topic' => $topic_id,
'points' => 0,
'total_points' => 0,
'percentage' => 0,
'timespent' => 0,
'has_graded' => false,
'statistic_ref_id' => 0,
'm_edit_by' => get_current_user_id(), // Manual Edit By ID.
'm_edit_time' => time(), // Manual Edit timestamp.
];
$quizz_progress[] = $quizdata;
if (true === $quizdata['pass']) {
$quizdata_pass = true;
} else {
$quizdata_pass = false;
}
// Then we add the quiz entry to the activity database.
learndash_update_user_activity(
[
'course_id' => $course_id,
'user_id' => $user_id,
'post_id' => $quiz_id,
'activity_type' => 'quiz',
'activity_action' => 'insert',
'activity_status' => $quizdata_pass,
'activity_started' => $quizdata['time'],
'activity_completed' => $quizdata['time'],
'activity_meta' => $quizdata,
]
);
$quiz_changed = true;
if ((isset($quizdata['course'])) && (!empty($quizdata['course']))) {
$quizdata['course'] = get_post($quizdata['course']);
}
if ((isset($quizdata['lesson'])) && (!empty($quizdata['lesson']))) {
$quizdata['lesson'] = get_post($quizdata['lesson']);
}
if ((isset($quizdata['topic'])) && (!empty($quizdata['topic']))) {
$quizdata['topic'] = get_post($quizdata['topic']);
}
/**
* Fires after the quiz is marked as complete.
*
* #param arrat $quizdata An array of quiz data.
* #param WP_User $user WP_User object.
*/
do_action('learndash_quiz_completed', $quizdata, get_user_by('ID', $user_id));
}
} elseif (true !== $quiz_new_status) {
// If we are unsetting a quiz ( changing from complete to incomplete). We need to do some complicated things...
if (true === $quiz_old_status) {
if (!empty($quizz_progress)) {
foreach ($quizz_progress as $quiz_idx => $quiz_item) {
if (($quiz_item['quiz'] == $quiz_id) && (true === $quiz_item['pass'])) {
$quizz_progress[$quiz_idx]['pass'] = false;
// We need to update the activity database records for this quiz_id
$activity_query_args = [
'post_ids' => $quiz_id,
'user_ids' => $user_id,
'activity_type' => 'quiz',
];
$quiz_activity = learndash_reports_get_activity($activity_query_args);
if ((isset($quiz_activity['results'])) && (!empty($quiz_activity['results']))) {
foreach ($quiz_activity['results'] as $result) {
if ((isset($result->activity_meta['pass'])) && (true === $result->activity_meta['pass'])) {
// If the activity meta 'pass' element is set to true we want to update it to false.
learndash_update_user_activity_meta($result->activity_id, 'pass',
false);
// Also we need to update the 'activity_status' for this record
learndash_update_user_activity(
[
'activity_id' => $result->activity_id,
'course_id' => $course_id,
'user_id' => $user_id,
'post_id' => $quiz_id,
'activity_type' => 'quiz',
'activity_action' => 'update',
'activity_status' => false,
]
);
}
}
}
$quiz_changed = true;
}
/**
* Remove the quiz lock.
*
* #since 2.3.1
*/
if ((isset($quiz_item['pro_quizid'])) && (!empty($quiz_item['pro_quizid']))) {
learndash_remove_user_quiz_locks($user_id, $quiz_item['quiz']);
}
}
}
}
}
$processed_course_ids[intval($course_id)] = intval($course_id);
}
}
}
if (true === $quiz_changed) {
update_user_meta($user_id, '_sfwd-quizzes', $quizz_progress);
}
}
if (!empty($processed_course_ids)) {
foreach (array_unique($processed_course_ids) as $course_id) {
learndash_process_mark_complete($user_id, $course_id);
learndash_update_group_course_user_progress($course_id, $user_id);
}
}
}

Rename comments labels in WP admin

Is it possible to change default comments in wordpress admin?
I`d like to rename comments into testimonials everywhere in admin.
If you want to change all WordPress uses of 'Comment', then you need to hook into the translation filter
is_admin() && add_filter('gettext', function ($translation, $text, $domain) {
if (strpos($translation, 'comment') !== FALSE) {
return str_replace('comment', 'testimonial', $translation);
}
if (strpos($translation, 'Comment') !== FALSE) {
return str_replace('Comment', 'Testimonial', $translation);
}
return $translation;
}, 10, 3);
But that changes EVERYTHING that runs through gettext.
If you just wanted to change the admin section title you would do this:
add_action('admin_head', function () {
global $wp_meta_boxes;
if (!empty($wp_meta_boxes)) {
foreach ($wp_meta_boxes as $page => &$positions) {
foreach ($positions as $context => &$priorities) {
foreach ($priorities as $priority => &$boxes) {
foreach ($boxes as $id => &$box) {
if ($id === 'commentsdiv') {
$box['title'] = 'Testimonials';
break;
}
}
}
}
}
}
});
Beyond that, you'd have to find every instance of 'Comment' and see if there was an associated hook for that situation. I'm not sure if that is feasible.

Use delete_user_meta

I want to delete my usermeta in table database but give nothing. it give me an error because its not array expected string parameter
function remove_meta(){
$role = 'client'; //Select user role
$users = get_users('role='.$role);
global $wpdb;
$stats = $wpdb->get_results("
SELECT ".$wpdb->prefix." group_clients.client_id
FROM ".$wpdb->prefix." group_clients
WHERE ".$wpdb->prefix." group_clients.group_id IN (1, 2, 5, 6)
", $users); // Fetch data by selective group ID
$stats = array();
if (is_array($stats) || is_object($stats)){
//foreach ((array) $stats as $stat){
foreach ($stats as $stat) {
delete_user_meta($stat->ID, 'terms_and_conditions');
}
echo 'Fini!';
}
}
Try below code you are doing confusing code. Do not do sql query unless it is really required.
$args = array(
'role' => 'customer', //client or whatever you required
);
//geting all user
$users = get_users( $args );
foreach ($users as $result)
{
//each user id
$userId = $result->ID;
if($userId != '')
{
//getting all user meta of particular user
$all_meta_for_user = get_user_meta( $userId );
if(is_array($all_meta_for_user))
{
foreach ($all_meta_for_user as $key => $value) {
$terms =get_user_meta($userid,'terms_and_conditions',true);
if($terms !=''){
delete_user_meta($userId, 'terms_and_conditions');
}
}
}
}
}
with hook
add_action('init','deletedata');
function deletedata()
{
if(!is_admin())
return;
if(!current_user_can('manage_options'))
return false;
$args = array(
'role' => 'customer', //client or whatever you required
);
//geting all user
$users = get_users( $args );
foreach ($users as $result)
{
//each user id
$userId = $result->ID;
if($userId != '')
{
//getting all user meta of particular user
$all_meta_for_user = get_user_meta( $userId );
if(is_array($all_meta_for_user))
{
foreach ($all_meta_for_user as $key => $value) {
# code...
$terms =get_user_meta($userid,'terms_and_conditions',true);
if($terms !=''){
delete_user_meta($userId, 'terms_and_conditions');
}
}
}
}
}
}

How to set a custom value for records in a Report?

The code below is a custom report I'm putting together, using SilverStripe 3.1.
The Title and ClassName values are working fine, but though I can get the Status for each Page I'm not sure how to set the Status value against each Page in the DataList. How can I do that?
Once that's done, the Status column should be populated.
class PageListByType extends SS_Report {
function title() {
return 'Page List by Type';
}
function description() {
return 'List all the pages in the site, along with their page type';
}
public function sourceRecords($params = array(), $sort = null, $limit = null) {
$pages = Page::get()->sort($sort);
foreach ($pages as $pagenum=>$page) {
$flags = $page->getStatusFlags();
if ($flags) {
foreach ($flags as $status) {
// if (isset($pages[$pagenum]->Status)) die(array($pages[$pagenum]->Status, $status)); #detect multiple statuses; not sure if this will happen
/////////////////////////
// The following line needs fixing:
/////////////////////////
$pages[$pagenum]->Status = "{$status['text']} ({$status['title']})";
}
}
}
// die($pages->debug());
return $pages;
}
public function columns() {
return array(
'Title' => _t('PageListByTypeReport.PageName', 'Page name'),
'ClassName' => _t('PageListByTypeReport.ClassName', 'Page type'),
'Status' => _t('PageListByTypeReport.Status', 'Status')
);
}
}
Edit: Thanks #Turnerj for your answer! My final working code is as follows:
class PageListByType extends SS_Report {
function title() {
return 'Page List by Type';
}
function description() {
return 'List all the pages in the site, along with their page type';
}
public function sourceRecords($params = array(), $sort = null, $limit = null) {
$pages = DataObject::get("SiteTree", "", "");
return $pages;
}
public function columns() {
return array(
'Title' => _t('PageListByTypeReport.PageName', 'Page name'),
'ClassName' => _t('PageListByTypeReport.ClassName', 'Page type'),
'Status' => _t('PageListByTypeReport.Status', 'Status')
);
}
}
and in Page.php:
public function getStatus() {
$flags = $this->getStatusFlags();
$result = array();
if ($flags) {
foreach ($flags as $status) {
$result[] = "{$status['text']} ({$status['title']})";
}
} else {
$result[] = 'Published';
}
return implode(', ', $result);
}
After further investigation, I recreated the issue and found the solution.
Overall, my solution involves what I suggested in the comments about bringing the status fetching to the actual Page by adding a getStatus function.
I described essentially the following:
public function getStatus()
{
return $this->getStatusFlags();
}
This technically is correct, it will get the status flags but you are right, it doesn't display them in the report. This is due to this function returning an array which the report does not understand to render.
My solution is to change this function to return a string so with a few simple edits combining what you wrote with what I wrote, we get the following:
public function getStatus()
{
$flags = $this->getStatusFlags();
$result = array();
if ($flags)
{
foreach ($flags as $status)
{
$result[] = "{$status['text']} ({$status['title']})";
}
}
return implode(', ', $result);
}
I've got one unique twist on combining our code, I add each status to an array and implode it back to a single string. This can seem a little excessive, by default getStatusFlag will return one key in the array. If however you have a DataExtension that has the updateStatusFlags method, you could add additional keys to the result.
Basically, I would leave the implode handling in if in the future you do have code that messes with the status flags.
Now, you might be able to do something similar using the $casting property on the Page but given you were essentially adding this function just for the report, it was cleaner to just update it directly.
I did notice that the status flags array is actually empty if the page is published which means your report won't have anything next to published pages. If that is your intention, great!
If not, you could do another little alteration:
public function getStatus()
{
$flags = $this->getStatusFlags();
$result = array();
if ($flags)
{
foreach ($flags as $status)
{
$result[] = "{$status['text']} ({$status['title']})";
}
}
else
{
$result[] = 'Published (The page has been published)';
}
return implode(', ', $result);
}
The if ($flags) will evaluate to false when there are no current statuses (aka. the page is published) due to automatic casting.
Have you tried with an anonymous function inside columns()?
class PageListByType extends SS_Report {
function title() {
return 'Page List by Type';
}
function description() {
return 'List all the pages in the site, along with their page type';
}
public function sourceRecords($params = array(), $sort = null, $limit = null) {
return Page::get()->sort($sort);
}
public function columns() {
return array(
'Title' => _t('PageListByTypeReport.PageName', 'Page name'),
'ClassName' => _t('PageListByTypeReport.ClassName', 'Page type'),
'Status' => array(
'title'=>_t('PageListByTypeReport.Status', 'Status'),
'formatting' => function($value, $item) {
$flags = $item->getStatusFlags();
$status = '';
if ($flags) {
foreach ($flags as $status) {
$status = "{$status['text']} ({$status['title']})";
}
}
return $status ? : _t('PageListByTypeReport.PagePublished', 'Page published');
}
)
);
}
}

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