Menu
  • HOME
  • TAGS

How to get the value instead of order_id with get_post_meta()

Tag: wordpress,woocommerce

I've had the following code to add a custom order field in the woocommerce checkout:

add_filter('woocommerce_checkout_fields', 'custom_override_checkout_fields');
function custom_override_checkout_fields($fields) {
   $fields['billing']['billing_reason_for_purchase'] = array(
       'label' => __('Reason for purchase', 'woocommerce'),
       'placeholder' => _x('Reason for purchase', 'placeholder', 'woocommerce'),
       'required' => false,
       'type' => 'select',
       'class' => array('form-row-first'),
       'options' => array(
           'option_1' => __('Personal', 'woocommerce'),
           'option_2' => __('Academic', 'woocommerce'),
           'option_3' => __('Small Business', 'woocommerce'),
           'option_4' => __('Large Organization', 'woocommerce')
       )
   );
   return $fields;
}

Then, followed by the below code to update the order meta with field value

add_action('woocommerce_checkout_update_order_meta', 'my_custom_checkout_field_update_order_meta');
function my_custom_checkout_field_update_order_meta($order_id) {
    if(!empty($_POST['billing_reason_for_purchase'])) {
        update_post_meta($order_id,'Reason for purchase',sanitize_text_field($_POST['billing_reason_for_purchase']));
    }
}

Next, display the field on the order edit page:

add_action('woocommerce_admin_order_data_after_billing_address', 'my_custom_checkout_field_display_admin_order_meta',10,1);
function my_custom_checkout_field_display_admin_order_meta($order){
    //echo '<p><strong>'.__('Reason for purchase').':<strong>'.get_post_meta($order->id, 'Reason for purchase',true).'</p>';
    echo '<p><strong>'.__('Reason for purchase').':<strong>'.get_post_meta(get_the_ID(), 'Reason for purchase',true).'</p>';
}

The problem I'm having is if I created a dummy order with choosing "academic" as the reason for purchase, I'd get "option_2" instead of "academic" in the order edit page.

Please help point me in the right direction.

Best How To :

It happens because the value of the selected option (and so of $_POST['billing_reason_for_purchase']) is actually the key of the array (in your example option_2) and not the text related. In fact this is the option tag created:

<option value="option_2">Academic</option>

You're saving only the key of your array.

So you need to retrieve the array of options even on the my_custom_checkout_field_display_admin_order_meta function to get the proper text.

You could copy the array in each function (but is not convenient to duplicate code), or put it in a global variable to be able to access it from anywhere (but then something else could change it), so instead you can use a function that returns the array:

function reasons_for_purchase () {
    return array(
       'option_1' => __('Personal', 'woocommerce'),
       'option_2' => __('Academic', 'woocommerce'),
       'option_3' => __('Small Business', 'woocommerce'),
       'option_4' => __('Large Organization', 'woocommerce')
   );
}

And then use it where you need it:

add_filter('woocommerce_checkout_fields','custom_override_checkout_fields');
function custom_override_checkout_fields($fields) {
   $fields['billing']['billing_reason_for_purchase'] = array(
       'label' => __('Reason for purchase', 'woocommerce'),
       'placeholder' => _x('Reason for purchase', 'placeholder', 'woocommerce'),
       'required' => false,
       'type' => 'select',
       'class' => array('form-row-first'),
       'options' => reasons_for_purchase()
   );
   return $fields;
}

add_action('woocommerce_admin_order_data_after_billing_address','my_custom_checkout_field_display_admin_order_meta',10,1);
function my_custom_checkout_field_display_admin_order_meta($order){
    $reasons = reasons_for_purchase();
    $reason  = get_post_meta($order->id, 'Reason for purchase', true);
    if( isset($reasons[$reason]) )
        echo '<p><strong>'.__('Reason for purchase').':</strong> '. $reasons[$reason] .'</p>';
}

woocommerce - make order notes required

wordpress,woocommerce

