如何在相同的帖子id wordpress(JSON数据)中显示postmeta键和值

时间:2016-10-22 02:06:22

标签: javascript php json wordpress

在那里我有数据postmeta我想要显示

$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;
}

在那里我想显示数据:

enter image description here

其中元数据具有相同的帖子ID数据

我想在内部细节中循环数据,有人帮助我或告诉我需要改进哪些代码,以便我的代码能够工作?

3 个答案:

答案 0 :(得分:5)

元数据存储在 wp_postmeta 表中。使用json_encode。

您可以按$meta = get_post_meta( get_the_ID() );

获取元数据

请检查以下代码。

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);

答案 1 :(得分:4)

如果您只想将表数据作为json,那么您只需要使用json_encode()

http://php.net/manual/en/function.json-encode.php

答案 2 :(得分:4)

你可以试试这个

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);