0

I am writing a code snippet to fill a table from the database with WordPress and I am doing an AJAX request responding with the posts in JSON format. At the moment I have the posts in JavaScript and now I want to get specific fields like price or supplies. How do I do that in JavaScript? I know I can do it in PHP with $post->fieldname but not how to do it in JavaScript. The post_title needs to be replaced with post variables.

Javascript

function do_update_table(posts) {
    table = document.getElementById("' . $table_id . '");
    tableBody = table.firstChild;
    var i = tableBody.children.length - 1;

    while(i > 0)
    {
        tableBody.removeChild(tableBody.children[i]);
        i--;
    }

    posts.forEach(function(post){
        console.log(post);
        tableBody.innerHTML += "<tr><td>" + post.post_title + "</td><td>" + post.post_title + "</td><td>" + post.post_title + "</td><td>" + post.post_title + "</td></tr>";
    });
}

Php post getting in functions.php

function do_find_posts_by_term()
{
    if (!isset($_GET)) {
        die;
    }

    if (!isset($_GET['post_type'])) {
        echo "Parameter post_type is missing";
        die;
    }
    if (!isset($_GET['taxonomy_name'])) {
        echo "Parameter taxonomy is missing";
        die;
    }
    if (!isset($_GET['term_id'])) {
        echo "Parameter term is missing";
        die;
    }
    $post_type = $_GET['post_type'];
    $term_id = $_GET['term_id'];
    $taxonomy_name = $_GET['taxonomy_name'];

    $args = array(
        'post_type'   => $post_type,
        'tax_query' => array(
            array(
                'taxonomy' => $taxonomy_name,
                'field' => 'id',
                'terms' => $term_id,
                'include_children' => false
            )
        )
    );
    $posts = get_posts($args);
    echo (json_encode($posts));
    die;
}
add_action('wp_ajax_get_posts_by_term', 'do_find_posts_by_term');
add_action('wp_ajax_nopriv_get_posts_by_term', 'do_find_posts_by_term');

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.