Don't have access to post meta in save_post action - php

So what I've noticed is that if I check for a meta value in my save_post function, it comes as blank, meaning the meta value hasn't actually been entered into the post. Looking at this code for example,
function order_mirror_create($post_id) {
global $post;
if($post->ID == ''){
$pid = $post_id;
} else {
$pid = $post->ID;
}
$videohost = get_post_meta($pid, 'video_provider', true);
if ($videohost == "UploadAnime") {
add_post_meta($pid, 'video_display_order', 1, true);
} else {
add_post_meta($pid, 'video_display_order', $videohost, true);
}
}
$videohost is actually blank, so get_post_meta($pid, 'video_provider', true) does not return the actual value of that meta field because it hasn't been created yet.
So in the code above, the else is always the one that runs, since $videohost is blank. How can I fix this? What action should I use that would run in such a manner that the post meta have already been added to the post.

You should change the following:
if ($videohost == "UploadAnime") {
add_post_meta($pid, 'video_display_order', 1, true);
} else {
add_post_meta($pid, 'video_display_order', $videohost, true);
}
To:
if ($videohost == "UploadAnime") {
update_post_meta($pid, 'video_display_order', 1, true);
} else {
update_post_meta($pid, 'video_display_order', $videohost, true);
}
I find add_post_meta has never really worked for me, whereas update_post_meta does.

Related

What's the best way to store post_meta value in variable, with a default value?

What's the most efficient and simplest way to store a post_meta value in a variable, along with a default value if the meta_key doesn't exist?
I want to use something like this, the meta_value will always be a number:
$bv_faq_thumbs_up = isset(get_post_meta($post->ID, '_bv_faq_thumbs_up', true)) ? get_post_meta($post->ID, '_bv_faq_thumbs_up', true) : 0;
But this throws a PHP error:
Fatal error: Cannot use isset() on the result of an expression
Off the top of my head, the only thing I can think of something like:
if(get_post_meta($post->ID, '_bv_faq_thumbs_up', true) === null) {
$bv_faq_thumbs_up = 0;
} else {
$bv_faq_thumbs_up = get_post_meta($post->ID, '_bv_faq_thumbs_up', true);
}
But that seems quite long-winded and bloated, is this the correct way (in terms of speed and efficiency, and tidiness)
Try this code;
$bv_faq_thumbs_up = get_post_meta($post->ID, '_bv_faq_thumbs_up', true);
if(empty($bv_faq_thumbs_up)) {
$bv_faq_thumbs_up = 0;
}
OR
$bv_faq_thumbs_up = get_post_meta($post->ID, '_bv_faq_thumbs_up', true);
$bv_faq_thumbs_up = (!empty($bv_faq_thumbs_up)) ? $bv_faq_thumbs_up : 0;
OR
if(metadata_exists( 'post', $post->ID, '_bv_faq_thumbs_up' ) === null) {
$bv_faq_thumbs_up = 0;
} else {
$bv_faq_thumbs_up = get_post_meta($post->ID, '_bv_faq_thumbs_up', true);
}
for future users
Based on Stender's comment, I found using metadata_exists instead of isset allows the same idea to work, still contained within a single sentence, and only using the get_post_meta() function once, whilst setting a default value.
$bv_faq_thumbs_up = metadata_exists('post', $post->ID, '_bv_faq_thumbs_up') ? get_post_meta($post->ID, '_bv_faq_thumbs_up', true) : 0;
You can do this since PHP 7:
$result = get_post_meta($id, $key, true) ?? false; // false is default value
Alternative:
if (($result = get_post_meta($id, $key, true) ?? false) !== false) {
// do stuff but only if the $key exists
echo $result;
}
There is no need to call metadata_exists() or get_post_meta() twice. Explanation for ?? can be found here https://www.phptutorial.net/php-tutorial/php-null-coalescing-operator/

Can you display an empty value with an array if the value is missing?

