使用AJAX更新用户元数据

时间:2016-01-30 作者:Al Rosado

我想使用ajax表单在前面编辑用户元,这是我的:

表单具有用户ID:

<form id="<?php echo $current_user->ID; ?>"...
这是脚本::

<script>
    jQuery( document ).ready( function() {
        jQuery( \'#<?php echo $current_user->ID; ?>\' ).submit( function( e ) {
            e.preventDefault();
            jQuery.ajax( {
                type: "POST",
                url: ajaxurl,
                data: "action=updateUserFront&id=" + <?php echo $post->ID?>,  
                success: function() {
                    alert( \'funcionó\' );
                }
            } );
        } );
    } );
</script>
这就是我的functions.php 文件

function my_ajaxurl() {
    $html  = \'<script type="text/javascript">\';
    $html .= \'var ajaxurl = "\' . admin_url( \'admin-ajax.php\' ) . \'"\';
    $html .= \'</script>\';
    echo $html;
}
add_action( \'wp_head\', \'my_ajaxurl\' );

function updateUserFront_ajax() {
    $user_id    = get_current_user_id();
    $newVal     = \'test\';
    $userUrl    = get_user_meta( $user_id, \'url\', true ); 

    update_user_meta($post_id,\'url\',$newVal);

    die( $newVal );
}
add_action( \'wp_ajax_updateUserFront\', \'updateUserFront_ajax\' );

1 个回复
最合适的回答,由SO网友:Howdy_McGee 整理而成

Alright, there\'s a few things that isn\'t standardized WordPress so I\'ve put together a minimal script which I\'ll explain piece by piece. Hopefully clear things up for you by the time you get to the end.

HTML Form

Below is a very simple HTML form. We\'re going to use javascript to listen for submission and stop it from actually refreshing the page but that will be later.

<form id="um_form" method="POST">
        <p>
            <label for="um_key">
                User Meta Value:&nbsp;&nbsp;
                <input type="text" name="um_key" id="um_key" value="" style="width:100%;" />
            </label>
            <input type="submit" value="Submit" />
        </p>
    </form>

We\'re $_POSTing the form but you could also $_GET the form if you\'d like. In this situation I don\'t think it matters.

Enqueue our scripts

So WordPress has a hook which you can use to enqueue styles and scripts in their proper places ( header or footer ) called wp_enqueue_scripts. Using this we can localize our script and pass a variable ( or two if you\'d like ) to our javascript, specifically the ajax_url. Doing that looks something like this:

/**
 * Enqueue our Scripts and Styles Properly
 */
function theme_enqueue() {

    $theme_url  = get_template_directory_uri();     // Used to keep our Template Directory URL
    $ajax_url   = admin_url( \'admin-ajax.php\' );        // Localized AJAX URL

    // Register Our Script for Localization
    wp_register_script(
        \'um-modifications\',                             // Our Custom Handle
        "{$theme_url}/scripts/um-modifications.js",  // Script URL, this script is located for me in `theme-name/scripts/um-modifications.js`
        array( \'jquery\' ),                              // Dependant Array
        \'1.0\',                                          // Script Version ( Arbitrary )
        true                                            // Enqueue in Footer
    );

    // Localize Our Script so we can use `ajax_url`
    wp_localize_script(
        \'um-modifications\',
        \'ajax_url\',
        $ajax_url
    );

    // Finally enqueue our script
    wp_enqueue_script( \'um-modifications\' );
}
add_action( \'wp_enqueue_scripts\', \'theme_enqueue\' );

The above code is heavily commented so please read through the code comments if something doesn\'t make sense. This would go into your functions.php file.

Our Javascript / JQuery

Since I wanted to keep it simple, In this example we\'re only processing one meta_value but you could just as easily passed multiple meta_values to the data object, referencing them in your PHP by $_POST index which we\'ll see later. The below lies in a scripts directory, theme-name/scripts/um-modifications.js and is also heavily commented:

// Declare our JQuery Alias
jQuery( \'document\' ).ready( function( $ ) {

    // Form submission listener
    $( \'#um_form\' ).submit( function() {

        // Grab our post meta value
        var um_val = $( \'#um_form #um_key\' ).val();

        // Do very simple value validation
        if( $( \'#um_form #um_key\' ).val().length ) {
            $.ajax( {
                url : ajax_url,                 // Use our localized variable that holds the AJAX URL
                type: \'POST\',                   // Declare our ajax submission method ( GET or POST )
                data: {                         // This is our data object
                    action  : \'um_cb\',          // AJAX POST Action
                    \'first_name\': um_val,       // Replace `um_key` with your user_meta key name
                }
            } )
            .success( function( results ) {
                console.log( \'User Meta Updated!\' );
            } )
            .fail( function( data ) {
                console.log( data.responseText );
                console.log( \'Request failed: \' + data.statusText );
            } );

        } else {
            // Show user error message.
        }

        return false;   // Stop our form from submitting
    } );
} );

AJAX PHP Callback / Handler / Action

Finally, The actual processing! Important things to note are the hooks at the end of this function:

Here we can get the current user and update their user_meta or even the User Object if we wanted to.

/**
 * AJAX Callback
 * Always Echos and Exits
 */
function um_modifications_callback() {

    // Ensure we have the data we need to continue
    if( ! isset( $_POST ) || empty( $_POST ) || ! is_user_logged_in() ) {

        // If we don\'t - return custom error message and exit
        header( \'HTTP/1.1 400 Empty POST Values\' );
        echo \'Could Not Verify POST Values.\';
        exit;
    }

    $user_id        = get_current_user_id();                            // Get our current user ID
    $um_val         = sanitize_text_field( $_POST[\'first_name\'] );      // Sanitize our user meta value
    $um_user_email  = sanitize_text_field( $_POST[\'user_email\'] );      // Sanitize our user email field

    update_user_meta( $user_id, \'first_name\', $um_val );                // Update our user meta
    wp_update_user( array(
        \'ID\'            => $user_id,
        \'user_email\'    => $um_user_email,
    ) );

    exit;
}
add_action( \'wp_ajax_nopriv_um_cb\', \'um_modifications_callback\' );
add_action( \'wp_ajax_um_cb\', \'um_modifications_callback\' );

Hopefully this makes it easier for you to understand and visualize. Should you have any questions, comment below!

相关推荐

尝试在WordPress中实现AJAX注释,遇到WP错误

我试图在WordPress中为我的评论实现Ajax,使用this tutorial. 但我在将教程中的代码集成到自己的预构建主题时遇到了问题。问题是,我要么得到一个WP错误“检测到重复注释;看来你已经说过了!”或标准500错误。以下是我得到的:下面是我对ajax的评论。js文件如下所示: * Let\'s begin with validation functions */ jQuery.extend(jQuery.fn, { /* * check i