Calling a function from anywhere, used in different places

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]" );