Saving user meta as single values or an array - wordpress

I'm working on a plugin which is going to save about 10 custom user meta for certain users bound to the plugin. Among these metas we find: Address, zip, occupation, etc...
These metas will only be used by the plugin, and mostly (if not always) all of them will be fetched from the DB together to be shown in a table view in the admin.
So, I'm thinking about the best way to save these values.
I could do this:
add_user_meta( $user_id, 'address', 'kings street 45');
add_user_meta( $user_id, 'zip', '12345');
add_user_meta( $user_id, 'occupation', 'nurse');
... some more meta
Or would it be better to do this:
add_user_meta( $user_id, 'plugin_name_user_meta', array(
'address' => 'kings street 45'
'zip' => '12345'
'occupation' => 'nurse')
... some more meta
);

In WordPress I prefer to work with arrays because in helps keeping my data organized, so I would go the second way. Nevertheless, if you go the first way, prefix all the metas with a unique ID related to your plugin.

I disagree with the first answer and I would use your first suggestion.
Why? Because if you use add_user_meta for each field you have a seperate field in the database for each value. That means:
1) You can do meta and Wildcard Queries e.g. "Select all user with a ZIP starting with 11". This is impossible if you save an array especially as the array will be saved in serialized format.
Keep this possibility open! Some day you may want to do complicated queries on this data even if it is not the case currently.
Have a look at the WP Meta Query class and even better the WP User Query class:
https://codex.wordpress.org/Class_Reference/WP_Meta_Query
https://codex.wordpress.org/Class_Reference/WP_User_Query#Custom_Field_Parameters
2) You do not have a disadvantage in extensibility: As these fields are already saved in a meta table and not within fixed columns you can add and remove values dynamically.
However #Juan is right with the hint on prefixes: You definitly should prefix your meta_values in order to avoid collisions.

Related

joining two custom post types for wp_query

I have two custom post types ("affiliate_codes" & "affiliate_tracker") that share a custom field ("affiliate_code"). In "affiliate_codes" I manage a master list of affiliate accounts (ie Affiliate Code, WP User, Percentage). In "affiliate_tracker", I have a form that adds new posts to the CPT passing fields such as Affiliate Code, Purchase Amt, etc.
I'm trying to create a report that is essentially a query that combines data from both of these CPTs, using the affiliate_code custom field to join the two CPTs together for the query.
A user could have more than one affiliate_code associated, so it would need to use the user ID passed in to grab all affiliate_codes associated to that user ID in 'affiliate_codes' CPT, and then retrieve all posts from 'affiliate_tracker' CPT that includes any of the codes associated to the user.
Is there a way to Join two custom post types as part of one query?
I initially tried to do this by nesting a second query within the main query.
Query 1 - pulling all posts from affiliate_tracker CPT and looping through.
Query 2 (nested inside the loop above) - uses affiliate code field to retrieve User from affiliate_code CPT
This works fine when I want to return all posts in affiliate_tracker. I also need to be able to filter the posts returned to only those associated with a specific user which is where I am struggling. Ideally I could have one query that combines the two CPTs by connecting posts via the shared 'affiliate_code' field and then can pull all posts from affiliate_tracker that have a code that is associated to a specific user. Not sure if this is possible.
Of course m8 , u can do it easily.
$args = array(
'post_type' => [ 'affiliate_codes', 'affiliate_tracker' ],
'post_status' => 'publish',
);
$query = new WP_Query( $args );
Above query gives you the all posts of these post types , now using following link you can filter them based on meta values based on your needs
Wordpress meta query parmeters

How to create a custom meta table in wordpress?

I have custom meta box with multiple fields and it is working fine. Now, I want to store this meta box data into a custom table. So how can I do that ?
I have researched on google and Youtube but didn't got what exactly I am looking for.
If anyone can provide me with Step by Step guide or tutorial links then it will be very much helpful.
I'm not entirely sure why you would want to store Post Meta into a separate table, but I've had situations where I've needed to do crazier things.
The gist would be that you can use your Custom Meta Box to display the form fields, and then handle those form fields with your own custom function on the save_post hook.
Let's say you've registered a custom meta box with <input name="my_custom_table_field" /> in it. Instead of using update_post_meta() on the save_post hooks, you could write a function that manages the data with the $wpdb->update method. Something like this would get you started:
add_action( 'save_post', 'save_my_custom_data' );
function save_my_custom_data( $post_id ){
global $wpdb;
if( isset( $_POST['my_custom_table_field'] ){
$result = $wpdb->update(
'my_custom_table',
array(
'post_id' => $post_id,
'my_custom_table_field' => $_POST['my_custom_table_field'],
),
array(
'post_id' => $post_id
),
array(
'%d',
'%s'
),
array (
'%d'
)
);
});
}
You'll want to make sure to handle the data appropriately before saving it, of course. And again, I'm not sure why you'd need a custom "meta" table, but farbeit from me to say you "shouldn't" (especially depending on your particular usecase) - but something like the above would get you started.
To summarize:
Display your custom meta box with WP's metabox functions
Handle the save_post hook for your custom fields separately
Sanitize, trim, or otherwise make sure the data being stored is supposed to be stored in accordance to best practices for the field type
Make use of the global $wpdb class to update it.
Also of note, this answer doesn't go into CREATING the database table - because that depends on your storage engine, particular indexing needs, etc. But in general you should be able to search for "create database table in [whatever storage language]" to get a walkthrough of creating the table - then use the outline above to store the data in it.
This is the official Wordpress guide: https://developer.wordpress.org/plugins/metadata/custom-meta-boxes/

Meta_key and meta_value - Wordpress

