首页 > 解决方案 > 如何在 WordPress 中实现自定义逻辑?

问题描述

我正在我的网站上工作,我想添加两件事。

最后需要显示特定职位的感兴趣和工作人员的数量(自定义职位类型:工作)。

有一个表格,其中每一行都有帖子(工作)的标题我可以通过 WordPress 原生函数获取帖子的值,然后将其与数据库中的帖子 ID 进行比较,然后检索它的状态(noofinterested 和 noofworking)然后使用 jQuery 通过 AJAX 注入。

我为此目的创建了表格,但我遇到了困难:

  1. 通过 jquery 获取 POST ID 和 USER ID 由于某些原因,我无法修改当前的自定义帖子模板,因为我正在使用 wp 作业管理器进行自定义职位发布。
  2. 我所需要的只是找到一种方法让独特的人依靠特定的帖子

到目前为止,我想到了一种通过 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");
    }
});

现在应该从数据库中获取感兴趣和工作的数量,并且对于单击时唯一登录的用户也会增加。

标签: javascriptphpjquerywordpress

解决方案


为什么不向自定义帖子类型添加自定义字段而不是使用自定义表格?这几乎是什么时候适合使用它的一个典型例子。只需使用WP Ajax 挂钩将当前用户 ID 添加到数组中即可get_post_metaupdate_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,如果需要)传递给您想要单击的按钮。


推荐阅读