wordpress plugin creation get_post_meta - wordpress

I am building my first plugin, and I am using as a reference the following link.
http://www.sitepoint.com/create-a-voting-plugin-for-wordpress/
and I am trying to underestand the following part of the code:
function voteme_addvote()
{
$results = '';
global $wpdb;
$post_ID = $_POST['postid'];
$votemecount = get_post_meta($post_ID, '_votemecount', true) != '' ? get_post_meta($post_ID, '_votemecount', true) : '0';
$votemecountNew = $votemecount + 1;
update_post_meta($post_ID, '_votemecount', $votemecountNew);
$results.='<div class="votescore" >'.$votemecountNew.'</div>';
// Return the String
die($results);
}
I run the code and it works, but I just dont understand the following:
What is "get_post_meta" doing?
Does it create a custom meta field, the same as add_post_meta?, if it doesnt why there is not an add_post_meta?
I checked the DB, and it looks like it is creating a custom meta field... so in that order what is the difference between get_post_meta and add_post_meta?
Thanks very much for helping me understand this.

The first time your code runs, get_post_meta returns '' so $votemecount is set to 0. The following update_post_meta creates the new meta field as documented below. Values that start with _ are not displayed (are hidden meta fields).
The function, update_post_meta(), updates the value of an existing meta key (custom field) for the specified post.
This may be used in place of add_post_meta() function. The first thing this function will do is make sure that $meta_key already exists on $post_id. If it does not, add_post_meta($post_id, $meta_key, $meta_value) is called instead and its result is returned.

Related

Updating an ACF field after creating a Woocommerce attribute

I have a set of products (courses) that are dependent on a calendar.
The calendar is generated by a post type date which has an ACF field date_start and an associated_product
The logic is; the user creates a post-type Date which adds an attribute term to the associated product's attribute pa_dates.
I have hooked save_post and so far so good, the attribute is written to the product.
I then need to copy the date field to the term created $term_set this section doesn't produce anything. (I need this date to order the terms in my product)
Part of the problem is I have no way of interrogating the variables as this is all happening in a hook that has no way of printing output. (I have tried fwrite but with no result)
// Add terms on Date save.
function add_terms_to_date($post_ID) {
if ('date' !== get_post_type() ) {
return;
} else {
$product_id = get_field('associated_product',$post_ID);
$term_name = get_the_title($post_ID);
$taxonomy = 'pa_dates';
$term_set = wp_set_post_terms( $product_id, $term_name, $taxonomy, true );
// up to here, works fine.
// now need to identify that term ($term_set)
// Then I need to write copy the date field to its ACF field in my Date attribute
$selector = "term_date_start"; // the ACF field in the term
$date_start = get_field('date_start', $post_ID); // the date field to be copied
$value = $date_start;
// This next line caused the issue leading to the question so is commented out
// update_field($selector, $value, $term_set);
// and this line is correct
update_field($selector, $value, $taxonomy."_".$term_set);
}
}
add_action('save_post', 'add_terms_to_date');
So, complicated question, simple answer.
The last line should read;
update_field($selector, $value, $taxonomy."_".$term_set);
to avoid confusion with post IDs (RTFM) ACF has a different system for identifying terms. ($taxonomy comes from the earlier line and is pa_dates)
I have edited the post above, just in case it can provide help to someone.

I want to add a new value in the post meta without deleting the old value

I have post meta "metaname" with value "thatsme"
and I want to add a new value "thatsyou" in the post meta "metaname" without deleting the old value "thatsme"
so the result will be:
metaname -> New value
thatsyou -> Old value
how to do it in wordpress?
You can do this simply using add_post_meta as normal.
The 4th (optional) parameter is a boolean to indicate whether the meta key should be unique or not:
false means that you can add another entry using the same key
true means WP won't create a new entry or change the old one.
You already have a key set up, presumably using code like this:
add_post_meta( $post_id, 'metaname', 'thatsme');
To add another value, you just to the same again - I've added false for the unique parameter here to highlight it, but it is the default value so there is no need
add_post_meta( $post_id, 'metaname', 'thatsyou');
Then to retrieve all the values of the meta-key, you can do the following:
$my_meta_keys = get_post_meta( $post_id, 'metaname', false ); // get all values for this key
if ( ! empty( $my_meta_keys ) ) {
// loop through all values
foreach( $my_meta_keys as $value)
echo $value; // or whatever you want to do with it
}
References:
Wordpress Code Reference for add_post_meta
Wordpress Code Reference for get_post_meta

