Shortcode to get a field value in an entry from another form, using a User ID

By: George Plumley | Asked: 06/10/2022
ForumsCategory: Code SnippetsShortcode to get a field value in an entry from another form, using a User ID
George Plumley asked 2 years ago
Wasn't finding a way of getting a value from a user's entry in another form, so I've tried my hand at writing a shortcode. It's working, but I'm looking for feedback, improvements (I've got it handling Dynamic Fields, which are used a lot in the project this was written for, but there are probably other field types that could do with special handling?), code clean up, etc. // Find a field value in another form's entries, based on the user ID // usage example: [frm-field-value-from-another-form form_id=5 field_id=465 prefix="Pt 3 Status:" user_id=[411 show="ID"]] add_shortcode( 'frm-field-value-from-another-form', 'frm_find_field_value_from_another_form_using_user_id' ); function frm_find_field_value_from_another_form_using_user_id( $atts ) { $atts = shortcode_atts( array( 'user_id' => '', 'form_id' => '', 'field_id' => '', 'prefix' => '', ), $atts, 'frm-field-value-from-another-form' ); $thisFieldValue = ''; $prefixText = ''; $userID = $atts['user_id']; $formID = $atts['form_id']; $fieldID = $atts['field_id']; if ( $atts['prefix'] != '' ) { $prefixText = $atts['prefix'] . ' '; } if ( $userID != '' ) { global $wpdb; $entryID = $wpdb->get_col( "SELECT id FROM {$wpdb->prefix}frm_items WHERE form_id = '{$formID}' AND user_id = '{$userID}'" ); // If there's no Entry ID (Community has no Actions) then don't do anything more if ( count($entryID) > 0 ) { $fieldType = $wpdb->get_col( "SELECT type FROM {$wpdb->prefix}frm_fields WHERE id = '{$fieldID}'" ); $fieldType = $fieldType[0]; $entryID = $entryID[0]; $entryValue = $wpdb->get_col( "SELECT meta_value FROM {$wpdb->prefix}frm_item_metas WHERE field_id = '{$fieldID}' AND item_id = '{$entryID}'" ); if ( count($entryValue) > 0 ) { $thisEntryValue = $entryValue[0]; // For dynamic fields that store a number and get their display text from anther form if ( $fieldType == 'data' ) { $thisEntryValue = $wpdb->get_col( "SELECT meta_value FROM {$wpdb->prefix}frm_item_metas WHERE item_id = '{$thisEntryValue}'" ); $thisEntryValue = $thisEntryValue[0]; } $thisFieldValue = $prefixText . $thisEntryValue; } } } return $thisFieldValue; // Value of the field }
1 Answers
Victor Font answered 2 years ago
The only thing I might have done differently is to use $wpdb->get_var() instead of $wpdb->get_col(). It would save a few execution steps because get_var() returns a single value instead of an array.
George Plumley replied 2 years ago

Thanks so much, Victor!

Making the Best WordPress Plugin even better - Together

Take on bigger projects with confidence knowing you have access to an entire community of Formidable Experts and Professionals who have your back when the going gets tough. You got this!
Join the community
crossarrow-right