Adam Projo Adam Projo - 1 month ago 8
JSON Question

How to display postmeta key and value in same post id wordpress (JSON data)

in there i have data postmeta i want to show





$command = $_GET['command'];
switch ($command) {
case 'list_product':

$loop = new WP_Query(
array(
'post_type' => 'product'
// 'showposts' => 4,
// 'meta_key' => '_sale_price',
// 'meta_value' => '0',
// 'meta_compare' => '>=',
)
);
if($loop->have_posts()) :

$data = array( "api_status" => 1, "api_message" => "success");
while ( $loop->have_posts() ) : $loop->the_post();

$data[] = array("id" => get_the_ID(),
"post_name" => get_the_title(),
"post_meta" => get_post_meta(get_the_ID());

endwhile;


echo json_encode($data);
break;
}




in there i want to show data :

enter image description here

where the meta data have same post id data,

i want to loop the data in inside details, have someone help me or tell me what code need i improve so my code its work ?

Answer

You can try this

if( $loop->have_posts() ) :

    $data = array( "api_status" => 1, "api_message" => "success");
    $meta = array();
    while ( $loop->have_posts() ) : $loop->the_post();

        $meta[] = array(
            "id"         => get_the_ID(),
            "post_name"  => get_the_title(),
            "_edit_lock" => get_post_meta( get_the_ID(), '_edit_lock', true ),
            "_edit_last" => get_post_meta( get_the_ID(), '_edit_last', true ),
            "username"   => get_post_meta( get_the_ID(), 'username', true ),
            "password"   => get_post_meta( get_the_ID(), 'password', true ),
            "email"      => get_post_meta( get_the_ID(), 'email', true ),
            "phone"      => get_post_meta( get_the_ID(), 'phone', true ),
        );

    endwhile;
endif;

echo  json_encode($meta);