WordPress Custom Fields (meta key)

A custom fields are, basically, the properties for a post type.

The creation phase of a custom field is divided in two parts:

  1. Creation of the structure
  2. Define the behavior

Creation of the structure

Metabox is the graphic container of our custom fields. It will appear as a fieldsets in the admin page, containing our custom fields.

add_action('add_meta_boxes_{post_type_name}','add_metabox_function');

function add_metabox_function($post)
{
  add_meta_box('id','title','metabox_field_function','post_type_name','normal','default');
}

This function will contain all necessary html, CSS and logical code to manage and show our custom fields.

function metabox_field_function()
{
  //html code to show fields and php code to manage fields
}

One interesting thing is that you don’t have to define an html form and a submit button, because your code will be automatically wrapped in.
So: no form and no submit butto, but the normal html input tag.

After defining the html field in the previous step it’s time to manage the submit of your metadata.

The hook to define it is:

add_action('save_post','save_posttypename_meta', 10, 2);
and the function to manage it:
function save_posttypename_meta($post_id, $post) 
{
  //php code to get fields from POST and save them into db
}

Define the behavior

With this variable you can access directly to your wordpress database to make query, access tables and so on

global $wpdb;
Ex. to get the list of content of a custo post type slb_list
$list_query=$wpdb->get_results("select ID, post_title from {$wpdb->posts} where post_type='slb_list' and post_status in ('draft', 'publish')");

Ex. get the post id

$post_id = $post->ID;

 

to read custom field value from the DB, you can use this code the wordpress function “get_post_meta”:

$first_name = (!empty(get_post_meta($post_id, 'slb_first_name', true))) ? get_post_meta($post_id, 'slb_first_name', true) : '';

Basically it takes the custom field value of that post_id and that custom field name

To take parameter value from a http request (after a submit) in PHP you have to do like this:

$first_name = ( isset($_POST['slb_first_name']) ) ? sanitize_text_field($_POST['slb_first_name']) : '';

 

To add a customfield, and its value, do this:

add_post_meta( $post_id, 'customfield_name', value, true/false );

The last parameter means that you want to exlude (true) or you don’t mind (false) duplicated values of that custom field for that post_id 

to update a custom field:

update_post_meta($post_id, ‘customfield_name’, value);
To delete the existing list meta for that post id:
delete_post_meta( $post_id, 'customfield_name');

Yes, all values of that custom fields will be deleted, even if you associated more than one value.

0 Comments

Add Your Comment: