1

I have a function that is currently operating correctly.

It is currently located in the 'My Account' section and is working as it is supposed to. Changing user meta info in the back-end fro a drop-down menu located on the front-end.

The issue is I would like this drop-down to be called from anywhere I like, functioning correctly. For example, it is working in 'My Account' but I also want this on the homepage and a couple of other places.

Code that is working in 'My Account' :

// -------------------------------------------
// CHANGE DEFAULT CITY ON FRONTEND DASHBOARD

function location_select_account() { ?>
    <script>
        jQuery(document).ready( function(){
            jQuery('#location_select').select2();
        });
    </script> <?php

    global $current_user;
        // Get New User Meta
        if(isset($_POST['location_select'])) {
            $locationposter = $_POST['location_select'];
            // Update/Create User Meta
            update_user_meta( $current_user->ID, 'location_select', $locationposter);
            }    
        else {
            // Get User Meta
            $locationposter = get_user_meta( $current_user->ID, 'location_select', true);
        }
    ?>                              
                                    <form method="POST">
                                        <?php 
                                        //get dropdown saved value
                                        $selectedinfo = get_the_author_meta( 'location_select', $current_user->ID );
                                        $selected = isset( $selectedinfo['location_select'] ) ? esc_attr( $selectedinfo['location_select'][0] ) :'';
                                        ?>
                                        <select name="location_select" id="location_select" style="width:13em;" onchange="this.form.submit()">
                                            <option value="all_of_canada" <?php echo ($selectedinfo == "all_of_canada")?  'selected="all_of_canada"' : '' ?>>All of Canada</option>
                                            <option value="abbotsford" <?php echo ($selectedinfo == "abbotsford")?  'selected="abbotsford"' : '' ?>>Abbotsford</option>
                                            <option value="barrie" <?php echo ($selectedinfo == "barrie")?  'selected="barrie"' : '' ?>>Barrie</option>
                                            <option value="brantford" <?php echo ($selectedinfo == "brantford")?  'selected="brantford"' : '' ?>>Brantford</option>
                                        </select>                                       
                                    </form>
    <?php
    }

// Add Hook

add_action( 'location_select_account_init' , 'location_select_account' );
add_action( 'woocommerce_account_content' , 'location_select_account_init' , 5 );

function location_select_account_init() {
    do_action('location_select_account_init');
}

1 Answer 1

1

If you want to use that function everywhere, you need to be sure that:

  • $current_user is always defined as a WP_User object,
  • $current_user->ID is different from 0 (zero) - only for logged in users,
  • jQuery select2() function (plugin) exist, avoiding JS errors on some other pages (where Select 2 is not enabled). See: How can I check if a jQuery plugin is loaded?.

I have also make some changes in your code, simplifying and compacting.

Now you can use this function in all available action hooks.

You can also use it in any template or php files with this simple line:

location_select_account();

Your revisited code:

add_action( 'woocommerce_account_content' , 'location_select_account' , 5 );
function location_select_account() {
    global $current_user;

    if( ! is_a( $current_user, 'WP_User' ) )
        $current_user = wp_get_current_user();

    if( $current_user->ID === 0 ) {
        return; // Exit
    }

    // Get the posted data and update user meta data
    if( isset($_POST['location_select']) ) {
        $locationposter = $_POST['location_select'];
        // Update/Create User Meta
        update_user_meta( $current_user->ID, 'location_select', $locationposter );
    }
    ?>
    <form method="POST">
        <?php
        //get dropdown saved value
        $selectedinfo = $current_user->location_select;
        ?>
        <select name="location_select" id="location_select" style="width:13em;" onchange="this.form.submit()">
            <option value="all_of_canada" <?php echo ($selectedinfo == "all_of_canada")?  'selected="all_of_canada"' : '' ?>>All of Canada</option>
            <option value="abbotsford" <?php echo ($selectedinfo == "abbotsford")?  'selected="abbotsford"' : '' ?>>Abbotsford</option>
            <option value="barrie" <?php echo ($selectedinfo == "barrie")?  'selected="barrie"' : '' ?>>Barrie</option>
            <option value="brantford" <?php echo ($selectedinfo == "brantford")?  'selected="brantford"' : '' ?>>Brantford</option>
        </select>
    </form>
    <script>
    jQuery( function($){
        // Check if select2 jQuery plugin is loaded
        if (typeof $().select2 !== 'undefined') {
            $('#location_select').select2();
        };
    });
    </script>
    <?php
}

Code goes in functions.php file of the active child theme (or active theme), or a plugin file. Tested and works.


Bonus - Using the function as a shortcode

add_shortcode( 'location_select', 'location_select_shortcode' );
function location_select_shortcode(){
    ob_start(); // Start buffering

    location_select_account();

    return ob_get_clean();
}

Code goes in functions.php file of the active child theme (or active theme), or a plugin file. Tested and works.

USAGE:

1) In the Wordpress editor:

[location_select]

2 In a php file:

echo do_shortcode( "[location_select]" );
4
  • This is awesome, thank you so much. Solved it perfectly. One issue - my select2 was working previously but is not now. Any idea of the cause? Commented Aug 20, 2019 at 22:23
  • @BruceBrain21 Sorry I have make a little mistake for select2: I have updated the code and it works now as it should. Commented Aug 20, 2019 at 22:47
  • Thanks for that. It still isn't being recognized though, and I'm receiving no errors in my console... Funny enough it is working in my admin area backend with: 'jQuery(document).ready( function(){ jQuery('#location_select').select2(); });' And I have had it working on the frontend before as well... no idea. Commented Aug 20, 2019 at 23:05
  • @BruceBrain21 jQuery( function(){ and jQuery(document).ready( function(){ are the same thing. The $ function argument in jQuery( function($){ is the shortened alias for jQuery that you can use inside the function like $('div').show() instead of jQuery('div').show() for example… Commented Aug 20, 2019 at 23:37

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.