How to check if post have meta data and display it by function?
I have post type Portfolio and meta fields (_wi_next-script-part and _wi_prev-script-part)
function wi_next_prev_part_links($content) {
global $wp_query;
$postid = $wp_query->post->ID;
if ( is_singular( 'portfolio' ) ) {
if ( get_post_meta( $postid, '_wi_prev-script-part', true ) ) {
$prev_script_part = get_post_meta( $postid, '_wi_prev-script-part', true );
$content .= '← Prev Part Link';;
}
if ( get_post_meta( $postid, '_wi_next-script-part', true ) ) {
$next_script_part = get_post_meta( $postid, '_wi_next-script-part', true );
$content .= 'Next Part Link →';
}
}
return $content;
}
add_filter ('the_content', 'wi_next_prev_part_links', 0);
There are two ways of doing this. One is to check the value of the meta key and one is to check if the meta key exists.
Checking the value
As explained in the get_post_meta documentation the function will return an empty string or an empty array if the meta key your tried accessing does not exists. Since both an empty string and an empty array are falsy you can use a simple if statement to check whether a meta key has valid meta data or not as such:
if ( get_post_meta( $postid, '_wi_prev-script-part', true ) )
{
//Do something
}
Checking for the key
However, in some instances an empty string is considered to be a valid value. If your code regards empty string as a desirable value you will need to check the for the existence of the meta key itself. We can do that with the get_post_custom_keys function:
if( in_array( '_wi_prev-script-part', get_post_custom_keys($postid) ) )
{
//Do something
}
Related
I have a taxonomy named talent_cat which is the category of said post, has 4 values: modelos, atores, musica, djs and inside each individual talent_cat there are these post meta keys:talent_id_1495127471815 for modelostalent_id_1495127471816 for atorestalent_id_1495127471817 for musica talent_id_1495127471818 for djs
How can I build a conditional to show the right post meta depending on the talent_cat of said post? So if the post belongs to talent_cat = modelos it returns the talent_id_1495127471815 and not the other values.
I tried this but unsuccessfully:
$talent_data = get_the_term_list( $post->ID, 'talent_cat');
switch( $talent_data ) {
case 'modelos':
echo get_post_meta(get_the_ID(), 'talent_id_1495127471815', true);
break;
}
Thanks.
The function get_the_term_list returns HTML but you need to get an array or object to check your statement. You need to use get_the_terms function instead. Your code should look like this:
global $post;
$talent_data = get_the_terms( $post->ID, 'talent_cat');
// check for errors or empty data
if ( is_wp_error( $talent_data ) || empty( $talent_data ) ) {
return;
}
foreach ( $talent_data as $term ) {
// you can check for name or slug or id
switch( $term->slug ) {
case 'modelos':
echo get_post_meta($post->ID, 'talent_id_1495127471815', true);
break;
}
}
I'm trying to generate a unique random value from an array and store it in another array so it can't be used again.
I've managed to generate the random value based on a meta field but I'm not sure how I would go about making this unique and ensuring the same values aren't being generated again. I've created an empty array $tickethistory to save the values into. Is it possible the next time it runs to run a validation check so the $lottery_max_tickets don't include the $tickethistory values?
I'm using the function below which returns the number and I', calling it when customers purchase a product in Woocommerce.
function add_lottery_ticket_number( $postid ) {
$tickethistory = array();
$lottery_max_tickets = get_post_meta( $postid, '_max_tickets', true );
$max_tickets = range(1, $lottery_max_tickets);
$ticketallocated = array_rand($max_tickets, 1);
$tickethistory[] = $ticketallocated;
return $ticketallocated;
}
for ( $i = 0; $i < $item_meta['_qty'][0]; $i++ ) {
add_post_meta( $product_id, '_participant_id', $order->get_user_id() );
$participants = get_post_meta( $product_id, '_lottery_participants_count', true ) ? get_post_meta( $product_id, '_lottery_participants_count', true ) : 0;
update_post_meta( $product_id, '_lottery_participants_count', intval( $participants ) + 1 );
$this->add_lottery_to_user_metafield( $product_id, $order->get_user_id() );
$ticketnumber = $this->add_lottery_ticket_number($product_id);
$log_ids[] = $this->log_participant( $product_id, $order->get_user_id(), $ticketnumber, $order_id, $item );
}
As you can see here, you can use storing array in the metadata - in your case, the tickethistory array.
But, for your case I would take different approach - create ticket options once and assign the first element each time.
Consider the following:
function add_lottery_ticket_number( $postId ) {
if (metadata_exists('post', $postId, 'optionsToGive')) {
$ticketOptions = get_post_meta( $postId, 'optionsToGive', true );
} else {
$lottery_max_tickets = get_post_meta( $postid, '_max_tickets', true );
$ticketOptions = range(1, $lottery_max_tickets);
shuffle($ticketOptions ); //random order of all number
}
$ticketAllocated = array_shift($ticketOptions); //take the first element
update_post_meta( $postId, 'optionsToGive', $ticketOptions ); //update all the rest
return $ticketAllocated;
}
Notice, if all numbers has been assign this will return null.
As I never tested this code please consider it as pseudo.
I'm wanting to change a WordPress post's permalink (post_name) dynamically every time time a post is saved/updated by pulling from a custom field present in the post and replacing the permalink with this value. I have code within functions.php which is working, except that it appends -2 to the permalink. I assume this is because something is occurring twice, the first time resulting in the permalink I want, and the second resulting in WordPress responding to the "duplicate" by adding -2.
This is the current code:
add_action('save_post', 'change_default_slug');
function change_default_slug($post_id) {
if ( defined('DOING_AUTOSAVE') && DOING_AUTOSAVE )
return;
if ( !current_user_can('edit_post', $post_id) )
return;
remove_action('save_post', 'change_default_slug');
wp_update_post(array('ID' => $post_id, 'post_name' =>get_post_meta($post_id,'request_number',true)));;
add_action('save_post', 'change_default_slug');
}
I'll take a crack at this...
Now, this is assuming that you are using ACF for your custom field...
If not, simply update the code with the WP custom meta functions instead. Oh, don't forget the change the field_5fed2cdbc1fd2 with your ACF field Key
add_filter('save_post', 'change_post_name', 20, 1);
function change_post_name($post_id)
{
$post_type = get_post_type();
if ($post_type == "post"){
$acf_title_field = $_POST['acf']['field_5fed2cdbc1fd2']; // get the field data by $_POST
if (!empty($acf_title_field)) {
// update the title in database
$wpdb->update($wpdb->posts, array('post_title' => $acf_title_field, 'post_name' => sanitize_title($acf_title_field)), array('ID' => $post_id));
}
}
}
add_filter( 'wp_insert_post_data', 'update_post_name', 50, 2 );
function update_post_name( $data, $postarr ) {
$post_type = get_post_type();
if ($post_type == "post"){
//Check for the post statuses you want to avoid
if ( !in_array( $data['post_status'], array( 'draft', 'pending', 'auto-draft' ) ) ) {
$acf_title_field = $_POST['acf']['field_5fed2cdbc1fd2']; // get the field data by $_POST
// $data['post_name'] = sanitize_title( $data['post_title'] );
$data['post_name'] = sanitize_title( $acf_title_field );
}
return $data;
}
}
I would like to add a dynamic value to a custom field in wordpress.
I do not want to use update_post_meta() because it is a dynamic value that I want to add every time when the post is loaded ..
The custom field is tm_video_file, and retrieved with get_post_meta().
This will return a URL, I beed to append a query string to it.
I am trying to hook a function that will change the value of "tm_video_file", but without success.
// URL will be called as:
get_post_meta($post_id, 'tm_video_file', true);
// I try to add a filter for these meta data
add_filter('get_post_metadata', array($this,'add_hash_key'),1,4);
// And try to append the tm_video_file value here:
public function add_hash_key ($meta_value, $post_id, $meta_key, $single ) {
if($meta_key == 'tm_video_file') {
var_dump($meta_value); // ALWAYS NULL ???
var_dump($post_id);
var_dump($meta_key);
var_dump($single);
}
return $meta_value.'?hash=something-dynamic-here';
}
UPDATE:
I have found out some information on the net, and I think I am a bit closer to the solution:
public static function add_hash_key($meta_value, $object_id, $meta_key, $single) {
if ($meta_key == 'tm_video_file') {
$meta_type = 'post';
$meta_cache = wp_cache_get($object_id, $meta_type . '_meta');
if ( !$meta_cache ) {
$meta_cache = update_meta_cache( $meta_type, array( $object_id ) );
$meta_cache = $meta_cache[$object_id];
}
if ( isset($meta_cache[$meta_key]) ) {
if ( $single ) {
$meta_value = maybe_unserialize( $meta_cache[$meta_key][0] );
} else {
$meta_value = array_map('maybe_unserialize', $meta_cache[$meta_key]);
}
}
// At this point $meta_value contains the right data!
$meta_value .= '?Hash-Here';
return array($meta_value); //
}
}
In wordpress file meta.php there is a function called:
get_metadata()
This will apply filters, and returns the value in the end:
$check = apply_filters( "get_{$meta_type}_metadata", null, $object_id, $meta_key, $single );
if ( null !== $check ) {
if ( $single && is_array( $check ) )
return $check[0];
else
return $check;
}
//For some reason $check is ALWAYS null .. ? But the filter function did run for sure..
So I'm trying to work out conditionals with Wordpress post meta. I've been using get_post_meta() to display content if user had populated the post meta, but I need to improve the rule and add some additional conditionals to it.
Basically, what I need to do is extend this condition to multiple keys. If the user typed in both post_meta_1 and post_meta_2 some code will run, if not then some other code will run.
This is the code I'm currently using:
if (!((get_post_meta($post->ID, 'post_meta_1', TRUE))=='')) {
// code here
} elseif {
// code here as well
}?>
Here's how far my PHP logic goes:
if (!((get_post_meta($post->ID, array('post_meta_1', 'post_meta_2'), false))=='')) {
// code here
} elseif {
// code here as well
}?>
EDIT
Somehow I managed to get it to work by using this method:
<?php
$post_meta_1 = get_post_meta($post->ID, 'post_meta_1', TRUE);
$post_meta_2 = get_post_meta($post->ID, 'post_meta_2', TRUE);
if ($post_meta_1 && $post_meta_2) : ?>
CODE HERE
<?php endif; ?>
You will need to call get_post_meta() individually for each meta_key that you would like a value for. You can have multiple values stored under a single meta_key which is what the third parameter is for - true returns a single value, false an array of values for that meta_key. The result of get_post_meta() will be === false if there is no value in the database, or you can just check for empty() as well.
$capacity = get_post_meta( $post->ID, 'post_meta_1', true );
$approved_environment = get_post_meta( $post->ID, 'post_meta_2', true );
if ( $capacity && $approved_environment ){
// post_meta_1 AND post_meta_2 are set
}
if ( false !== $capacity && false !== $approved_environment ){
// post_meta_1 AND post_meta_2 are not set
}
if ( false !== $capacity || false !== $approved_environment ){
// post_meta_1 AND/OR post_meta_2 are not set
}
if ( empty( $capacity ) && empty( $approved_environment ) ){
// post_meta_1 AND post_meta_2 are not set or are equal to "", null, or 0
}
if ( empty( $capacity ) || empty( $approved_environment ) ){
// post_meta_1 AND/OR post_meta_2 are not set or are equal to "", null, or 0
}