get_post_meta does not accept variable for some reason - php

I have a meta value set for a post. The meta is '_test_field_one' and the value is "Cats".
I've made the following function just to test it (it's in a class, yes):
public function get( $post_id, $metakey ) {
echo $metakey; // test_field_one
$metakey = '_' . $metakey;
echo $metakey; // _test_field_one
echo get_post_meta( $post_id, $metakey, true ); // nothing ..
echo get_post_meta( $post_id, '_test_field_one', true ); // Cats
return get_post_meta( $post_id, $metakey, true );
}
In the comments after each echo I've indicated what gets printed on the screen.
Does anyone know what is the reason for the third echo to not work (additionally the function returns nothing).

Apparantly $metakey and '_test_field_one' are unequal but appear equal when echoed. The most likely solution is that $metakey has some trailing spaces. You can remove them using trim($metakey).
Official documentation

Related

How can I get my number of views for a single post in wordpress?

I'm facing a problem, while I tried to retrieve number of views for a single post by the following code:
<?php $id = get_the_ID(); ?>
<?php $views = get_post_meta($id, 'post_views_count', true); var_dump($views) ?>
But I got string(0)"" result.
As per my understanding, it means there is no 'post_views_count' column available in my database and so I found looking up my database.
Now, how can I get number of views for a single post?
Best Regards
even i was facing this problem but this code helped me i hope this helps you.
Copy this code in your function.php before the closing tag?>
function gt_get_post_view() {
$count = get_post_meta( get_the_ID(), 'post_views_count', true );
return "$count views";
}
function gt_set_post_view() {
$key = 'post_views_count';
$post_id = get_the_ID();
$count = (int) get_post_meta( $post_id, $key, true );
$count++;
update_post_meta( $post_id, $key, $count );
}
function gt_posts_column_views( $columns ) {
$columns['post_views'] = 'Views';
return $columns;
}
function gt_posts_custom_column_views( $column ) {
if ( $column === 'post_views') {
echo gt_get_post_view();
}
}
add_filter( 'manage_posts_columns', 'gt_posts_column_views' );
add_action( 'manage_posts_custom_column', 'gt_posts_custom_column_views' );
Then copy this code in single.php file in the while loop
<?php gt_set_post_view(); ?>
& now paste this code where you want to show post count
<?= gt_get_post_view(); ?>

How to display a custom field (variable) in a shortcode

I would like to have a shortcode display a value which is a custom field in Wordpress. In this case the variable "prijs".
I have tried lots of solutions on the net and lots more but no luck so far. Can anyone help me ?
Why doesn't this script show anything ? How do i display the custom field "prijs" ?
<?php
function showdetails_shortcode( $attr, $content = null ) {
return <?php $key="prijs"; echo get_post_meta($post->ID, $key, true); ?>
}
add_shortcode('showdetails', 'showdetails_shortcode');
?>
Why doesn't this script show anything?
The provided code shows a couple of syntax errors, of which the most crucial is the re-invocation of <?php within a PHP statement.
If prijs is a good custom field key for the post where this shortcode is placed, then it should work.
function showdetails_shortcode( ) {
$post_id = get_the_ID();
//either output the value or let us know the code is working but the value has not been found
$output = get_post_meta( $post_id, 'prijs', true) ? get_post_meta( $post_id, 'prijs', true) : 'NO CUSTOM VALUE FOUND' ;
return $output;
}
add_shortcode('showdetails', 'showdetails_shortcode');
Responding to a comment, here's a version with two fields and tabular output, keeping in mind that there would be cleaner (more flexible and parsimonious) ways to derive the variables and produce the output for a larger number of fields.
function showdetails_shortcode( ) {
$post_id = get_the_ID();
//extract the field values
$field1 = get_post_meta( $post_id, 'prijs', true) ? get_post_meta( $post_id, 'prijs', true) : 'PRIJS NOT FOUND';
$field2 = get_post_meta( $post_id, 'prijs2', true) ? get_post_meta( $post_id, 'prijs2', true) : 'PRIJS2 NOT FOUND';
//prepare html table output
$output = '<table><tbody>';
$output .= '<tr><td>' . $field1 . '</td></tr>';
$output .= '<tr><td>' . $field2 . '</td></tr>';
$output .= '</tbody></table>';
//return the html
return $output;
}
add_shortcode('showdetails', 'showdetails_shortcode');

