Would like to bulk populate a custom field via CSV import - php

I have a custom plugin and it includes an import/export section. I have added a new ACF field called serial_number_issued. I would like to bulk populate this using a CSV import file. However, I'm not too sure what I need to add to the code to get this working. I've added serial_number_issued to the list array but what do I need to add to update the page:
list( $system_name, $system_id, $status, $serial_number, $serial_number_issued ) = $data;
$status = ( $status == '-' ) ? 'Generated' : $status;
$status = ( ( $status == 'Generated' ) && ( $system_id != '-' ) ) ? 'Allocated' : $status;
// If serial exists, update. If not, insert new
$post = get_page_by_title( trim( $serial_number ), ARRAY_A, $sha_wreg_module_slug );
if ( isset( $post['post_type'] ) && ( $post['post_type'] == $sha_wreg_module_slug ) ) {
$serial_id = $post['ID'];
// Update system info
if ( ( $system_name != '-' ) && ( $system_id != '-' ) ) {
$system = get_post( $system_id );
update_post_meta( $serial_id, $sha_wreg_prefix . 'system', array( 'id' => $system->ID, 'name' => $system->post_title ) );
}
// Update status
update_post_meta( $serial_id, $sha_wreg_prefix . 'status', $status );
This is the page with the Serial Number Issued column that I want to update with the CSV file import
So we want to be able to bulk update the field with the answer Yes.
Here is the full code for the import.
switch ( $action ) {
// Import cards from CSV
case 'import':
if ( isset( $_FILES[ $sha_wreg_prefix . 'import_csv' ] ) && ( $_FILES[ $sha_wreg_prefix . 'import_csv' ]['error'] == 0 ) ) {
$row = 1;
if ( ( $handle = fopen( $_FILES[ $sha_wreg_prefix . 'import_csv' ]['tmp_name'], "r" ) ) !== FALSE ) {
while ( ( $data = fgetcsv( $handle, 1000, "," ) ) !== FALSE ) {
$row++;
if ( $row > 2 ) {
list( $system_name, $system_id, $status, $serial_number, $serial_number_issued ) = $data;
$status = ( $status == '-' ) ? 'Generated' : $status;
$status = ( ( $status == 'Generated' ) && ( $system_id != '-' ) ) ? 'Allocated' : $status;
// If serial exists, update. If not, insert new
$post = get_page_by_title( trim( $serial_number ), ARRAY_A, $sha_wreg_module_slug );
if ( isset( $post['post_type'] ) && ( $post['post_type'] == $sha_wreg_module_slug ) ) {
$serial_id = $post['ID'];
// Update system info
if ( ( $system_name != '-' ) && ( $system_id != '-' ) ) {
$system = get_post( $system_id );
update_post_meta( $serial_id, $sha_wreg_prefix . 'system', array( 'id' => $system->ID, 'name' => $system->post_title ) );
}
// Update status
update_post_meta( $serial_id, $sha_wreg_prefix . 'status', $status );
wp_update_post( $serial_id . 'serial_number_issued', $serial_number_issued );
} else {
$data = array(
'post_title' => $serial_number,
'post_type' => $sha_wreg_module_slug,
'post_status' => 'publish'
);
$serial_id = wp_insert_post( $data );
// Update system info
if ( ( $system_name != '-' ) && ( $system_id != '-' ) ) {
update_post_meta( $serial_id, $sha_wreg_prefix . 'system', array( 'id' => $system_id, 'name' => $system_name ) );
}
// Update status
update_post_meta( $serial_id, $sha_wreg_prefix . 'status', $status );
}
}
}
fclose($handle);
}
$_SESSION['sha-wreg'] = array(
'class' => 'notice-success',
'message' => 'Serials successfully imported'
);
}
break;

Related

Having a second orderby sorting criteria after default sorting criteria (WP Profile Builder)

I'm using the WP Profile Builder plugin. In the frontend user listing I set a default sorting criteria. Works fine! But now I would like to have a second criteria that comes right after the default one.
Lets say first are the "gold" users and behind them the "silver" users.
Right now it looks like this:
*/
function wppb_userlisting_users_loop( $value, $name, $children, $extra_values ){
if( $name == 'users' ){
global $userlisting_args;
global $wpdb;
$userlisting_form_id = $extra_values['userlisting_form_id'];
$userlisting_args = get_post_meta( $userlisting_form_id, 'wppb_ul_page_settings', true );
if( !empty( $userlisting_args[0] ) ){
$paged = (get_query_var('wppb_page')) ? get_query_var('wppb_page') : 1;
if( !is_int( (int)$userlisting_args[0]['number-of-userspage'] ) || (int)$userlisting_args[0]['number-of-userspage'] == 0 )
$userlisting_args[0]['number-of-userspage'] = 5;
// Check if some of the listing parameters have changed
if ( isset( $_REQUEST['setSortingOrder'] ) && sanitize_text_field( $_REQUEST['setSortingOrder'] ) !== '' )
$sorting_order = sanitize_text_field( $_REQUEST['setSortingOrder'] );
else
$sorting_order = $userlisting_args[0]['default-sorting-order'];
/* if we have admin approval on we don't want to show those users in the userlisting so we need to exclude them */
if( wppb_get_admin_approval_option_value() === 'yes' ){
$excluded_ids = array();
$user_statusTaxID = get_term_by( 'name', 'unapproved', 'user_status' );
if( $user_statusTaxID != false ){
$term_taxonomy_id = $user_statusTaxID->term_taxonomy_id;
$results = $wpdb->get_results( $wpdb->prepare( "SELECT wppb_t1.ID FROM $wpdb->users AS wppb_t1 LEFT OUTER JOIN $wpdb->term_relationships AS wppb_t0 ON wppb_t1.ID = wppb_t0.object_id WHERE wppb_t0.term_taxonomy_id = %d", $term_taxonomy_id ) );
foreach ( $results as $result )
array_push( $excluded_ids, $result->ID );
$excluded_ids = implode( ',', $excluded_ids );
}
}
if( !empty($excluded_ids) )
$extra_values['exclude'] .= ','. $excluded_ids;
//set query args
$args = array(
'order' => $sorting_order,
'include' => $extra_values['include'],
'exclude' => $extra_values['exclude'],
'fields' => array( 'ID' )
);
/* get all field options here, we will need it bellow */
global $wppb_manage_fields;
if( !isset( $wppb_manage_fields ) )
$wppb_manage_fields = get_option( 'wppb_manage_fields', 'not_found' );
// Check if some of the listing parameters have changed
if ( isset( $_REQUEST['setSortingCriteria'] ) && sanitize_text_field( $_REQUEST['setSortingCriteria'] ) !== '' )
$sorting_criteria = sanitize_text_field( $_REQUEST['setSortingCriteria'] );
else
$sorting_criteria = $userlisting_args[0]['default-sorting-criteria'];
if( in_array( $sorting_criteria, array( 'login', 'email', 'url', 'registered', 'post_count', 'nicename' ) ) ){
if( $sorting_criteria == 'nicename' )
$args['orderby'] = 'display_name';
}
else{
$args['orderby'] = apply_filters( 'wppb_ul_sorting_type', 'meta_value', $sorting_criteria );
if ($wppb_manage_fields != 'not_found') {
foreach ($wppb_manage_fields as $wppb_field) {
if( $wppb_field['meta-name'] == $sorting_criteria ){
if( $wppb_field['field'] == 'Number' || $wppb_field['field'] == 'Phone' ){
$args['orderby'] = apply_filters( 'wppb_ul_sorting_type', 'meta_value_num', $sorting_criteria );
}
}
}
}
switch( $sorting_criteria ){
case "bio":
$args['meta_key'] = 'description';
break;
case "firstname":
$args['meta_key'] = 'first_name';
break;
case "lastname":
$args['meta_key'] = 'last_name';
break;
case "nickname":
$args['meta_key'] = 'nickname';
break;
case "role":
$args['meta_key'] = $wpdb->get_blog_prefix().'capabilities';
break;
case "RAND()":
break;
default:
$args['meta_key'] = $sorting_criteria;
}
}
/* the relationship between meta query is AND because we need to narrow the result */
$args['meta_query'] = array('relation' => 'AND');
/* we check if we have a meta_value and meta_key in the shortcode and add a meta query */
if( !empty( $extra_values['meta_value'] ) && !empty( $extra_values['meta_key'] ) ){
$args['meta_query'][0] = array( 'relation' => 'AND' ); //insert relation here
$args['meta_query'][0][] = array(
'key' => $extra_values['meta_key'],
'value' => $extra_values['meta_value'],
'compare' => apply_filters( 'wppb_ul_meta_att_in_shortcode_compare', '=', $extra_values )
);
}
Can someone help me out with that? Best regards, Ingo
I already tried to change some parameters and checked what was changing but no luck for me!

Profile photo upload locked at 600px. Ultimate Member Registration Form

This is the plugin that generates a profile photo upload button:
https://github.com/ultimatemember/Extended/blob/main/um-profile-photo/um-profile-photo.php
if ( ! defined( 'ABSPATH' ) ) exit;
/**
* Add new predefined field "Profile Photo" in UM Form Builder.
*
* #param array $arr field array settings.
*/
function um_predefined_fields_hook_profile_photo( $arr ) {
$arr['register_profile_photo'] = array(
'title' => __( 'Profile Photo', 'ultimate-member' ),
'metakey' => 'register_profile_photo',
'type' => 'image',
'label' => __('Change your profile photo','ultimate-member' ),
'upload_text' => __( 'Upload your photo here', 'ultimate-member' ),
'icon' => 'um-faicon-camera',
'crop' => 1,
'editable' => 1,
'max_size' => ( UM()->options()->get('profile_photo_max_size') ) ? UM()->options()->get('profile_photo_max_size') : 999999999,
'min_width' => str_replace('px','',UM()->options()->get('profile_photosize')),
'min_height' => str_replace('px','',UM()->options()->get('profile_photosize')),
);
return $arr;
}
add_filter( 'um_predefined_fields_hook', 'um_predefined_fields_hook_profile_photo', 99999, 1 );
/**
* Multiply Profile Photo with different sizes
*
* #param integer $user_id the user ID.
*/
function um_registration_set_profile_photo( $user_id, $args ) {
if( isset( $args['form_id'] )) $req = 'register_profile_photo-' . $args['form_id'];
else $req = 'register_profile_photo';
if( ! isset( $_REQUEST[$req] ) ) return;
//if ( strpos( $_REQUEST['register_profile_photo'], '_temp.') <= -1 ) {
//return;
//}
if( is_user_logged_in() ) {
UM()->files()->delete_core_user_photo( $user_id, 'profile_photo' );
}
$user_basedir = UM()->uploader()->get_upload_user_base_dir( $user_id, true );
$temp_dir = UM()->uploader()->get_core_temp_dir() . DIRECTORY_SEPARATOR;
$temp_profile_photo = array_slice( scandir( $temp_dir ), 2);
$temp_profile_id = isset( $_COOKIE['um-register-profile-photo'] ) ? $_COOKIE['um-register-profile-photo'] : null;
if( empty( $temp_profile_photo ) ) return;
foreach( $temp_profile_photo as $i => $p ){
if ( strpos($p, "_photo_{$temp_profile_id}_temp") !== false ) {
$profile_p = $p;
}
}
if( empty( $profile_p ) ) return;
$temp_image_path = $temp_dir . DIRECTORY_SEPARATOR . $profile_p;
$new_image_path = $user_basedir . DIRECTORY_SEPARATOR . $profile_p;
$image = wp_get_image_editor( $temp_image_path );
$file_info = wp_check_filetype_and_ext( $temp_image_path, $profile_p );
$ext = $file_info['ext'];
$new_image_name = str_replace( $profile_p, "profile_photo.{$ext}", $new_image_path );
$sizes = UM()->options()->get( 'photo_thumb_sizes' );
$quality = UM()->options()->get( 'image_compression' );
if ( ! is_wp_error( $image ) ) {
$image->save( $new_image_name );
$image->set_quality( $quality );
$sizes_array = array();
foreach( $sizes as $size ) {
$sizes_array[ ] = array ( 'width' => $size );
}
$image->multi_resize( $sizes_array );
delete_user_meta( $user_id, 'synced_profile_photo' );
update_user_meta( $user_id, 'profile_photo', "profile_photo.{$ext}" );
update_user_meta( $user_id, 'register_profile_photo', "profile_photo.{$ext}" );
#unlink( $temp_image_path );
}
}
add_action( 'um_after_user_account_updated', 'um_registration_set_profile_photo', 1, 2 );
add_action( 'um_registration_set_extra_data', 'um_registration_set_profile_photo', 1, 2 );
/**
* Set Temporary user id
*/
function um_register_profile_photo_set_temp_user_id() {
$temp_profile_id = isset( $_COOKIE['um-register-profile-photo'] ) ? $_COOKIE['um-register-profile-photo'] : null;
if ( ! $temp_profile_id ) {
setcookie( 'um-register-profile-photo', md5( time() ), time() + 3600, COOKIEPATH, COOKIE_DOMAIN );
}
}
add_action( 'template_redirect', 'um_register_profile_photo_set_temp_user_id' );
/**
* Set handler callback for filename
*/
function um_register_profile_photo_upload_handler( $override_handler ) {
if ( 'stream_photo' == UM()->uploader()->upload_image_type && 'register_profile_photo' == UM()->uploader()->field_key ) {
$override_handler['unique_filename_callback'] = 'um_register_profile_photo_name';
}
return $override_handler;
}
add_filter( 'um_image_upload_handler_overrides__register_profile_photo', 'um_register_profile_photo_upload_handler', 99999 );
/**
* Change filename
*/
function um_register_profile_photo_name( $dir, $filename, $ext ) {
$temp_profile_id = isset( $_COOKIE['um-register-profile-photo'] ) ? $_COOKIE['um-register-profile-photo'] : null;
return "profile_photo_{$temp_profile_id}_temp{$ext}";
}
/**
* Support profile photo uploader in Account form
*/
function um_register_display_profile_photo_in_account( $field_atts, $key, $data ) {
if ( 'register_profile_photo' == $key && um_is_core_page( 'account' ) ) {
$profile_photo = UM()->uploader()->get_upload_base_url() . um_user( 'ID' ) . DIRECTORY_SEPARATOR . um_profile( 'profile_photo' ) . '?ts=' . current_time( 'timestamp' );
$field_atts['data-profile_photo'] = array( $profile_photo );
}
return $field_atts;
}
add_filter( 'um_field_extra_atts', 'um_register_display_profile_photo_in_account', 10, 3 );
/**
* Clear profile photo cache
*/
function um_register_display_profile_photo_script() {
if( ! um_is_core_page( 'account' ) ) return;
?>
<script type="text/javascript">
jQuery(document).on("ready", function(){
setTimeout(() => {
var register_profile_photo = jQuery("div[data-key='register_profile_photo']");
register_profile_photo.find(".um-field-area").find(".um-single-image-preview").find("img").attr("src", register_profile_photo.data("profile_photo"));
}, 1000);
var account_small_avatar = jQuery(".um-account-meta-img-b").find("a").find("img");
account_small_avatar.attr("src", account_small_avatar.attr("src") + "?ts=" + Math.floor(Date.now() / 1000) );
jQuery(document).ajaxSuccess(function(event, xhr, settings) {
if( typeof settings.data.indexOf !== "undefined" ){
if (settings.data.indexOf("action=um_resize_image") > -1) {
jQuery(".um-account .um-form form").submit();
}
}
});
});
</script>
<?php
}
add_action( 'wp_footer', 'um_register_display_profile_photo_script' );
/**
* Delete profile photo viam the account form
*/
function um_register_delete_profile_photo_from_account() {
if( isset( $_REQUEST['mode'] ) && "account" == $_REQUEST['mode'] ) {
UM()->files()->delete_core_user_photo( get_current_user_id(), 'profile_photo' );
}
wp_send_json_success();
}
add_action( 'wp_ajax_um_remove_file', 'um_register_delete_profile_photo_from_account', 1 );
When uploading the profile photo from the registration form with the 1:1 crop, it does not allow uploading a photo smaller than 600px, since it is not linked to the ultimate member settings.
This lock at 600px is located at line 1799 in the path ultimatemember/includes/core/class-fields.php
https://github.com/ultimatemember/ultimatemember/blob/master/includes/core/class-fields.php
if ( $array['min_width'] == '' && $array['crop'] == 1 ) {
$array['min_width'] = 600;
}
if ( $array['min_height'] == '' && $array['crop'] == 1 ) {
$array['min_height'] = 600;
}
if ( $array['min_width'] == '' && $array['crop'] == 3 ) {
$array['min_width'] = 600;
}
if ( $array['min_height'] == '' && $array['crop'] == 3 ) {
$array['min_height'] = 600;
Let's see if you can help me in the first code to unlock that 600px value and if you can, link it with the Ultimate Member profile photo settings.
Thank you very much for everything and greetings to the community.

How do I show custom field in Sensei LMS Certificates plugin PDF

I am using "Sensei LMS" and "Sensei LMS Certificates" plugins.
Now , to enhance "Sensei LMS Certificates" plugin functionality , I have created a custom meta box and custom fields like this : https://prnt.sc/104s7oy
I am using this action hook sensei_certificates_before_pdf_output to show text in PDF
I have added the following code in my custom plugin :
<?php
add_action( 'sensei_certificates_before_pdf_output', 'action__sensei_certificates_before_pdf_output' , 20, 2 );
function action__sensei_certificates_before_pdf_output( $pdf_certificate, $fpdf ) {
global $woothemes_sensei_certificates;
$show_border = apply_filters( 'woothemes_sensei_certificates_show_border', 0 );
$start_position = 200;
$args = array(
'post_type' => 'certificate',
'meta_key' => 'certificate_hash',
'meta_value' => $pdf_certificate->hash,
);
$query = new WP_Query( $args );
$certificate_id = 0;
if ( $query->have_posts() ) {
$query->the_post();
$certificate_id = $query->posts[0]->ID;
}
wp_reset_query();
if ( 0 < intval( $certificate_id ) ) {
$user_id = get_post_meta( $certificate_id, 'learner_id', true );
$student = get_userdata( $user_id );
$student_name = $student->display_name;
$fname = $student->first_name;
$lname = $student->last_name;
if ( '' != $fname && '' != $lname ) {
$student_name = $fname . ' ' . $lname;
}
$course_id = get_post_meta( $certificate_id, 'course_id', true );
$course_title = get_post_field('post_title', $course_id);
$course_end = Sensei_Utils::sensei_check_for_activity(
array(
'post_id' => intval( $course_id ),
'user_id' => intval( $user_id ),
'type' => 'sensei_course_status',
),
true
);
$course_end_date = $course_end->comment_date;
$date = Woothemes_Sensei_Certificates_Utils::get_certificate_formatted_date( $course_end_date );
if ( isset( $woothemes_sensei_certificates->certificate_template_fields['certificate_custom_message']['text'] ) && '' != $woothemes_sensei_certificates->certificate_template_fields['certificate_custom_message']['text'] ) {
$certificate_custom_message = $woothemes_sensei_certificates->certificate_template_fields['certificate_custom_message']['text'];
$certificate_custom_message .= str_replace( array( '{{learner}}', '{{course_title}}', '{{completion_date}}', '{{course_place}}' ), array( $student_name, $course_title, $date, get_bloginfo( 'name' ) ), $certificate_custom_message );
}
$output_fields = array(
'certificate_custom_message' => 'textarea_field',
);
foreach ( $output_fields as $meta_key => $function_name ) {
if ( isset( $woothemes_sensei_certificates->certificate_template_fields[ $meta_key ]['position']['x1'] ) ) {
$font_settings = $woothemes_sensei_certificates->get_certificate_font_settings( $meta_key );
call_user_func_array( array( $pdf_certificate, $function_name ), array( $fpdf, $meta_key, $show_border, array( $woothemes_sensei_certificates->certificate_template_fields[ $meta_key ]['position']['x1'], $woothemes_sensei_certificates->certificate_template_fields[ $meta_key ]['position']['y1'], $woothemes_sensei_certificates->certificate_template_fields[ $meta_key ]['position']['width'], $woothemes_sensei_certificates->certificate_template_fields[ $meta_key ]['position']['height'] ), $font_settings ) );
}
}
} else {
wp_die( esc_html__( 'The certificate you are searching for does not exist.', '' ), esc_html__( 'Certificate Error', '' ) );
}
}
but this is how text showing inside PDF : https://prnt.sc/104sg3v
expected result is "Hello Test hii" instead of "certificate_custom_message"
How do I fix this ?

Override WordPress plugin class to change upload image size

I'm trying to change the function inside the handler class for uploading user image from front end using the the code which mostly works in situations like this one:
class Custom_Class extends Main_Class {
function __construct() {
remove_action('default_action', array($this));
add_action('new_action', array($this));
}
/* custom code from here on */
}
new Custom_Class
The goal is to change the $image->resize value to 320px, but I can not even remove the action, and the original code looks like this:
class UR_Form_Handler {
/**
* Hook in methods.
*/
public static function init() {
add_action( 'template_redirect', array( __CLASS__, 'redirect_reset_password_link' ) );
add_action( 'template_redirect', array( __CLASS__, 'save_profile_details' ) );
add_action( 'template_redirect', array( __CLASS__, 'save_change_password' ) );
add_action( 'wp_loaded', array( __CLASS__, 'process_login' ), 20 );
add_action( 'wp_loaded', array( __CLASS__, 'process_lost_password' ), 20 );
add_action( 'wp_loaded', array( __CLASS__, 'process_reset_password' ), 20 );
add_action( 'user_registration_before_customer_login_form', array( __CLASS__, 'export_confirmation_request' ) );
}
/**
* Save/update a profile fields if the form was submitted through the user account page.
*
* #return mixed
*/
public function save_profile_details() {
if ( 'POST' !== strtoupper( $_SERVER['REQUEST_METHOD'] ) ) {
return;
}
if ( empty( $_POST['action'] ) || 'save_profile_details' !== $_POST['action'] || empty( $_POST['_wpnonce'] ) || ! wp_verify_nonce( $_POST['_wpnonce'], 'save_profile_details' ) ) {
return;
}
$user_id = get_current_user_id();
if ( $user_id <= 0 ) {
return;
}
if ( has_action( 'uraf_profile_picture_buttons' ) ) {
if ( isset( $_POST['profile_pic_url'] ) && ! empty( $_POST['profile_pic_url'] ) ) {
update_user_meta( $user_id, 'user_registration_profile_pic_url', $_POST['profile_pic_url'] );
}
} else {
if ( isset( $_FILES['profile-pic'] ) && $_FILES['profile-pic']['size'] ) {
if ( ! function_exists( 'wp_handle_upload' ) ) {
require_once ABSPATH . 'wp-admin/includes/file.php';
}
$upload = $_FILES['profile-pic'];
$upload_overrides = array(
'action' => 'save_profile_details',
);
$uploaded = wp_handle_upload( $upload, $upload_overrides );
if ( $uploaded && ! isset( $uploaded['error'] ) ) {
$image = wp_get_image_editor( $uploaded['file'] );
if ( ! is_wp_error( $image ) ) {
$image->resize( 150, 150, true );
$image->save( $uploaded['file'] );
}
update_user_meta( $user_id, 'user_registration_profile_pic_url', $uploaded['url'] );
} else {
ur_add_notice( $uploaded['error'], 'error' );
}
} elseif ( UPLOAD_ERR_NO_FILE !== $_FILES['profile-pic']['error'] ) {
switch ( $_FILES['profile-pic']['error'] ) {
case UPLOAD_ERR_INI_SIZE:
ur_add_notice( __( 'File size exceed, please check your file size.', 'user-registration' ), 'error' );
break;
default:
ur_add_notice( __( 'Something went wrong while uploading, please contact your site administrator.', 'user-registration' ), 'error' );
break;
}
} elseif ( empty( $_POST['profile-pic-url'] ) ) {
$upload_dir = wp_upload_dir();
$profile_url = get_user_meta( $user_id, 'user_registration_profile_pic_url', true );
// Check if profile already set?
if ( $profile_url ) {
// Then delete file and user meta.
$profile_url = $upload_dir['basedir'] . explode( '/uploads', $profile_url )[1];
if ( ! empty( $profile_url ) && file_exists( $profile_url ) ) {
#unlink( $profile_url );
}
delete_user_meta( $user_id, 'user_registration_profile_pic_url' );
}
}
}
$form_id_array = get_user_meta( $user_id, 'ur_form_id' );
$form_id = 0;
if ( isset( $form_id_array[0] ) ) {
$form_id = $form_id_array[0];
}
$profile = user_registration_form_data( $user_id, $form_id );
foreach ( $profile as $key => $field ) {
if ( ! isset( $field['type'] ) ) {
$field['type'] = 'text';
}
// Get Value.
switch ( $field['type'] ) {
case 'checkbox':
if ( isset( $_POST[ $key ] ) && is_array( $_POST[ $key ] ) ) {
$_POST[ $key ] = $_POST[ $key ];
} else {
$_POST[ $key ] = (int) isset( $_POST[ $key ] );
}
break;
default:
$_POST[ $key ] = isset( $_POST[ $key ] ) ? ur_clean( $_POST[ $key ] ) : '';
break;
}
// Hook to allow modification of value.
$_POST[ $key ] = apply_filters( 'user_registration_process_myaccount_field_' . $key, $_POST[ $key ] );
$disabled = false;
if ( isset( $field['custom_attributes'] ) && isset( $field['custom_attributes']['readonly'] ) && isset( $field['custom_attributes']['disabled'] ) ) {
if ( 'readonly' === $field['custom_attributes']['readonly'] || 'disabled' === $field['custom_attributes']['disabled'] ) {
$disabled = true;
}
}
if ( ! empty( $_POST[ $key ] ) ) {
// Validation rules.
if ( ! empty( $field['validate'] ) && is_array( $field['validate'] ) ) {
foreach ( $field['validate'] as $rule ) {
switch ( $rule ) {
case 'email':
$_POST[ $key ] = strtolower( $_POST[ $key ] );
if ( ! is_email( $_POST[ $key ] ) ) {
ur_add_notice( sprintf( __( '%s is not a valid email address.', 'user-registration' ), '<strong>' . $field['label'] . '</strong>' ), 'error' );
}
break;
}
}
}
}
}// End foreach().
do_action( 'user_registration_after_save_profile_validation', $user_id, $profile );
if ( 0 === ur_notice_count( 'error' ) ) {
$user_data = array();
foreach ( $profile as $key => $field ) {
$new_key = str_replace( 'user_registration_', '', $key );
if ( in_array( $new_key, ur_get_user_table_fields() ) ) {
if ( $new_key === 'display_name' ) {
$user_data['display_name'] = $_POST[ $key ];
} else {
$user_data[ $new_key ] = $_POST[ $key ];
}
} else {
$update_key = $key;
if ( in_array( $new_key, ur_get_registered_user_meta_fields() ) ) {
$update_key = str_replace( 'user_', '', $new_key );
}
$disabled = isset( $field['custom_attributes']['disabled'] ) ? $field['custom_attributes']['disabled'] : '';
if ( $disabled !== 'disabled' ) {
update_user_meta( $user_id, $update_key, $_POST[ $key ] );
}
}
}
if ( count( $user_data ) > 0 ) {
$user_data['ID'] = get_current_user_id();
wp_update_user( $user_data );
}
do_action( 'user_registration_save_profile_details', $user_id, $form_id );
wp_safe_redirect( ur_get_endpoint_url( 'edit-profile', '', ur_get_page_permalink( 'myaccount' ) ) );
exit;
}
}
}
Either I get Fatal error: Cannot make static method UR_Form_Handler::save_profile_details() non static in class Custom_UR_Form_Handler, or the override doesn't work at all, I'm not sure if I'm even doing this the right way, maybe there's no need to override the entire function, but I'm stuck with this, any help or idea would be much appreciated, thanks.

Quotes missing when saving json data inside a database (ajax related)

I noticed that I'm missing the usual quotes when using JSON data inside a database table. This only happens inside the second column Followers IDs
My code is as follows:
public function ajax_follow_me() {
check_ajax_referer( 'km-ajax-create-nonce', 'security' );
$current_user = get_current_user_id();
$target_user = isset( $_POST['data-follow-user'] ) ? $_POST['data-follow-user'] : false;
if( ! empty( $_POST['data-follow-user'] ) ) {
$this->follow_user( $current_user, $target_user );
}
wp_die();
}
Next step...
public function follow_user( $current_user = 0, $user_to_follow = 0 ) {
if ( empty( $user_to_follow ) ) {
return;
}
$args = array(
'user_id' => $current_user,
'follow_to' => $user_to_follow
);
$response = $this->add_following( $args );
if ( ! empty( $response ) && $response !== FALSE ) {
$args = array(
'user_id' => $user_to_follow,
'followed_by' => $current_user
);
$this->add_followed_by( $args );
$this->km_follow_me_success( $user_to_follow );
} else {
$this->km_follow_me_error();
}
}
First column:
public function add_following ( $args = array() ) {
global $wpdb;
$author_info = get_userdata( $args["user_id"] );
if ( empty( $author_info->display_name ) ) {
$author_name = $author_info->user_login;
} else {
$author_name = $author_info->display_name;
}
$defaults = array(
'user_id' => '',
'follow_to' => '',
'username' => $author_name,
'user_email' => $author_info->user_email
);
$args = wp_parse_args( $args, $defaults );
// First you have to check if the user already exists and return his Following Row
$following = array();
$existing = $wpdb->get_var( $wpdb->prepare( "SELECT following FROM {$this->table} WHERE user_id = %d", $args["user_id"] ) );
if( ! empty( $existing ) ) {
$following = json_decode( $existing, true );
}
// We check if this user ($args["user_id"]) is already following the $args["follow_to"] user.
if( in_array( $args["follow_to"], $following ) ) {
return TRUE;
} else{
array_push( $following, $args['follow_to'] );
}
// We verify if the user exists and update the value, if he does not and we sent username, then, we create it.
if( null === $existing && ! empty( $args['username'] ) ) {
$wpdb->insert( $this->table,
array(
'user_id' => $args['user_id'],
'username' => $args['username'],
'email' => $args['user_email'],
'following' => json_encode( $following ),
'followers' => json_encode( array() )
),
array( '%d', '%s', '%s', '%s', '%s' )
);
return $wpdb->insert_id;
} else {
$updated = $wpdb->update( $this->table,
array(
'following' => json_encode( $following )
),
array(
'user_id' => $args["user_id"]
),
'%s', '%d'
);
return $updated;
}
}
This code is for updating the second column (and where it's suppose to go wrong somewhere).
public function add_followed_by( $args = array() ) {
global $wpdb;
$author_info = get_userdata( $args['user_id'] );
if ( empty( $author_info->display_name ) ) {
$author_name = $author_info->user_login;
} else {
$author_name = $author_info->display_name;
}
$defaults = array(
'user_id' => '',
'followed_by' => '',
'username' => $author_name,
'user_email' => $author_info->user_email
);
$args = wp_parse_args( $args, $defaults );
// First you have to check if the user already exists and return his Followers Row
$followers = array();
$existing = $wpdb->get_var( $wpdb->prepare( "SELECT followers FROM {$this->table} WHERE user_id = %d", $args["user_id"] ) );
if( ! empty( $existing ) ) {
$followers = json_decode( $existing, true );
}
// We check if this user ($args["user_id"]) is already followed by $args["followed_by"] user.
if( in_array( $args['followed_by'], $followers ) ) {
return TRUE;
} else {
array_push( $followers, $args['followed_by'] );
}
// We verify if the user exists and update the value, if he does not and we sent username, then, we create it.
if( null === $existing && ! empty( $args['username'] ) ) {
$wpdb->insert( $this->table,
array(
'user_id' => $args['user_id'],
'username' => $args['username'],
'email' => $args['user_email'],
'following' => json_encode( array() ),
'followers' => json_encode( $followers )
),
array( '%d', '%s', '%s', '%s', '%s' )
);
return $wpdb->insert_id;
} else {
$updated = $wpdb->update( $this->table,
array(
'followers' => json_encode( $followers )
),
array(
'user_id' => $args["user_id"]
),
"%s", "%d"
);
return $updated;
}
}
Any help in the right direction is greatly appreciated.

Categories