As the question asks, I'm trying to understand one thing, as this is a popular of the fields within the table, but I can't understand their usefulness.
global $wpdb;
$wpdb->insert(
$wpdb->postmeta,
array(
'post_id' => '1',
'meta_key' => 'address',
'meta_value' => '1428 Elm St.'
),
array(
'%d',
'%s',
'%s'
)
);
One thing is the post-table table?
What is the use of this table as in the previous case, for the seo?
in my searches on google, I saw that setting the correct tags, involves a better indexing by google, and for this there is a truly spectacular tool, which allows you to have access by entering the word of the topic we want to write like post and get all the queries, that people type more on google: (https://answerthepublic.com/)
but setting tags and populating the postmeta table are not the same thing?
What is the utility of populating with a code like the postmeta table before?
Its NOT for SEO. Its for custom fields. On WP by default for posts and pages you have wp-post table, that tables has following columns (https://i.imgur.com/NCBslgq.png) for expanding functionality and adding extra custom fields WP has other table wp-postmeta (meta_id, post_id, meta_key, meta_value). So if you want add address field to post or custom post, you attaching meta field to that post using add_post_meta() https://codex.wordpress.org/Function_Reference/add_post_meta

Viewing, adding and editing database content

I just started using Drupal and I was wondering if there is an easy way of viewing, adding or editing data from my custom database. Are there tutorials/modules which allow me to do these actions?
Sorry for the newbie question, I have no idea what to look for...
This question is perhaps more suitable for the Drupal Answers community.
Connecting a custom database
There is a great tutorial on how to connect Drupal to a separate, custom database, called How to connect to multiple databases within Drupal. In summary, it can be achieved by adding the following code into your settings.php file.
<?php
$databases = array();
$databases['default']['default'] = array(
// Drupal's database credentials go here
);
$databases['custom']['default'] = array(
// Custom database credentials go here
);
?>
Accessing custom database
First, tell Drupal that you're accessing a custom database, by inserting db_set_active('custom'); right before your query. To switch back to Drupal's default database, insert db_set_active();.
To make queries to your database, refer to a list of Database Functions. Although these functions are geared more towards a Drupal's default database, you'll find that certain functions will work on a custom database. For example, for simple SELECT queries, you may want to use the db_query.
db_query usage:
<?php
$uid = 1;
$result = db_query('SELECT n.nid, n.title, n.created
FROM {node} n WHERE n.uid = :uid', array(':uid' => $uid));
// Fetch next row as a stdClass object.
$record = $result->fetchObject();
// Fetch next row as an associative array.
$record = $result->fetchAssoc();
// Fetch data from specific column from next row
// Defaults to first column if not specified as argument
$data = $result->fetchColumn(1); // Grabs the title from the next row
// Retrieve a single value
$result->fetchField();
// Retrieve all records into an indexed array of stdClass objects.
$result->fetchAll();
// Retrieve all records as stdObjects into an associative array
// keyed by the field in the result specified.
// (in this example, the title of the node)
$result->fetchAllAssoc('title');
// Retrieve a 2-column result set as an associative array of field 1 => field 2.
$result->fetchAllKeyed();
// Also good to note that you can specify which two fields to use
// by specifying the column numbers for each field
$result->fetchAllKeyed(0,2); // would be nid => created
$result->fetchAllKeyed(1,0); // would be title => nid
// Retrieve a 1-column result set as one single array.
$result->fetchCol();
// Column number can be specified otherwise defaults to first column
$result->fetchCol($db_column_number);
// Count the number of rows
$result->rowCount();
?>
You were not clear if you need to merely manage the data, or edit the data in Drupal. If managing data is the need, use a front-end. Since you are using Drupal, you must be using PHP. If you are new to accessing databases, you may like to use PHPMyAdmin http://www.phpmyadmin.net. It may be already included with your PHP distribution if you installed PHP with MAMP, or XAMMP or one of the similar packages, but you didn't say.
Viewing, adding and editing database data in Drupal requires reading and understanding the Drupal database API https://www.drupal.org/developing/api/database

order by custom field include even if empty - wordpress

I have a query for a page of posts.
It return results based on a custom post type, and custom field value. Now I've added the ability to order the results based on another custom field.
$loop = new WP_Query( array ( 'post_type' => 'new', 'orderby' => 'meta_value_num', 'meta_key' => 'over-length', 'meta_query' => array( array( 'key' => 'over-make', 'value' => 'Doral', 'compare' => 'LIKE') ) ) );
I've run into a bit of a problem. I'm ordering the results by a custom field called 'over-length' but it seems that if a post doesn't contain a value for 'over-length' it is excluded from the results.
I'm wondering how could I change my code so that it included post that don't have a value for orderby.
Also just thought of a workaround, but not sure how to do it. I'm using a plugin called "more fields" to create my custom fields. Would it be easier to check if the 'over-length' field is empty and set it to 0? if so how do I go about doing this.
Update
I've looked into the issue a bit further. It seems that if no value is given to 'over-length' the custom field is not added to wp_postmeta in the database. If I give a post a over-length value then go back and remove it it does in fact include the result in my query as the field still exist in the database. So how can I get this custom field to be entered into the database if it has a value or not?
About your last request - for a way to add a meta_key (custom field) on all posts even if it is left blank:
I often use the plugin Custom Fields Template for this kind of thing. It is similar to the one you are using (more fields) but it gives you many possibilities to play with the fields, and most importantly for this case, you can adjust hidden fields and default values. You can perhaps set a default=' ' (space) to have the field inserted if left blank. Or, with a bit more work, modify the plugin code to insert all the fields to DB without checking for empty the values. In the case of CustomFieldsTemplate it shouldn't be hard to do it.

Resources