0

I'm writng custom endpoints for my mobile app..

My output like this

Tried somethings, but getting null values for id, title and content.

function my_function($request) {

$data = array();
$id = (int) $request['id'];
$request = array();

if ( empty( $id ) ) {
    return new WP_Error( 'rest_post_invalid_id', __( 'Invalid term id.' ), array( 'status' => 404 ) );
}

$query = new WP_Query( array(
    'post_type' => 'my_posttype_name',
    'posts_per_page' => -1,
    'tax_query' => array(
        array(
            'taxonomy' => 'my_taxonomy_name',
            'field' => 'term_id',
            'terms' => $id,
        )
    )
) );

print_r($query);

foreach ($query as $q) {
    $data['id'] = $q->posts[0]->ID;
    $data['title'] = $q->posts[0]->post_title;
    $data['content'] = $q->posts[0]->post_excerpt;

    $request[] = $data;
}

return new WP_REST_Response($request, 200);
}

How can I get that values?

2
  • 1
    I suggest you use get_posts instead of relying WP_Query, please take your time to visit @jgraup answer wordpress.stackexchange.com/a/212113 to figure out how to get json output.
    – Jevuska
    Mar 14, 2016 at 16:22
  • yes. added $posts = $query->get_posts(); after wp_query, know it works..
    – sakarya
    Mar 14, 2016 at 16:38

1 Answer 1

0

You're running the query but you're immediately afterwards printing it out, you need to call the method get_posts or use something like a while statement with have_posts:

https://codex.wordpress.org/Class_Reference/WP_Query

1
  • Just saw Jevuska response, credit goes to him for responding first but glad you got it working!
    – sMyles
    Mar 15, 2016 at 15:57

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.