Wordpress: issue on update_post_meta for checkbox metabox - wordpress

I have a metabox (one checkbox) , in posts, to check if a post will be featured..
My code:
function add_featured_post_checkbox() {
add_meta_box(
'custom_featured_meta',
'Featured post for Sidebar',
'featured_post_checkbox_callback',
'Post',
'side',
'high'
);
} add_action( 'add_meta_boxes', 'add_featured_post_checkbox' );
Callback function:
function featured_post_checkbox_callback( $post ) {
wp_nonce_field( 'custom_save_data' , 'custom_featured_nonce' );
$featured = get_post_meta($post->ID, '_featured_post', true);
echo "<label for='_featured_post'>".__('Is Featured? ', 'foobar')."</label>";
echo "<input type='checkbox' name='_featured_post' id='featured_post' value='1' " . checked(1, $featured) . " />";
}
Save function:
function custom_save_data( $post_id ) {
if( ! isset( $_POST['custom_featured_nonce'] ) ){
return;
}
if( ! wp_verify_nonce( $_POST['custom_featured_nonce'], 'custom_save_data') ) {
return;
}
if( defined('DOING_AUTOSAVE') && DOING_AUTOSAVE ){
return;
}
if( ! current_user_can( 'edit_post', $post_id ) ) {
return;
}
if( ! isset( $_POST['_featured_post'] ) ) {
return;
}
$my_data_featured = sanitize_text_field( $_POST['_featured_post'] );
update_post_meta( $post_id, '_featured_post', $my_data_featured );
} add_action( 'save_post', 'custom_save_data' );
This code works well only when I want to make a post featured..
For example if a post is not checked as featured and I select the choice then database updated perfect (with value 1 in post_meta) and the ckeckbox has the tick on box
But after, If I try to uncheck and save the post then the ckeckbox is again with the tick and nothing changed in database..
I try to find a solution for days on stackoverflow and general in web but I can't find.
Please help me
Thank you

When a checkbox is unchecked, $_POST will not contain the key _featured_post. Therefore, in your save callback, you need to change your strategy. You do not want to bail out if the key is not set. Rather, you either want to save a 0 or delete the post meta. Let's go with the later option.
function custom_save_data( $post_id ) {
if( ! isset( $_POST['custom_featured_nonce'] ) ){
return;
}
if( ! wp_verify_nonce( $_POST['custom_featured_nonce'], 'custom_save_data') ) {
return;
}
if( defined('DOING_AUTOSAVE') && DOING_AUTOSAVE ){
return;
}
if( ! current_user_can( 'edit_post', $post_id ) ) {
return;
}
if ( isset( $_POST['_featured_post'] ) ) {
update_post_meta( $post_id, '_featured_post', 1 );
} else {
delete_post_meta( $post_id, '_featured_post' );
}
}
Notice that you do not need to use sanitize_text_field(). Why? Because the value will only be a 1. That's it. Here we can hardcode that value.
Another Problem I Saw
Running your code I saw that upon being checked, the HTML for checked=checked is being rendered as text. Why? Because running the function checked() will echo it out to the browser unless you tell it not to. You'd have to check your code to:
checked(1, $featured, false);

That's happening because of return after the check if _featured_post is set in $_POST array. It's not set when you do not check the checkbox. Your approach here should be next
if (isset($_POST['_featured_post']))
{
update_post_meta($object_id, '_featured_post', 1); // can only be 1 when checked anyway
}
else
{
delete_post_meta($object_id, '_featured_post');
}

Related

How can i access woocommerce order variables inside shortcode?