I have this piece of code.
What it does is it shows the supplier name via email.
The problem is that if the supplier name is empty as some dont need it, i get an error which redirects me to this piece of code.
Is there a way for me to say that if the suppliername is empty, to show as none?? or as a blank space?
<?php
$array1supplier = get_post_meta($productId, 'fancyincarray', true);
echo $array1supplier['supplier'];
?>
To check if the array has a key you can use the isset function like so:
$array1supplier = get_post_meta($productId, 'fancyincarray', true);
echo (isset($array1supplier['supplier'])) ? $array1supplier['supplier'] : '';
Use empty() function to check if empty or not.
Code:
<?php
$array1supplier = get_post_meta($productId, 'fancyincarray', true);
if(empty($array1supplier['supplier'])) {
echo "Supplier is empty!";
} else {
echo $array1supplier['supplier'];
}
?>
or
You Can also use isset() function to check if it is set or not.
Code:
<?php
$array1supplier = get_post_meta($productId, 'fancyincarray', true);
if(isset($array1supplier['supplier'])) {
echo $array1supplier['supplier'];
} else {
echo "Supplier is empty!";
}
?>
or
You can just use if($array1supplier['supplier'] == "")
Code:
<?php
$array1supplier = get_post_meta($productId, 'fancyincarray', true);
if($array1supplier['supplier'] == "") {
echo "Supplier is empty!";
} else {
echo $array1supplier['supplier'];
}
?>
All of them are same, you can choose anything you want
It seems like you are expecting an array to be returned from get_post_meta()
According to WP Code Reference:
get_post_meta ( int $post_id, string $key = '', bool $single = false )
Retrieve post meta field for a post.
Return: (mixed) Will be an array if $single is false. Will be value of
meta data field if $single is true.
So the last parameter should be false.
Use isset() to determine if a variable is set and is not NULL
Try this:
$array1supplier = get_post_meta($productId, 'fancyincarray', false);
echo (isset($array1supplier['supplier'])) ? $array1supplier['supplier'] : "Empty";
<?php
$array1supplier = get_post_meta($productId, 'fancyincarray', true);
echo (!empty($array1supplier['supplier'])
? $array1supplier['supplier']
: '';
?>

Redirecting back to referer

I am trying to get the referrer url passed as a variable so that I can link back to that page if a cookie isn't already set when a user lands on said page.
Currently looking into $_SERVER['HTTP_REFERER'] but not too sure how that works and how I would pass that in the below function.
Any help would be greatly appreciated.
function cookie_check() {
$post_ID = get_the_ID();
$parent_ID = wp_get_post_parent_id( $post_ID );
if($parent_ID == 9 || $post_ID == 9) {
if(!isset($_COOKIE["mycookie"])) {
header("Location: http://test.dev");
die();
}
}
if($parent_ID == 7 || $post_ID == 7) {
if(!isset($_COOKIE["diffcookie"])) {
header("Location: http://test.dev");
die();
}
}
}

Modifying plural form of views_edit in wordpress

I want to change default Draft text for my custom post type views, and I found a function that could do this:
add_filter( 'views_edit-custom_post_type_name', 'custom_draft_name', 10, 1);
if (!function_exists('custom_draft_name')) {
function custom_draft_name( $views ) {
if (isset($views['draft']) && $views['draft'] != '') {
$views['draft'] = str_replace(esc_html__('Draft', 'custom_post_type_name'), esc_html__('Unapproved', 'custom_post_type_name'), $views['draft']);
print_r($draft_array);
}
return $views;
}
}
The problem is that I get only singular change for this. So if I had one Draft I'll have one Unapproved. But when I have more than one I'll have two Drafts and automatically I'll have two Unapproveds. Which is terrible. It should be two unapproved. So I tried to use _n() for the plurals, by creating an array to check against with my str_replace:
add_filter( 'views_edit-custom_post_type_name', 'custom_draft_name', 10, 1);
if (!function_exists('custom_draft_name')) {
function custom_draft_name( $views ) {
if (isset($views['draft']) && $views['draft'] != '') {
$draft_array = array(esc_html__('Draft', 'custom_post_type_name'), _n('Draft', 'Drafts' , 10, 'custom_post_type_name'));
$views['draft'] = str_replace($draft_array, esc_html__('Unapproved', 'custom_post_type_name'), $views['draft']);
print_r($draft_array);
}
return $views;
}
}
But I still get Unapproveds instead Unapproved.
Any help how to solve this?
** ANSWER **
And once again I found the solution immediately after I post on SO xD
Just do a wp_count_posts('custom_post_type') like
$custom_posts = wp_count_posts('custom_post_type_name');
if($custom_posts->draft == 1){
$views['draft'] = str_replace(esc_html__('Draft', 'custom_post_type_name'), esc_html__('Unapproved', 'custom_post_type_name'), $views['draft']);
} else{
$views['draft'] = str_replace(esc_html__('Drafts', 'custom_post_type_name'), esc_html__('Unapproved', 'custom_post_type_name'), $views['draft']);
}

How to add Buy Now button in cs-cart

I'm creating a buy-now button cs-cart add-on. I've created an add-on and I've made the add-to-cart functionality work. But cant redirect it to checkout page. I have used "fn_redirect("checkout")" function for the redirection. And used this function below this:
"fn_add_product_to_cart($_REQUEST['product_data'], $cart, $auth);"
What should I do for redirection?
Edit:
My controller (buy_now.php)
if ($mode == 'add') {
if (empty($auth['user_id']) && Registry::get('settings.General.allow_anonymous_shopping') != 'allow_shopping')
{
return array(CONTROLLER_STATUS_REDIRECT, "auth.login_form?return_url=" . urlencode($_REQUEST['return_url']));
}
// Add to cart button was pressed for single product on advanced list
if (!empty($dispatch_extra)) {
if (empty($_REQUEST['product_data'][$dispatch_extra]['amount'])) {
$_REQUEST['product_data'][$dispatch_extra]['amount'] = 1;
}
foreach ($_REQUEST['product_data'] as $key => $data) {
if ($key != $dispatch_extra && $key != 'custom_files') {
unset($_REQUEST['product_data'][$key]);
}
}
}
$prev_cart_products = empty($cart['products']) ? array() : $cart['products'];
fn_add_product_to_cart($_REQUEST['product_data'], $cart, $auth);
fn_save_cart_content($cart, $auth['user_id']);
$previous_state = md5(serialize($cart['products']));
$cart['change_cart_products'] = true;
fn_calculate_cart_content($cart, $auth, 'S', true, 'F', true);
if (md5(serialize($cart['products'])) != $previous_state && empty($cart['skip_notification'])) {
$product_cnt = 0;
$added_products = array();
if (!empty($added_products)) {
Registry::get('view')->assign('added_products', $added_products);
if (Registry::get('config.tweaks.disable_dhtml') && Registry::get('config.tweaks.redirect_to_cart')) {
Registry::get('view')->assign('continue_url', (!empty($_REQUEST['redirect_url']) && empty($_REQUEST['appearance']['details_page'])) ? $_REQUEST['redirect_url'] : $_SESSION['continue_url']);
}
fn_redirect(Registry::get('config.https_location') . "/checkout");
// $msg = Registry::get('view')->fetch('views/checkout/components/product_notification.tpl');
//fn_set_notification('I', __($product_cnt > 1 ? 'products_added_to_cart' : 'product_added_to_cart'), $msg, 'I');
$cart['recalculate'] = true;
} else {
fn_set_notification('N', __('notice'), __('product_in_cart'));
}
}
unset($cart['skip_notification']);
$_suffix = '.checkout';
}
`
hook template : add_to_cart.post.tpl
{$id = "buy_now_{$product.product_id}"}
<button id="opener_{$id}" name="dispatch[buy_now.add..{$product.product_id}]" class=" vs-button buynow_btn_">Buy Now</button>
I'd consider putting your fn_redirect("checkout") code into an if/else statement to see what's happening with it.
If you have this code:
fn_add_product_to_cart($_REQUEST['product_data'], $cart, $auth);
Then surely you can put the redirection to the checkout page underneath it?
$redirect_url = "http://testcheckout.com?test=test"; //change this!
$errorMessage = "I should have redirected already....";
if (!empty($redirect_url)) {
//if it's not empty then it should redirect.
fn_redirect($redirect_url);
//Then put a die statement in here just to check it's not executing
//anything else and you can see if the redirect has a problem:
die(print_r($errorMessage, true ));
}
else {
//otherwise there is a problem with the supplied redirect url (empty)
die(print_r($redirect_url, true ));
}
I'd also take a look at this page which might help more:
http://forum.cs-cart.com/topic/6873-direct-buy-button/
Hope that helps!

Categories