Categories
CMS Mastering Development Wordpress

Get Current Post ID in functions php, meta query filter

How do I get the Current post ID in functions php when creating an meta query filter? I’ve made many attempts but all return Null. The filter works as expected when I manually input a number, but I need it to automatically echo the current post ID. Any guidance is appreciated, thanks.

$args = array(
  'post_type' => 'project',
  'post_status' => 'publish',
  'post_parent' => 'HOW DO I GET CURRENT PAGE ID?',
  'meta_query' => $meta_query,
); 

Here is the full function:

add_action('wp_ajax_my_ajax_filter_search', 'my_ajax_filter_search_callback');
add_action('wp_ajax_nopriv_my_ajax_filter_search', 'my_ajax_filter_search_callback');

function my_ajax_filter_search_callback() {

  header("Content-Type: application/json");

  $meta_query = array('relation' => 'AND');

  if(isset($_GET['project_type'])) {
    $project_type = sanitize_text_field( $_GET['project_type'] );
    $meta_query[] = array(
        'key' => 'project_type',
        'value' => $project_type,
        'compare' => '='
    );
  }

  $args = array(
      'post_type' => 'project',
        'post_status' => 'publish',
        'post_parent' => 'HOW DO I GET CURRENT PAGE ID?',
      'meta_query' => $meta_query,
  );

  if ( $search_query->have_posts()) {

      $filter_result = array();

      while ( $search_query->have_posts() ) {

          $search_query->the_post();

          $filter_result[] = array(
              "id" => get_the_ID(),
              "title" => get_the_title(),
              "permalink" => get_permalink(),
              "status" => get_field('status'),
              "tags" => get_field('tags'),
              "project_type" => get_field('project_type'),
          );
      }
      wp_reset_query();

      echo json_encode($filter_result);

  } else {
    echo 'no content';
  }
  wp_die();
}

Here’s what show’s on the page

$ = jQuery;

var mafs = $("#my-ajax-filter-search"); 
var mafsForm = mafs.find("form"); 

mafsForm.submit(function(e){

    e.preventDefault(); 

    if(mafsForm.find("#project_type").val().length !== 0) {
        var project_type = mafsForm.find("#project_type").val();
    }             
    var data = {
    action : "my_ajax_filter_search",
    project_type : project_type
    }

    $.ajax({
      url : ajax_url,
      data : data,
      success : function(response) {
        mafs.find(".roadmap-search").empty();
        if(response) {
          for(var i = 0 ;  i < response.length ; i++) {
            var html += "<span class='meta category'>" + response[i].project_type + "</span>";
            mafs.find(".roadmap-search").append(html);
          }
        } else {
          var html  = "No matching projects found. Try a different filter or search keyword";
          mafs.find(".roadmap-search").append(html);
        }
      } 
    });

});

Leave a Reply

Your email address will not be published. Required fields are marked *