如何使用AJAX调用更新_post_meta()或添加_post_meta()

时间:2015-09-04 作者:Eduardo Sánchez Hidalgo Urías

我有一个叫albums的CPT。CPT有一些自定义字段,我希望这些字段在帖子编辑器中为空,这样编辑帖子的人可以在编辑器中为相册添加曲目,然后这些字段再次变为空以添加更多曲目。我的解决方案是让用户在三个字段中键入:歌曲的解释器、音频文件的url和歌曲的名称。填写完字段后,用户可以单击按钮触发AJAX调用,该调用将字段的值发送到函数中的函数。php文件,目的是将这些字段的值存储在post meta中。几乎所有操作都正常,但字段的值没有存储在指定的元键中:

我一直在努力做到这一点,但我不知道为什么这不起作用。这是我的代码:

这是自定义字段所在的函数:

function topchart_albums_cpt_cf($post){

    var_dump(get_post_meta($post->ID, "track-info", true)); //It prints string(0) ""

    //All fields appear correctly on the editor of the CPT

    //$album_artist = get_post_meta( $post->ID, \'album-artist\', true ); Not needed in this case
    echo \'<label for="album-artist">\';
    _e( \'Intérprete del track\', \'topchart\' );
    echo \'</label> \';
    echo \'<input type="text" id="album-artist" name="album-artist"  size="50" /></br>\';

    //$add_new_track = get_post_meta( $post->ID, \'add-new-track\', true ); Not needed in this case
    echo \'<label for="add-new-track">\';
    _e( \'Añadir un nuevo track\', \'topchart\' );
    echo \'</label> \';
    echo \'<input type="text" id="add-new-track" name="add-new-track"  size="80" />\';

    //$track_url = get_post_meta( $post->ID, \'track-url\', true ); Not needed in this case
    echo \'<label for="track-url">\';
    _e( \'Url del archivo\', \'topchart\' );
    echo \'</label> \';
    echo \'<input type="url" id="track-url" name="track-url"  size="100" />\';

    echo \'<button id="add-track">Añadir track</button></br>\';

    $erase_track = get_post_meta( $post->ID, \'erase-track\', true );
    echo \'<label for="erase-track">\';
    _e( \'Borrar un track \', \'topchart\' );
    echo \'</label> \';
    echo \'<select id="erase-track" name="erase-track">\';
    if(is_array($erase_track)) { 
        foreach($erase_track as $track ) {
    ?>
            <option value="<?php echo $track; ?>"><?php echo $track; ?></option>

    <?php         
        } 
    } else {
        echo \'No se han incluido tracks (todavía) en este album\';  
    }
    echo \'</select>\';
    echo \'<button id="borrar-track">Borrar track</button>\';

}
这在JS文件中:

jQuery(document).ready(function($){
    $("#add-track").click(function(){
        var track_artist = $("#album-artist").val();
        var track_name = $("#add-new-track").val();
        var track_url = $("#track-url").val();
        if ( track_name  !== "") {
            $.ajax({
                url : track.ajax_url,
                type : \'post\',
                data : {
                action: \'save_track_data\',
                track_artist : track_artist,
                track_name : track_name, 
                track_url : track_url                
                },
                success: function(response) {
                    alert("ok"); /*Alert triggers when clicking on the button #add-track in the CPT */
                }

            }); 
        } else {
            alert("Tienes que introducir el título del track"); 
        }
    });
});
处理Ajax调用函数的函数。php

function add_album_cpt_edit_script($hook) {
    global $post;

    if ( $hook == \'post-new.php\' || $hook == \'post.php\' ) {
        if ( \'topchart_album\' === $post->post_type ) {     
            wp_enqueue_script(  \'album-edit-script\', get_stylesheet_directory_uri().\'/js/album-edit-script.js\', array(\'jquery\'), \'1.0\', true );
            wp_localize_script( \'album-edit-script\', \'track\', array(\'ajax_url\' => admin_url( \'admin-ajax.php\' )));
        }
    }
}
add_action( \'admin_enqueue_scripts\', \'add_album_cpt_edit_script\', 10, 1 );
简化了功能,但即使这样也不起作用。我用update\\u post\\u meta()和add\\u post\\u meta()尝试了几种方法,但都没有存储信息。我遗漏了一些东西,但不知道是什么,可能是一些WordPress AJAX API规则或其他东西。

add_action( \'wp_ajax_save_track_data\', \'save_track_data\' );
function save_track_data() {
   global $post;
   $track_info = array ($_POST[\'track_name\'] => array ( \'artist\' => $_POST[\'track_artist\'], \'url\' => $_POST[\'track_url\']));
   add_post_meta($post->ID, \'track-info\', $track_info);
   wp_die();
}
希望有人能帮我。抱歉,如果我的代码很混乱,我一直在尝试triyng以使其正常工作。

1 个回复
最合适的回答,由SO网友:Eduardo Sánchez Hidalgo Urías 整理而成

我刚刚解决了这个问题。显然,当您在WordPress或administrator中调用AJAX来发布编辑页面时,情况会有所不同,您无法获得正在编辑的帖子的ID。我读过很多类似的问题,但没有一个解决方案对我有效,但它们给了我提示。

这就是我为解决这个问题所做的:

JS文件中的AJAX代码:

$("#add-track").click(function(){        
        var track_artist = $("#album-artist").val();
        var track_name = $("#add-new-track").val();
        var track_url = $("#track-url").val();        
        if ( track_name  !== "") {
            $.ajax({
                url : track.ajax_url,
                type : \'post\',
                data : {
                action: \'save_track_data\',
                track_artist : track_artist,
                track_name : track_name, 
                track_url : track_url,
                post_url : window.location.href, //get the complete url of the post editor, wich includes post id
                execute: "add track" //This is not necessary in this code, I\'am using it to know when to erase or add a track 
                },
                success: function(response) {

                }

            }); 
        } else {
            alert("Tienes que introducir el título del track");
        }
    });
函数中的代码。php

add_action( \'wp_ajax_save_track_data\', \'save_track_data\' );
function save_track_data() {    
    $post_url = $_POST[\'post_url\']; //The post edit page\'s url string from AJAX call
    $id_start = strpos($post_url, \'post=\') + 5; //Get the position where the id number starts in the url string
    $id_end = strpos($post_url, \'&\'); //Get the position where the id number of the post ends
    $post_id = substr($post_url, $id_start, ($id_end - $id_start)); //Extract the number from the urs string
    $tracks_info = get_post_meta($post_id, \'tracks-info\', true); //Get the array with the tracks information          
    $track_name = $_POST[\'track_name\'];
    $track_artist = $_POST[\'track_artist\'];
    $track_url = $_POST[\'track_url\'];
    $track_partial = array("artist" => $track_artist, "url" => $track_url);    
    if($tracks_info === \'\') { //If the meta key has no information
        $track_info[$track_name] = $track_partial; // assign the first array element
         add_post_meta($post_id, \'tracks-info\', $track_info); //Save the track info in post meta
    } else { //If the post meta have at least one track
         $tracks_info[$track_name] = $track_partial; //assign a new element to the array of tracks
         update_post_meta($post_id, \'tracks-info\', $tracks_info); //Update the post meta
    }    
    wp_die();
}
我希望这能帮助有同样问题的人。

相关推荐

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

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