我尝试在单击按钮的自定义帖子类型上显示用户。我创建了这个函数。
这是添加按钮的代码
<?php
// Display the post content
if (have_posts()) {
while (have_posts()) {
the_post();
the_content();
// Add a form with a button for tracking user clicks
if (is_user_logged_in()) {
$nonce = wp_create_nonce('track_button_click');
?>
<form method="post">
<input type="hidden" name="track_button_click_nonce" value="<?php echo esc_attr($nonce); ?>">
<button type="submit" name="track_button_click">Click me!</button>
</form>
<?php
}
}
}
?>
这是处理用户单击按钮时表单提交的函数。
function handle_button_click() {
if (isset($_POST['track_button_click'])) {
// Verify nonce
if (isset($_POST['track_button_click_nonce']) && wp_verify_nonce($_POST['track_button_click_nonce'], 'track_button_click')) {
// Get current user ID
$user_id = get_current_user_id();
// Add user ID to a secure user meta key (custom database table or secure storage method)
$clicked_users = get_option('clicked_users', array());
if (!in_array($user_id, $clicked_users)) {
$clicked_users[] = $user_id;
update_option('clicked_users', $clicked_users);
}
}
}
}
add_action('init', 'handle_button_click');
这是显示用户列表的功能。
function display_clicked_users() {
$clicked_users = get_option('clicked_users', array());
if (!empty($clicked_users)) {
echo '<h2>Users who clicked the button:</h2>';
echo '<ul>';
foreach ($clicked_users as $user_id) {
$user_info = get_userdata($user_id);
if ($user_info) {
echo '<li>' . esc_html($user_info->display_name) . '</li>';
}
}
echo '</ul>';
} else {
echo '<p>No users have clicked the button yet.</p>';
}
}
模板标签。
display_clicked_users();
如果我实现这些代码行,乍一看似乎可以工作。但最终单击按钮时什么也没有发生。包含所有用户以及他们单击按钮的日期和时间的列表不会出现。
数据是否存储在数据库中?您可以通过使用 error_log('Button was clicked'); 之类的日志跟踪每个操作来调试代码
然后你就可以看到你的代码卡在哪里了。不要忘记启用 wp_debug!