Wordpress search database values and return

i'm have been searching for a code that will do some thing like this in WordPress and but it CANT call on woocommerce
nothing seems to work
if
get_post_meta( get_the_ID(), '_regular_price' is greater then 1)
do this
else
do this code
It depends on the place where you are using this function.
Imagine you are trying to edit a product page. In your woocommerce templates folder, you find for example: price.php
Usually there is one global variable available already, and if it's not available you can set it with global $product. With $product->get_id() you can get the product id then.
With the global variable the sale price is then available like this $price = $product->get_sale_price();
In order to make the if statement, you need the data so then the next step. Maybe your price is empty for some reason, which returns undefined, making it difficult to do the if statement
if (empty($price))
$price = 0;
if($price > 1))
// do your thing
$my_post_meta = get_post_meta( get_the_ID(), 'sale_price', true);
if ( ! empty ( $my_post_meta ) ) {
do code here
} else
do other code
this works for me

Add meta field just after post is published

I'm trying to add a custom field of event_month when a post is published or saved. I'm using the save_post action and getting the contents of a custom field containing the date and trying to store this in a separate custom field with just the month. This works perfectly when saving a post that has already been created. I've shown my code below.
add_action('save_post', 'update_event_date');
function update_event_date($post_id){
$post_type = get_post_type($post_id);
$event_datee = get_post_meta($post_id, '_EventStartDate', true);
if ($post_type == 'tribe_events'){
$month = date("m",strtotime($event_datee));
update_post_meta($post_id, 'event_month', $month);
}
}
The problem arises when creating a new post. I think this is because the action fires before the _EventStartDate meta has been created and therefore the month can't be taken from this.
The hook is firing correctly and as intended when saving/updating a post but doesn't correctly get the month from the meta when creating a new post.
I'd really appreciate it if someone could provide me with some guidance.
To access post meta passed together with yours, you can do something like this:
$event_datee = get_post_meta($post_id, '_EventStartDate', true);
foreach($_POST['meta'] as $meta){
if($meta['key'] == '_EventStartDate'){
$event_datee = $meta['value'];
}
};

Auto-remove custom field with no value on publish

I got some plugins that auto-generates custom fields. Does anyone know how to automatically remove empty custom fields from post when I press "publish"?
A check I can put in my functions.php that does a check and removes the custom field if there is no value?
Here is the solution:
add_action('save_post','my_cf_check');
function my_cf_check($post_id) {
// verify this is not an auto save routine.
if ( defined('DOING_AUTOSAVE') && DOING_AUTOSAVE ) return;
//authentication checks
if (!current_user_can('edit_post', $post_id)) return;
//obtain custom field meta for this post
$custom_fields = get_post_custom($post_id);
if(!$custom_fields) return;
foreach($custom_fields as $key=>$custom_field):
//$custom_field is an array of values associated with $key - even if there is only one value.
//Filter to remove empty values.
//Be warned this will remove anything that casts as false, e.g. 0 or false
//- if you don't want this, specify a callback.
//See php documentation on array_filter
$values = array_filter($custom_field);
//After removing 'empty' fields, is array empty?
if(empty($values)):
delete_post_meta($post_id,$key); //Remove post's custom field
endif;
endforeach;
return;
}
wp_insert_post_data is a hook that happens before a database write in the admin panel. You can probably use that to call a function that checks for data, then strips out any empty custom field entries.
Or, you could use the_content hooks on the front end to strip out empty custom fields before they get displayed to the user.
Or, if you have control of the theme files, you can just test for data in your custom fields before displaying them.

Resources