Add unique random value from array

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.

Check and add to the post content

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
}

Adding nl2br to my Wordpress custom Meta Box

Okay let me see if I can explain this right. In wordpress we have a box to insert an excerpt. We need to add a second excerpt box. Instead of manually adding a custom field to every post I have placed a function to automatically add a custom field in the form of a Meta box on the admin post page.
Okay so this is the problem that i'm having this function is working except for the fact that whatever you enter into this field it loses it's line breaks. So when our writers are contrubuting to this field in order to keep formatting of the block of text I have to manually add to the end of the paragraph.
Here is my code:
function my_create_post_meta_box() {
add_meta_box( 'my-meta-box', 'Second Excerpt', 'my_post_meta_box', 'post', 'normal', 'high' );
}
function my_post_meta_box( $object, $box ) { ?>
<p>
<label for="second-excerpt">
<strong>Second Excerpt With Images for Post List Page</strong>
</label>
<textarea name="second-excerpt" id="second-excerpt" cols="60" rows="4" tabindex="30" style="width: 97%;" wrap="hard"><?php echo wp_specialchars( get_post_meta( $object->ID, 'Second Excerpt', true ), 1 ); ?></textarea>
<input type="hidden" name="my_meta_box_nonce" value="<?php echo wp_create_nonce( plugin_basename( __FILE__ ) ); ?>" />
</p>
<?php
}
function my_save_post_meta_box( $post_id, $post ) {
if ( !wp_verify_nonce( $_POST['my_meta_box_nonce'], plugin_basename( __FILE__ ) ) )
return $post_id;
if ( !current_user_can( 'edit_post', $post_id ) )
return $post_id;
$meta_value = get_post_meta( $post_id, 'Second Excerpt', true );
$new_meta_value = stripslashes( $_POST['second-excerpt'] );
if ( $new_meta_value && '' == $meta_value )
add_post_meta( $post_id, 'Second Excerpt', $new_meta_value, true );
elseif ( $new_meta_value != $meta_value )
update_post_meta( $post_id, 'Second Excerpt', $new_meta_value );
elseif ( '' == $new_meta_value && $meta_value )
delete_post_meta( $post_id, 'Second Excerpt', $meta_value );
}
Thanks and any help would do.
Use wpautop function on frontend template. Like:
<?php $yourvalue = get_post_meta($post->ID, "yourvalue", true);
if ($yourvalue != ""){ ?>
<dt>Consultório:</dt>
<dd><?php echo wpautop( $consultorio, $br = 1 ); ?></dd>
<?php } ?>
Just add this line after $new_meta_value = ...:
$new_meta_value = nl2br($new_meta_value);
And instead of comparing your values to '', it's better to use empty(). Also some of the comparisons are unneeded. Thus, the add/update/delete part of your save function can be written like this:
if(empty($meta_value)) {
add_post_meta( $post_id, 'Second Excerpt', $new_meta_value, true );
} elseif(empty($new_meta_value)) {
delete_post_meta( $post_id, 'Second Excerpt', $meta_value );
} else {
update_post_meta( $post_id, 'Second Excerpt', $new_meta_value );
}
Note that it's always advisable to use curly braces even if your statement is only one row long. It improves readability and doesn't mess things up if/when you have to add another row to the if clause.
Don't modify the data saved to the database. Save exactly what the user enters. Instead modify the content when you need to display it. This way when the user comes back to edit the field the edit what they put in, not what you've made of their content.
Use wpautop to do the same translation on your text that WordPress applies to the raw content entered in the post-content field and do it when the content is requested for display.
Okay I have found another solution to my problem. Thank you Tatu for getting my brain workin. For those who are looking for a solution this is what I did:
$new_meta_value = "<p>" . implode( "</p>\n\n<p>", preg_split( '/\n(?:\s*\n)+/', $new_meta_value ) ) . "</p>";

Categories