javascript - 如何在 WordPress 中实现自定义逻辑?
问题描述
我正在我的网站上工作,我想添加两件事。
当用户点击链接时,他/她的用户 ID 和当前帖子 ID 获取并插入数据库,计数器增加。
假设用户登录并打开帖子,链接是这样的:我有兴趣 (0)这里 0 是点击此链接的唯一登录用户总数的计数值。第二个链接就像:我想工作(0)同样的逻辑在这里适用。**
最后需要显示特定职位的感兴趣和工作人员的数量(自定义职位类型:工作)。
有一个表格,其中每一行都有帖子(工作)的标题我可以通过 WordPress 原生函数获取帖子的值,然后将其与数据库中的帖子 ID 进行比较,然后检索它的状态(noofinterested 和 noofworking)然后使用 jQuery 通过 AJAX 注入。
我为此目的创建了表格,但我遇到了困难:
- 通过 jquery 获取 POST ID 和 USER ID 由于某些原因,我无法修改当前的自定义帖子模板,因为我正在使用 wp 作业管理器进行自定义职位发布。
- 我所需要的只是找到一种方法让独特的人依靠特定的帖子
到目前为止,我想到了一种通过 jQuery 附加两个链接的方法,并通过 jQuery 向链接添加单击函数,并在其中添加 ajax 以获取数据并输入到我编码的 PHP 文件中,并在该 PHP 文件中插入通过 post 值进入表中,然后返回响应。在我想在表格行中插入状态的第二页中,我将为此使用 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 挂钩将当前用户 ID 添加到数组中即可get_post_meta
。update_post_meta
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
只需使用(Read more here )将帖子 ID、Ajax URL(和当前用户 ID,如果需要)传递给您想要单击的按钮。
推荐阅读
- python - 使用线程时处理请求异常?
- php - 如何在sql中更新rand号
- c# - 控制台应用程序 C#:如何刷新显示?
- google-cloud-platform - 在 GCP 中删除集群失败,并显示消息“资源未准备好”
- javascript - 当草稿编辑器处于只读模式时不会触发 onChange
- c# - 使用 yield return 来描述一个迭代器
- python - 从破折号的下拉列表中过滤行后显示数据表
- python - 在 Python 中按 Ctrl C 之前保存
- c++ - 为什么 URLDownloadToFile() 没有下载我的文件?
- yii2 - 为什么yii2中的'id'等于null