我正在开发我的网站,我想添加两件事。
当用户点击链接时,他/她的用户 ID 和当前帖子 ID 就会被获取并插入到数据库中,并且计数器会增加。
假设用户登录并打开帖子,链接如下:我感兴趣 (0) 这里 0 是唯一登录人数的计数值谁点击了此链接。第二个链接将类似于:我想工作 (0) 此处适用相同的逻辑。**
最后需要显示对特定帖子感兴趣和工作的人员数量(自定义帖子类型:工作)。
有一个表,其中每一行都有帖子的标题(工作)我可以通过 WordPress native 函数获取帖子的值,然后将其与数据库中的帖子 id 进行比较,然后检索其状态(noofinterested)和 noofworking),然后使用 jQuery 通过 AJAX 注入(inject)。
我为此目的创建了表格,但遇到了困难:
- 通过 jquery 获取帖子 ID 和用户 ID,由于某些原因,我无法修改当前的自定义帖子模板,因为我正在使用 wp 作业管理器来处理自定义职位帖子。
- 我需要的只是找到一种方法让独特的人依赖特定的帖子
到目前为止,我想到了一种方法,通过 jQuery 附加两个链接,并通过 jQuery 添加单击功能到链接,并在其中添加 ajax 来获取数据并输入到我已编码的 PHP 文件和该 PHP 文件中它将通过发布值插入表中,然后返回响应。在第二页中,我想在表行中插入状态,我将使用 jQuery。
这是我目前手头上的。
PHP
<?php
global wpdb;
if(isset($_POST['if_intested'])&&isset($_POST['if_working'])&&isset($_POST['user_id'])&&isset($_POST['post_id'])){
if($wpdb->insert('wp_custom_jobmanager', array ( "post_id" => $_POST['post_id'], "user_id" => $_POST['user_id'], "if_interested" => $_POST['if_interested'] , "if_working" => $_POST['if_working']))){
return "Thanks your feedback has been saved";
}else {
return "Sorry something went wrong Please Try Logging in again and try again.";
}
}
?>
jQuery
jQuery("#link").click(function(){
if(jQuery("body").hasClass("single")){
jQuery('<p id="stauts-interested">interested 24</p><br><p id="status-work">Working 43</p>').appendTo(".job-manager-single-alert-link");
}
});
现在应该从数据库中获取感兴趣和工作的数量,并且点击时唯一登录的用户也会增加。
最佳答案
为什么不直接向自定义帖子类型添加自定义字段,而不是使用自定义表格?这几乎是何时适合使用它的一个典型例子。只需使用 WP Ajax Hook 上的 get_post_meta
和 update_post_meta
将当前用户 ID 添加到数组中即可。
add_action( 'wp_ajax_increment_cpt_interests' );
add_action( 'wp_ajax_nopriv_increment_cpt_interests' );
function increment_cpt_interests(){
extract( $_POST );
// Get current interested people
$interested_people = get_post_meta( $post_id, 'interested', true );
$interested_user = get_current_user_id();
// If current user isn't already "interested"
if( !in_array( $interested_user, $interested_people ){
// Add them to the array of interested people
update_post_meta( $post_id, 'interested_people', $interested_people[$interested_user] );
}
}
只需使用 wp_localize_script
传递帖子 ID、Ajax URL(以及当前用户 ID,如果需要) (了解更多 here )到您要单击的按钮。
关于javascript - 如何在WordPress中实现自定义逻辑?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51004528/