Change the action from 'woocommerce_checkout_process' to 'woocommerce_after_checkout_validation'. add_action('woocommerce_after_checkout_validation', 'my_custom_checkout_field_process'); function my_custom_checkout_field_process() { // Check if set, if its not set add an error. if ( ! $_POST['order_comments'] ) wc_add_notice( __( 'Please enter something into this new shiny field.' ), 'error' ); } ...

Can not link the author

wordpress

Try this : <a href="<?php echo get_author_posts_url( get_the_author_meta( 'ID' ) ); ?>"><?php the_author(); ?></a> ...

WooCommerce query quantity on product page

php,forms,woocommerce

Well I had to add an ajax function to the input field that would then update a hidden field in my form. Then when the Calculate button is pressed, I have access to the updated quantity.

How to add stripslashes to get_option()

regex,wordpress,wordpress-theming,sublimetext,stripslashes

Why not just create your own function in place of get_option() (but which takes advantage of it)? For example, you could define the following in functions.php: function my_stripslashes_function($option, $default = false) { return stripslashes( get_option($option, $default) ); } And then use Sublime to replace all instances of get_option with my_stripslashes_function...no...

Two language site in wordpress what i can do [on hold]

wordpress

You want to look into the WPML plugin. Also, any time you emit a string from your own PHP code, you'll want to use the PHP gettext() method, which makes the string localizeable and will allow you to localize it using WPML. You may also want to modify your WordPress...

Wordpress End If Statements

php,wordpress,woocommerce

<?php if ( sizeof( $woocommerce->cart->cart_contents ) == 0 ) { // The cart is empty } else { ?> <div class="header-cart-inner"> <a class="cart-contents" href="<?php echo WC()->cart->get_cart_url(); ?>" title="<?php _e( 'View your shopping cart' ); ?>"><?php echo sprintf (_n( '%d item', '%d items', WC()->cart->cart_contents_count ), WC()->cart->cart_contents_count ); ?> - <?php echo...

How To check Product Have Variation in woocommerce

php,wordpress,woocommerce,product

This should work: if( $product->is_type( 'simple' ) ){ // No variations to product } elseif( $product->is_type( 'variable' ) ){ // Product has variations } Example: If you will replace the file woocommerce --> single-product --> meta.php with this code, you will see it works. <?php /** * Single Product Meta...

login with username or email in wordpress

wordpress

Try this remove_filter( 'authenticate', 'wp_authenticate_username_password', 20, 3 ); add_filter( 'authenticate', 'tcb_authenticate_username_password', 20, 3 ); function tcb_authenticate_username_password( $user, $username, $password ) { if ( ! empty( $username ) && is_email( $username ) ) : if ( $user = get_user_by_email( $username ) $username = $user->user_login; endif; return wp_authenticate_username_password( null, $username, $password );...

How to fetch the page id and use it for an image name

php,wordpress

<?php $postid = get_the_ID() ?> <div class="splash"> <img src="<?php echo get_template_directory_uri(); ?>/images/<?php echo $postid;?>.jpg" /> </div> ...

CSS disable horizontaly scrolling - Wordpress [on hold]

php,html,css,wordpress,responsive-design

Try This: in your css @media only screen and (max-width: 479px){ .post-container{overflow: hidden;} } ...

How to call posts from PHP

php,wordpress,caching,cron,call

The easiest way to do it in PHP is to use file_get_contents() (fopen() also works), if the HTTP stream wrapper is enabled on your server: <?php $postUrls = array( 'http://my.site.here/post1', 'http://my.site.here/post2', 'http://my.site.here/post3', 'http://my.site.here/post4', 'http://my.site.here/post5', ); foreach ($postUrls as $url) { // Get the post as an user will do it...

Changing font-size of
  • on wordpress
  • css,wordpress,html-lists

    I think you have style inheritance from upper element, check it with dev. tools in browser. You can also try to set inline style for: <li style: "font-size: 22px;">Name 1</li> or add !important in your css file, like this: td > ul li { font-size: 22px !important;"> } ...

    Random opening tabs/pills - bootstrap 3

    javascript,css,wordpress,twitter-bootstrap-3

    use this code : var items = $('[data-toggle=pill]'); var i = parseInt(Math.floor(Math.random()*items.length)); $('#tabs a:eq(' + i + ') ').tab('show'); ...

    Creating complex queries with WP_Query in Wordpress

    wordpress,wp-query

    Your meta_query is completely wrong. All you parameters inside your arrays is invalid. post__not_in should be outside your meta_query meta_key, meta_value_num and meta_compare are all invalid paramters inside a meta_query. This parameters is used outside a meta_query You query should look something like this $args_projekte = array( 'post_type' => 'projekt',...

    ACF Multiple Map Markers

    wordpress,google-maps,google-maps-api-3,acf

    You can create a custom query and loop through all locations. var locations = [ <?php $args = array( 'post_type' => 'your_post_type', 'posts_per_page' => -1 ); $locations = new WP_Query($args); if($locations->have_posts()){ while($locations->have_posts()){ the_post(); $loc = get_field('location') ?> ['<?php echo get_the_title(); ?>', <?php echo $loc[0]; ?>, <?php echo $loc[1]; ?>], <?php...

    CSS mystery: why the extra height in my div's?

    javascript,css,wordpress

    Adam Maybe you just remove the blank <p></p> that you really don't need it. remove that <p></p> after the <img/>. And your layout will be good. Take a look(which <p></p> you should remove it.)...

    Wordpress log out using URL and redirect to specify page

    javascript,php,wordpress

    Try wp_logout() function use the funtion . if($_GET['logout'] == 1) { ob_start(); error_reporting(0); wp_logout(); $redirect = wp_logout_url(); wp_safe_redirect( $redirect ); } ...

    wp_schedule_event hook sheduled but not working

    php,wordpress,cron,wordpress-plugin,cron-task

    Try to move add_action outside of a function: function starthere(){ if (!wp_next_scheduled('my_hourly_event')) { wp_schedule_event( time(), 'hourly', 'my_hourly_event' ); } } add_action( 'my_hourly_event', 'Download_CSV_with_args' ); function Download_CSV_with_args() { wp_mail('[email protected]', 'Automatic email', 'Cron works!'); } ...

    Coding after Wordpress loop not showing

    php,wordpress

    I'm not sure what you're doing with this line... <?php if(!function_exists('dynamic_sidebar') || !dynamic_sidebar('commissions-intro')) ?> ...since you're not outputting anything. I'd either get rid of it, or fix it so that it's a valid conditional (with an endif;). It also looks like you're calling get_footer() twice......

    WooCommerce: How to display Category Name in single-product.php

    php,wordpress,woocommerce

    Try this : global $post; $terms = get_the_terms( $post->ID, 'product_cat' ); foreach ($terms as $term) { echo $term->name .' '; $thumbnail_id = get_woocommerce_term_meta( $term->term_id, 'thumbnail_id', true ); $image = wp_get_attachment_url( $thumbnail_id ); echo "'{$image}'"; } ...

    WordPress expanding grid with thumbnail

    javascript,css,wordpress,grid,expand

    Please have al look at your code: data-largesrc="images/1.jpg" Change this to your thumbnail url....

    Wordpress page can't continue due to this error

    php,css,wordpress,wordpress-plugin,wordpress-theming

    First error is a general server error (look for http 500 status code). It's very unspecific so it you could look up in your server logs fore more information. Second error occurs because the font url can't be reached - try it for you self and open the url of...

    Add second single product page in Woocommerce

    wordpress,woocommerce

    What I would do in this case is add a link that will reload the page with a custom query arg in the URL. Then you can filter the template via template_include to load a different template. Untested, so be careful of syntax typos. add_filter( 'template_include', 'so_30978278_single_product_alt' ); function so_30978278_single_product_alt(...

    How to exclude posts without featured images from custom post type WP_Query

    wordpress,wp-query

    Do a meta_query where you search for _thumbnail_id: $args_projekte = array( 'post_type' => 'projekt', 'posts_per_page' => 18, 'post__not_in' => array(191), 'orderby' => 'rand', 'meta_query' => array(array('key' => '_thumbnail_id')) ); $query_projekte = new WP_Query($args_projekte); The above verifies that the _thumbnail_id key exists....

    WooCommerce seems to only orderby date and not price

    php,ajax,wordpress,woocommerce

    Try this: $args = array( 'post_type' => 'product', 'posts_per_page' => 100, 'product_cat' => 'beast-balls', 'orderby' => 'meta_value_num', 'meta_key' => '_price', 'order' => 'asc' ); ...

    Excluding certain pages from being redirected to https

    wordpress,.htaccess,redirect,https,http-redirect

    Try using THE_REQUEST instead of REQUEST_URI: <IfModule mod_rewrite.c> RewriteEngine On # Go to https if not on careers RewriteCond %{SERVER_PORT} =80 RewriteCond %{THE_REQUEST} !/careers/[\s?] [NC] RewriteRule ^(.*)$ https://www.mywebsite.com/$1 [R,L] # Go to http if you are on careers RewriteCond %{SERVER_PORT} !=80 RewriteCond %{THE_REQUEST} /careers/[\s?] [NC] RewriteRule ^(.*)$ http://www.mywebsite.com/$1 [R,L] </IfModule>...

    Text-decoration/CSS causing text to move

    html,css,wordpress

    This is normal behaviour: Bold text is wider, thus repositioning the centered text around it. You could go for a fixed width on all links to prevent this: .main-navigation a { text-decoration: none; min-width: 6em; display: inline-block; } ...

    Woocommece login URL

    wordpress,woocommerce

    Try this code: function redirect_login_page(){ if(is_user_logged_in()){ return; } global $post; // Store for checking if this page equals wp-login.php // permalink to the custom login page $login_page = get_permalink( 'CUSTOM_LOGIN_PAGE_ID' ); if( has_shortcode($post->post_content, "woocommerce_my_account") ) { wp_redirect( $login_page ); exit(); } } add_action( 'template_redirect','redirect_login_page' ); ...

    How can I change link in my dropdown menu [closed]

    php,wordpress

    One solution is to load all the drop downs, and use Jquery to hide them. Next you could display then based on $(document).ready(function(){ $(".subdropdown").show(); }); if($(".dropdown1").val()==item-2){ $(".subdropdown").show(); } Hope this helps, this is just an example buy i hope you can expand from this ....

    need wordpress plugin to show 3 type of different kind of text, image and 2 buttons

    wordpress,plugins,wordpress-plugin

    Your question is not really understandable, but I think you are looking for this, it's a really good slider with a lot of functionality. Revolution Slider...

    Bxslider, Custom Fields & Wordpress

    php,wordpress,bxslider

    First, you can run array_filter() on the $ar array to remove false/ empty values. Next, you probably don't need this line $media_full = wp_get_attachment_image_src($image_id, "full", false); You could comment it out and it won't have any effect on the page....

    Wordpress Custom Post Type categroies

    wordpress,custom-post-type,advanced-custom-fields

    You can do that with Post Types UI, You will need to create a new taxonomy. Here is the screenshot explaining that https://s.w.org/plugins/custom-post-type-ui/screenshot-4.png?r=1180724 Just fill the text boxes with appropriate names, and check STORY under "Attach to Post Type" option. After that you will have custom taxonomy like "Story Category"...

    How to crop image from center using wp_image_editor

    wordpress,image,wordpress-plugin,resize-crop,wp-image-editor

    Try this code: $crop = array( 'center', 'center' ); resize( $max_w, $max_h, $crop); ...

    Run AJAX function on form submit button after javascript confirm() cancel

    javascript,jquery,ajax,wordpress,forms

    Dont use one(it will fire ajax submit or button click only once) , use here var IsBusy to check user is not repeatedly pressing the form submit, Try below code, var isBusy = false; //first time, busy state is false $('#publish').on('click', function (e) { if(isBusy == true) return ; //if...

    How to use curl return value in php script

    php,wordpress,curl,login

    custom_login.php is not returning any output. You can test this by going to example.com/custom_login.php?username=theUsername&password=thePassword. You can change this by simply echoing what you want to use: if ( is_wp_error( $user ) ) { echo 0; return; } else { echo 1; return; } Edit: As @unknown pointed out you generally...

    trouble using AFOAuth2manager to generate HTTPSOauthToken

    ios,oauth,woocommerce,afoauth2client

    try this NSURL *baseURL = [NSURL URLWithString:urlString]; AFOAuth2Manager *oAuthManager = [[AFOAuth2Manager alloc] initWithBaseURL:baseURL clientID: keyClientID secret:keyClientSecret]; [oAuthManager authenticateUsingOAuthWithURLString:@"/oauth/token" username:myUserName password:myPassword scope:@"email" success:^(AFOAuthCredential *credential) { NSLog(@"Token: %@",credential.accessToken); //Authorizing requests AFHTTPRequestOperationManager *manager = [[AFHTTPRequestOperationManager alloc] initWithBaseURL:baseURL];...

    BeautifulSoup: Parsing bad Wordpress HTML

    python,html,regex,wordpress,beautifulsoup

    At least, you can rely on the tag names and text, navigating the DOM tree horizontally - going sideways. These are all strong, p and span (with id attribute set) tags you are showing. For example, you can get the strong text and get the following sibling: >>> from bs4...

    String indices must be integers, new to python

    python,wordpress

    You're getting that error because "string indices must be integers, not str". formats += '\n' + x['name'] + " " + str(i) Here, you are accessing the 'name'th element of x, where 'name' is of course a string and x is a string too, since server.wp.getPostFormats obviously returns a list...

    If image is null from JSON, use another image - AngularJS

    json,angularjs,wordpress,angularjs-ng-repeat,wp-api

    You can use ng-style: <article ng-repeat="post in posts"> <div ng-style="post.featured_image.attachment_meta.sizes.medium.url === null ? {'background-image': 'url(/yourimage.jpg)' } : {'background-image': 'url('+post.featured_image.attachment_meta.sizes.medium.url+')' }"></div> </article> ...

    Wordpress Custom Post type archive display

    wordpress,templates,custom-post-type,advanced-custom-fields

    you are guessing right, first you need a page template where you are going to call your terms, but you need to call by his taxonomy, right?, To do that, you need to use the function get_terms( $taxonomies, $args );, and with the function get_term_link($term), you are going to obtain...

    Wordpress function to effect only one (custom) post type, and not every post

    wordpress,custom-post-type

    You're looking for get_post_type(): function custom_default_cover_image( $image = null, $args = null ) { global $post; if ( get_post_type() === 'job_listing' && ! $image ) { $image = array( 'http://website.com/image.jpg' ); } return $image; } add_filter( 'cover_image', 'custom_default_cover_image', 10, 2 ); ...

    Foundation and Wordpress blank spaces

    wordpress,zurb-foundation

    the reason this happens is that your tiles does not have equal height. you can use Foundation Equalizer to fix that. and leave the code has you have it. I would still change the large to small and have <article class="small-12 medium-6 large-4 columns"> to achieve better responsive results. Foundation...

    How to enable mod_rewrite on Apache 2.4?

    php,wordpress,apache,mod-rewrite,centos7

    i found the way to know if a module is loaded or not, here's to command to list the modules enabled: apachectl -M | sort It will list all enabled modules alphabetically. Wordpress has an .htaccess but default where it enables Rewrite_Mod for its use: # BEGIN WordPress <IfModule mod_rewrite.c>...