get_current_user_id() постоянно выдает 0
У меня есть сайт на Wordpress и файл add_events.php со следующим содержимым. Под аккаунтом админа wordpress открываю http://localhost/wordpress/add_events.php выводит 0. И в БД тоже вводит 0 при ajax запросе к add_events.php
<?php
$title = $_POST['title'];
$start = $_POST['start'];
try {
require "db_config.php";
require "../wp-includes/user.php";
} catch(Exception $e) {
exit('Unable to connect to database.');
}
echo get_current_user_id(); //debug
$cur_user_id = get_current_user_id();
$sql = "INSERT INTO events (title, start, cur_user_id) VALUES (:title, :start, :cur_user_id)";
$q = $cal_db->prepare($sql);
$q->execute(array(':title'=>$title, ':start'=>$start, ':cur_user_id'=>$cur_user_id));
?>
Я пытаюсь получить id авторизованного пользователя, но всегда возвращается 0
Kак правильно использовать get_current_user_id() ?
Ответы (1 шт):
Автор решения: Leprush
→ Ссылка
Я написал плагин по руководству, все сработало, спасибо.
Нужно было написать свой мини-плагин, потом активировать в wordpress.
<?php
/**
* Plugin name: добавление событий через AJAX
*/
add_action('wp_ajax_event', 'add_event');
function add_event() {
$title = $_POST['title'];
$start = $_POST['start'];
$cur_user_id = get_current_user_id();
try {
require "db_config.php";
} catch(Exception $e) {
exit('Unable to connect to database.');
}
$sql = "INSERT INTO events (title, start, cur_user_id) VALUES (:title, :start, :cur_user_id)";
$q = $cal_db->prepare($sql);
$q->execute(array(':title'=>$title, ':start'=>$start, ':cur_user_id'=>$cur_user_id));
wp_die();
}
?>
//Ну и ajax запрос из html файла
$.ajax({ //get user id
url: 'http://localhost/wordpress/wp-admin/admin-ajax.php?action=event',
data: {
title: event_desc,
start: start
},
type: "POST",
success: function(json) {
calendar.refetchEvents();
}
});