Use delete_user_meta - wordpress

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

Related

How to do email validation by blocking some email domain names in wordpress?

I need to validate an email field in gravity form. We have some known list of email domains and need to validate whether that domains present or not and If that domains present means we need to show the error message.
What is the best way to implement that? Any plugin suggestions?
This is possible with the GW_Email_Domain_Validator snippet here:
https://gravitywiz.com/banlimit-email-domains-for-gravity-form-email-fields/
Full snippet as of July 18, 2020 included here. Use the link above to get the latest version.
<?php
/**
* Gravity Wiz // Gravity Forms // Email Domain Validator
*
* This snippets allows you to exclude a list of invalid domains or include a list of valid domains for your Gravity Form Email fields.
*
* #version 1.4
* #author David Smith <david#gravitywiz.com>
* #license GPL-2.0+
* #link http://gravitywiz.com/banlimit-email-domains-for-gravity-form-email-fields/
*/
class GW_Email_Domain_Validator {
private $_args;
function __construct($args) {
$this->_args = wp_parse_args( $args, array(
'form_id' => false,
'field_id' => false,
'domains' => false,
'validation_message' => __( 'Sorry, <strong>%s</strong> email accounts are not eligible for this form.' ),
'mode' => 'ban' // also accepts "limit"
) );
// convert field ID to an array for consistency, it can be passed as an array or a single ID
if($this->_args['field_id'] && !is_array($this->_args['field_id']))
$this->_args['field_id'] = array($this->_args['field_id']);
$form_filter = $this->_args['form_id'] ? "_{$this->_args['form_id']}" : '';
add_filter("gform_validation{$form_filter}", array($this, 'validate'));
}
function validate($validation_result) {
$form = $validation_result['form'];
foreach($form['fields'] as &$field) {
// if this is not an email field, skip
if(RGFormsModel::get_input_type($field) != 'email')
continue;
// if field ID was passed and current field is not in that array, skip
if($this->_args['field_id'] && !in_array($field['id'], $this->_args['field_id']))
continue;
$page_number = GFFormDisplay::get_source_page( $form['id'] );
if( $page_number > 0 && $field->pageNumber != $page_number ) {
continue;
}
if( GFFormsModel::is_field_hidden( $form, $field, array() ) ) {
continue;
}
$domain = $this->get_email_domain($field);
// if domain is valid OR if the email field is empty, skip
if($this->is_domain_valid($domain) || empty($domain))
continue;
$validation_result['is_valid'] = false;
$field['failed_validation'] = true;
$field['validation_message'] = sprintf($this->_args['validation_message'], $domain);
}
$validation_result['form'] = $form;
return $validation_result;
}
function get_email_domain( $field ) {
$email = explode( '#', rgpost( "input_{$field['id']}" ) );
return trim( rgar( $email, 1 ) );
}
function is_domain_valid( $domain ) {
$mode = $this->_args['mode'];
$domain = strtolower( $domain );
foreach( $this->_args['domains'] as $_domain ) {
$_domain = strtolower( $_domain );
$full_match = $domain == $_domain;
$suffix_match = strpos( $_domain, '.' ) === 0 && $this->str_ends_with( $domain, $_domain );
$has_match = $full_match || $suffix_match;
if( $mode == 'ban' && $has_match ) {
return false;
} else if( $mode == 'limit' && $has_match ) {
return true;
}
}
return $mode == 'limit' ? false : true;
}
function str_ends_with( $string, $text ) {
$length = strlen( $string );
$text_length = strlen( $text );
if( $text_length > $length ) {
return false;
}
return substr_compare( $string, $text, $length - $text_length, $text_length ) === 0;
}
}
To only accept submissions from a given email domain you can do something like this:
new GW_Email_Domain_Validator( array(
'form_id' => 326,
'field_id' => 1,
'domains' => array( 'gmail.com', 'hotmail.com', '.co.uk' ),
'validation_message' => __( 'Oh no! <strong>%s</strong> email accounts are not eligible for this form.' ),
'mode' => 'limit'
) );

