How to execute a wordpress function inside custom PHP file

Inside my active theme there is a user.php which serves this kind of url http://mysite.com/user/username. Inside user.php I echo a script tag with the following content

$.ajax({ url: "' . get_theme_root_uri() . '/fray/userslogan.php",
                    data: {"id": ' . $profile['id'] . ', "slogan": el.innerHTML},
                    type: "post",
                    success: function(status) { alert(status); }                    
                });

I created a file userslogan.php and added it at the same level as user.php. Inside this file now all I want to do is

Read More
<?php
update_user_meta( $_POST['id'], 'slogan', $_POST['slogan'] );
echo 1;
?>

but I get errors that functions that I call are undefined. So if I include some file that defines the update_user_meta function, then I will get another similar error and so on. What is the right way of executing code like this?

Related posts

Leave a Reply

3 comments

  1. You need to include wp-load.php to get access to the wordpress function in custom files.

    Suggestion: Don’t include wp-load, please. Use ajax in wordpress in proper way. You can refer this article.

    From above article

    Why this is wrong

    1. You don’t have the first clue where wp-load.php actually is. Both the plugin directory and the wp-content directory can be moved around
      in the installation. ALL the WordPress files could be moved about in
      this manner, are you going to search around for them?
    2. You’ve instantly doubled the load on that server. WordPress and the PHP processing of it all now have to get loaded twice for every page
      load. Once to produce the page, and then again to produce your
      generated javascript.
    3. You’re generating javascript on the fly. That’s simply crap for caching and speed and such.
  2. Try WP AJAX

    1) http://codex.wordpress.org/Plugin_API/Action_Reference/wp_ajax_(action)

    2) http://codex.wordpress.org/AJAX_in_Plugins

    add_action( 'admin_footer', 'my_action_javascript' );
    
    function my_action_javascript() {
        ?>
        <script type="text/javascript" >
        jQuery(document).ready(function($) {
    
        var data = {
        action: 'my_action',
        whatever: 1234
        };
    
        // since 2.8 ajaxurl is always defined in the admin header and points to admin-ajax.php
            $.post(ajaxurl, data, function(response) {
        alert('Got this from the server: ' + response);
        });
      });
      </script>
      <?php
      }
    
      add_action('wp_ajax_my_action', 'my_action_callback');
    
       function my_action_callback() {
    global $wpdb; // this is how you get access to the database
    
    $whatever = intval( $_POST['whatever'] );
    
    $whatever += 10;
    
        echo $whatever;
    
    die(); // this is required to return a proper result
       }