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;
}
}
Related
I want to count and show WordPress posts in admin panel.I don't want to show it on the website but I want to be able to sort posts in admin panel according to their hits.
I used this link to do so. Every thing is good but it only doesn't sort the posts. In the source website it has told to put some code in template.js. But I don't know where is this file.
functions.php
/*
Function: getPostViews (custom)
Gets the Post Views count
Returns:
$count.' Views'
*/
function getPostViews($postID){
$count_key = 'post_views_count';
$count = get_post_meta($postID, $count_key, true);
if($count==''){
delete_post_meta($postID, $count_key);
add_post_meta($postID, $count_key, '0');
return "0 View";
}
return $count.' Views';
}
/*
Function: setPostViews (custom)
Sets the Post Views count
*/
function setPostViews($postID) {
$count_key = 'post_views_count';
$count = get_post_meta($postID, $count_key, true);
if($count==''){
$count = 0;
delete_post_meta($postID, $count_key);
add_post_meta($postID, $count_key, '0');
}else{
$count++;
update_post_meta($postID, $count_key, $count);
}
}
template.js
// get querystring as an array split on "&"
var querystring = location.search.replace( '?', '' ).split( '&' );
// declare object
var queryObj = {};
// loop through each name-value pair and populate object
for ( var i=0; i<querystring.length; i++ ) {
// get name and value
var name = querystring[i].split('=')[0];
var value = querystring[i].split('=')[1];
// populate object
queryObj[name] = value;
}
// Check query string for sort filter method
if(queryObj[ "filter" ] === "popular"){
$('#newest').removeClass('active');
$('#popular').addClass('active');
} else if(queryObj[ "filter" ] === "newest"){
$('#popular').removeClass('active');
$('#newest').addClass('active');
}
Wordpress Post Sorting
<?
// Place this code into your archive.php template file
$filter = $_GET['filter'];
// Preserve existing query parameters
global $wp_query;
// Check query string parameter "filter" (options: 'popular' and 'newest')
if((isset($filter)) && $filter == 'popular'){
$args = array_merge( $wp_query->query, array('order' => 'desc', 'orderby' => 'meta_value_num', 'meta_key' => 'post_views_count') );
query_posts( $args );
}else if((isset($filter)) && $filter == 'newest'){
$args = array_merge( $wp_query->query, array('order' => 'desc') );
query_posts( $args );
}
?>
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
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
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');
}
}
}
}
}
}
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.