I am adding a shortcode from wordpress to woocommerce email template.
do_shortcode('[sample_test name="additional_gift_msg"]);
Then i am using this to display the value in email. I am able to display value.
function th_email_shortcode_handler( $atts ) {
if ( ! empty( $atts['name'] ) ) {
$field = $atts['name'];
echo 'Found me';
}
}
add_shortcode('sample_test','th_email_shortcode_handler');
But i need $order or $order_id inside this handler function to take some value from post meta. How can i use those variables? The shortcode handler function is in functions.php
Also i tried the following but still $order_id is empty.
do_shortcode('[sample_test name="additional_gift_msg" order_id=' . $order->get_id() . ']');
Below code will do the trick.
function th_email_shortcode_handler( $atts ) {
if ( ! empty( $atts['name'] ) ) {
$field = $atts['name'];
echo 'Found me';
}
global $wp;
$order_id = absint( $wp->query_vars['order_id'] );
if ( empty($order_id) || $order_id == 0 )
return; // Exit;
return $order_id;
}
add_shortcode('sample_test','th_email_shortcode_handler');

WordPress Custom MD5 slug page not found

My "werknemers" post type need an MD5 generated slug to make them unique. In order to do that, I have added the following code:
function isValidMd5($md5 =''){
return preg_match('/^[a-f0-9]{32}$/', $md5);
}
function custom_unique_post_slug( $slug, $post_ID, $post_status, $post_type ) {
if(isValidMd5($slug)) { } else {
if ( 'werknemers' == $post_type ) {
$slug = md5( time() );
}
}
return $slug;
}
add_filter( 'wp_unique_post_slug', 'custom_unique_post_slug', 10, 4 );
Works perfectly however, the posts are now not accessible, giving a "Page not found" error. Changing the permalinks doesn't help and neither did resetting ".htaccess". I assume I need something specific to be placed in ".htaccess", but I don't know what. Any ideas?
Because I removed the post type slug, the post couldn't be found.
It actually had nothing to do with the MD5 generator.
To fix it, I had to apply the following code (in case anyone else has this problem)
function na_remove_slug( $post_link, $post, $leavename ) {
if ( 'werknemers' != $post->post_type || 'publish' != $post->post_status ) {
return $post_link;
}
$post_link = str_replace( '/' . $post->post_type . '/', '/', $post_link );
return $post_link;
}
add_filter( 'post_type_link', 'na_remove_slug', 10, 3 );
function na_parse_request( $query ) {
if ( ! $query->is_main_query() || 2 != count( $query->query ) || ! isset( $query->query['page'] ) ) {
return;
}
if ( ! empty( $query->query['name'] ) ) {
$query->set( 'post_type', array( 'post', 'werknemers', 'page' ) );
}
}
add_action( 'pre_get_posts', 'na_parse_request' );

Woocommerce shopping cart column

How add custom column to woocommerce shopping cart and then add info of some input from this column to order, checkout page and to email?
Actually i need add friends list from buddypress to each product row(price must depends on how many friends checked).
Here i found suggestion, but it`s partly helpfull WooCommerce: Add input field to every item in cart
wp community also keep silence
http://wordpress.org/support/topic/woocommerce-custom-column-in-cart?replies=1
what i do - its just add list of avalaible friends and no idea how can I save data on update cart or proceed.
if ( bp_has_members( 'user_id=' . bp_loggedin_user_id() ) ){
function ggUserFrom(){
$arrUsers = array();
while ( bp_members() ){
bp_the_member();
$arrUsers[ bp_get_member_user_nicename() ] = bp_get_member_user_nicename();
}
return $arrUsers;
}
echo "<div class='friends-holder'>";
foreach ( ggUserFrom() as $friend ){
echo '<p><input type="checkbox" name="cart['.$cart_item_key.'][friendsfromcart]" value="'.$friend.'">
<span>'.$friend.'</span></p>';
}
echo "</div>";
}
Im seek ANY info about this question.
Here, since user may choose multiple checkboxes, it may contain multiple values. Therefore, we have used "serialize" function.
for example,
add_filter( 'woocommerce_get_cart_item_from_session', 'wdm_get_cart_items_from_session', 1, 3 );
if(!function_exists('wdm_get_cart_items_from_session'))
{
function wdm_get_cart_items_from_session($item,$values,$key)
{
$item['custom_field_name'] = isset( $values['friendsfromcart'] )? serialize($values['friendsfromcart']) : '';
return $item;
}
}
While you are adding Order meta data, you can fetch individual values and add corresponding keys as follows,
add_action('woocommerce_add_order_item_meta','wdm_add_values_to_order_item_meta',1,2);
function wdm_add_values_to_order_item_meta($item_id, $values)
{
$user_custom_values = unserialize($values['friendsfromcart']);
if(count($user_custom_values) > 0)
{
foreach($user_custom_values as $single_value)
{
wc_add_order_item_meta($item_id,ucfirst($single_value),single_value);
}
}
}
since order meta will be sent in E - mail.
Thank for reply and - yes, variable isset in checkout page, but his empty in
var_dump($_POST)...
...[custom_field_name] =>
...
and ofc is empty in email.
Perhaps i incorrect send it ?
name="friendsfromcart"
or send values its a array and must send:
name="friendsfromcart[]"
or
name="[friendsfromcart]"
or need session key
name="cart['.$cart_item_key.'][friendsfromcart]" ?
It works, array in cart but something wrong with unserialize:
add_action( 'init', 'update_cart_action', 9);
function update_cart_action() {
global $woocommerce;
if ( ( ! empty( $_POST['update_cart'] ) || ! empty( $_POST['proceed'] ) ) && $woocommerce->verify_nonce('cart')) {
$cart_totals = isset( $_POST['cart'] ) ? $_POST['cart'] : '';
if ( sizeof( $woocommerce->cart->get_cart() ) > 0 ) {
foreach ( $woocommerce->cart->get_cart() as $cart_item_key => $values ) {
if ( isset( $cart_totals[ $cart_item_key ]['friendsfromcart'] ) ) {
$woocommerce->cart->cart_contents[ $cart_item_key ]['friendsfromcart'] = $cart_totals[ $cart_item_key ]['friendsfromcart'];
}
}
}
}
}
add_filter( 'woocommerce_get_cart_item_from_session', 'wdm_get_cart_items_from_session', 1, 3 );
function wdm_get_cart_items_from_session($item,$values,$key){
$item['friendsfromcart'] = isset( $values['friendsfromcart'] )? serialize($values['friendsfromcart']) : '';
return $item;
}
add_action('woocommerce_add_order_item_meta','wdm_add_values_to_order_item_meta',1,2);
function wdm_add_values_to_order_item_meta($item_id, $values){
$user_custom_values = unserialize($values['friendsfromcart']);
if(count($user_custom_values) > 0){
foreach($user_custom_values as $single_value){
wc_add_order_item_meta($item_id,ucfirst($single_value),single_value);
}
}
}

how update post meta when post type post edit and save

hi all here is my function
function save_urun_meta_price( $post_id ) {
$slug = 'urun';
if ( $slug != $_POST['post_type'] ) {
return;
}
// - Update the post's metadata.
if ( isset( $_REQUEST['urun_indirimli_fiyat'] ) ) {
$product_price = get_post_meta( $post_id, 'urun_fiyat', true );
$product_discount = of_get_option('urun_discount');
$yuzde = ($product_discount / 100)*$product_price;
$discounted = $product_price-$yuzde;
update_post_meta( $post_id, 'urun_indirimli_fiyat', $discounted );
}
}
add_action( 'save_post', 'save_urun_meta_price' );
add_action( 'edit_post', 'save_urun_meta_price' );
When user write some price into the urun_fiyat meta field i want to calculate this price with % discount field from the options framework panel.
Than i want to put new price another meta field urun_indirimli_fiyat..
What is wrong with my function ?
Thanks.
Try using the below code. I think the problem was with the product price variable. You were trying to get the value from post meta ( which does not exist )
Getting the value from $_POST variable will do the trick I guess.
function save_urun_meta_price( $post_id ) {
$slug = 'urun';
if ( $slug != $_POST['post_type'] ) {
return;
}
// - Update the post's metadata.
if ( isset( $_REQUEST['urun_indirimli_fiyat'] ) ) {
$product_price = $_POST['urun_fiyat'];
$product_discount = of_get_option('urun_discount');
$yuzde = ($product_discount / 100)*$product_price;
$discounted = $product_price-$yuzde;
update_post_meta( $post_id, 'urun_indirimli_fiyat', $discounted );
}
}
add_action( 'save_post', 'save_urun_meta_price' );
add_action( 'edit_post', 'save_urun_meta_price' );

wordpress show only media user has uploaded in wp_editor

I'm creating a wordpress site where the registered user has the ability to create his own post via wp_editor() on the frontend, but just one post.
Now I want to restrict the user to be able to only see his uploaded media. I use the following script in the functions.php, which works in the backend. So if a user goes to the media section in the backend he will only see his uploaded media.
But if the user goes to "insert media" pop-up on the frontend wp_editor he can still see the uploaded media from all the users.
function restricted_media_view( $wp_query ) {
if ( strpos( $_SERVER[ 'REQUEST_URI' ], '/wp-admin/upload.php' ) !== false
|| strpos( $_SERVER[ 'REQUEST_URI' ], '/wp-admin/edit.php' ) !== false ) {
if ( !current_user_can( 'level_5' ) ) {
global $current_user;
$wp_query->set( 'author', $current_user->id );
}
}
}
add_filter('parse_query', 'restricted_media_view' );
Do you have any idea hot to solve this annoyance? Thank you!
You might try this plugin: http://wordpress.org/extend/plugins/view-own-posts-media-only/
Alternatively try this:
add_action('pre_get_posts','ml_restrict_media_library');
function ml_restrict_media_library( $wp_query_obj ) {
global $current_user, $pagenow;
if( !is_a( $current_user, 'WP_User') )
return;
if( 'admin-ajax.php' != $pagenow || $_REQUEST['action'] != 'query-attachments' )
return;
if( !current_user_can('manage_media_library') )
$wp_query_obj->set('author', $current_user->ID );
return;
}
Source: http://wpsnipp.com/index.php/functions-php/restricting-users-to-view-only-media-library-items-they-upload/#comment-810649773
alternatively since WordPress 3.7
add_filter( 'ajax_query_attachments_args', "user_restrict_media_library" );
function user_restrict_media_library( $query ) {
global $current_user;
$query['author'] = $current_user->ID ;
return $query;
}
I use API/Filter Reference/ajax query attachments args for WP 4.3.1 and works
add_filter( 'ajax_query_attachments_args', 'show_current_user_attachments', 10, 1 );
function show_current_user_attachments( $query = array() ) {
$user_id = get_current_user_id();
if( $user_id ) {
$query['author'] = $user_id;
}
return $query;
}
just add on functions.php
or check this link WP Codex

Resources