我正在尝试更新投票插件的post meta。特别是它调用update_post_meta()
根据ajax请求。代码如下:
function add_settings_menu() {
add_options_page(\'Contested Settings\', \'Contested Settings\', 1, \'manage_options\', \'contested_settings\');
}
function contested_settings() {
include("contested_admin_settings.php");
}
function get_posts_votes($post) {
$votes = get_post_meta($post, \'votes\', true );
return $votes;
}
function add_contested_voting($category, $post) {
if (in_category($category, $post)) {
wp_enqueue_script(\'jquery\');
$post = get_post($post);
$post_id = (int)$post->ID;
add_post_meta($post_id, \'votes\', \'0\', true);
/*if($votes == \'\') {
update_post_meta($post, \'votes\', \'0\');
$votes = get_post_meta( $post, \'votes\', true );
}*/
?>
<form id=\'voting-form\'>
<strong>Vote now!</strong><br />
<label id=\'votes\'><?php echo get_posts_votes($post); ?></label>
<input type=\'button\' id=\'vote_up\' value=\'+1\' />
</form>
<script>
$(function() {
ajaxurl = "<?php echo admin_url(\'admin-ajax.php\'); ?>";
$("#vote_up").click(function() {
var data = {
action: \'contested\',
votes: \'<?php echo $votes; ?>\',
post: \'<?php echo $post_id; ?>\'
};
$.post(ajaxurl, data, function(data) {
$("#voting-form").html(data);
});
});
});
</script>
<?
}
}
function ajax_posted() {
$votes_plus = $_POST[\'votes\']+1;
$id = $_POST[\'post\'];
if (update_post_meta($id, \'votes\', $votes_plus)) {
$votes_ret = get_post_meta($id, \'votes\', true);
echo "Thanks for voting! ".$votes_ret." vote.";
} else {
echo "Voting failed!";
}
die();
}
add_action(\'admin_menu\', \'add_settings_menu\');
add_action(\'wp_ajax_contested\', \'ajax_posted\');
我真的不确定这是怎么回事。有什么想法吗?
SO网友:wuz
我想出来了。在update\\u post\\u meta中使用“$id”时出错。
我更改了以下内容:
function ajax_posted() {
$votes_plus = $_POST[\'votes\']+1;
$id = $_POST[\'post\'];
if (update_post_meta($id, \'votes\', $votes_plus)) {
$votes_ret = get_post_meta($id, \'votes\', true);
echo "Thanks for voting! ".$votes_ret." vote.";
} else {
echo "Voting failed!";
}
die();
}
对此:
function ajax_posted() {
$id = intval($_POST[\'post\']);
$post = get_post($id);
$votes = get_posts_votes($post);
$votes_plus = $votes+1;
if (update_post_meta($post, \'votes\', $votes_plus)) {
$votes_ret = get_post_meta($id, \'votes\', true);
echo "Thanks for voting! ".$votes_ret." vote.";
} else {
echo "Voting failed!";
}
die();
}