load my user_login from database into my acf select field code

I am trying to upload my user_login from database into acf select field, in var_dump my array result is working good, but nothing uploaded in my acf select field?
1. I added a custom field "ACF select field" in a product post.
2. I'm trying to load my options values from my database.
3. I used an array to get the user_login values from the database
function.php
add_filter('acf/load_field/name=chef', 'my_acf_load_chef_field');
function my_acf_load_chef_field( $field )
{
$user_fields = array( 'user_login');
$argu = new WP_User_Query( array( 'role' => 'chef' , 'fields' => $user_fields ));
$choices = $argu->get_results();
$field = array();
if( is_array($choices) ) {
$len = count($choices);
for($i = 0; $i < $len; $i++) {
array_push($field, ($choices[$i]->user_login));
}
}
// var_dump($field);
// exit;
return $field;
}
this is the var_dump result
array(5) {
[0]=> string(5) "Ahmed"
[1]=> string(5) "Khedr"
[2]=> string(4) "meme"
[3]=> string(5) "Menna"
[4]=> string(7) "mustafa" }
this is the array result that i want to load in acf field
i found it
this is the new code
thanks justkidding96
add_filter('acf/load_field/name=chef', 'my_acf_load_chef_field');
function my_acf_load_chef_field( $field )
{
$user_fields = array( 'user_login');
$argu = new WP_User_Query( array( 'role' => 'chef' , 'fields' => $user_fields ));
$choices = $argu->get_results();
//$choices = get_field($field['choices'], $post->ID , false);
$field['choices'] = array();
if( is_array($choices) ) {
$len = count($choices);
for($i = 0; $i < $len; $i++) {
array_push($field['choices'], ($choices[$i]->user_login));
}
}
// var_dump($field['choices']);
// exit;
return $field;
Your don’t assign your choices to the field. Try this code:
if (is_array($choices)) {
// Clear the choices
$field[‘choices’] = [];
// Assign the data to the field
foreach ($choices as $choice) {
$field[‘choices’][$choice->user_login] = $choice->user_login;
}
}

How can I filter posts when the meta_value is a serialize object?

I'm doing a dropdown in my post custom type just to filter the content when is completed or not.
my meta_value is a serialize object like "a:3:{s:5:"email";s:21:"mrsxcvsfesr#gmail.com";s:9:"store";s:6:"testes";s:5:"token";s:34:"$P$B7efpLZUWWyB4QkhG0YaYyIwXRAj.3.";}"
and my job is to check if the token is null or not
CustomPostTypeController.php
add_action('restrict_manage_posts',[ $this, 'dropdown_status_filter']);
add_filter( 'parse_query', [ $this, 'filter_request_query'])
public function dropdown_status_filter($post_type){
if('ctp_dasboard' !== $post_type) {
return; //filter your post
}
$selected = '';
$request_attr = 'status_filter';
if ( isset($_REQUEST[$request_attr]) ) {
$selected = $_REQUEST[$request_attr];
}
echo '<select id="status_filter-loc" name="status_filter">';
echo ($selected === '1') ? "'<option value='1' selected>Done</option>'" : "'<option value='1'>Done</option>'";
echo ($selected === '2') ? "'<option value='2' selected>Pending</option>'" : "'<option value='2'>Pending</option>'";
echo '</select>';
}
public function filter_request_query($query){
//modify the query only if it admin and main query.
if( !(is_admin() AND $query->is_main_query()) ){
return $query;
}
//we want to modify the query for the targeted custom post and filter option
if( !('ctp_dasboard' === $query->query['post_type'] AND isset($_REQUEST['status_filter']) ) ){
return $query;
}
//for the default value of our filter no modification is required
if(0 == $_REQUEST['status_filter']){
return $query;
}
//modify the query_vars.
// $value = "";
// var_dump($_REQUEST['status_filter'] === '1');
if ( $_REQUEST['status_filter'] === '1'){
// global $wpdb;
// $meta_key = 'form_ctp';
// $meta_value = '"token";N;';
// $mid = $wpdb->get_results( $wpdb->prepare("SELECT * FROM $wpdb->postmeta WHERE meta_key = %s AND meta_value LIKE %s ", $meta_key, $meta_value) );
// dd($mid);
// // The Query
$args = [
'post_type' => 'ctp_dasboard',
['meta_query' => [
'key' => 'form_ctp',
'value' => 'token";N;', // this is when token is null
'compare' => 'IN'
]]
];
// dd($args);
$query = new \WP_Query( $args );
// dd($the_query);
}
if ( $_REQUEST['status_filter'] === '2'){
}
return $query;
}
There is a special function maybe_unserialize which can return you unserialized data array/ string and etc. Check documentation. Your variable should look like this:
$str = "a:3{s:5:"email";s:21:"mrsxcvsfesr#gmail.com";s:9:"store";s:6:"testes";s:5:"token";s:34:"$P$B7efpLZUWWyB4QkhG0YaYyIwXRAj.3.";}";
$data = maybe_unserialize($str); // will return an array

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.

drupal table with the edit link

I have a table in drupal which displays all the content from a table. I have added an edit link to each record . This link should take the user to the input form which has the values populated in it corresponding to the record. RIght now it is just populating the form with the last row.
For a row x, i need the form populated with the values for record x.
The table is created as
function _MYMODULE_sql_to_table($sql) {
$html = "";
// execute sql
$resource = db_query($sql);
// fetch database results in an array
$results = array();
while ($row = db_fetch_array($resource)) {
$results[] = $row;
$email = $row['p1'];
$comment = $row['p2'];
}
// ensure results exist
if (!count($results)) {
$html .= "Sorry, no results could be found.";
return $html;
}
// create an array to contain all table rows
$rows = array();
// get a list of column headers
$columnNames = array_keys($results[0]);
// loop through results and create table rows
foreach ($results as $key => $data) {
// create row data
$row = array(
'edit' => l(t('Edit'),"admin/content/test/$p1/$p2/Table1", $options=array()),);
// loop through column names
foreach ($columnNames as $c) {
$row[] = array(
'data' => $data[$c],
'class' => strtolower(str_replace(' ', '-', $c)),
);
}
// add row to rows array
$rows[] = $row;
}
// loop through column names and create headers
$header = array();
foreach ($columnNames as $c) {
$header[] = array(
'data' => $c,
'class' => strtolower(str_replace(' ', '-', $c)),
);
}
// generate table html
$html .= theme('table', $header, $rows);
return $html;
}
// then you can call it in your code...
function _MYMODULE_some_page_callback() {
$html = "";
$sql = "select * from {contactus}";
$html .= _MYMODULE_sql_to_table($sql);
return $html;
}
function display(){
$results = array();
$html = "";
$resource = db_query("select * from contactus");
$output = '';
while($row = db_fetch_array($resource)){
$results[] = $row;
}
if(!count($results)){
$html.= "Unable to display table";
return $html;
}
$rows = array();
$columnNames = array_keys($results[0]);
foreach($results as $key=>$data){
$row = array();
foreach($columnNames as $c){
$row = array(
'data' => $data[$c],
'class' => strtolower(str_replace(' ', '-', $c)),
);
}
$rows[] = $row;
}
$header = array();
foreach($columnNames as $c){
$header[] = array(
'data' => $c,
'class' => strtolower(str_replace(' ', '-', $c)),
);
}
$html .= theme('table', $header, $rows);
return $html;
}
You'll want to have $rows = array(); appear before your while loop. What you're doing is essentially destroying the array and redeclaring it as an empty array on each pass. This is why only the last row is appearing for you.

Resources