2014-02-07 5 views
0

Код, используемый ниже, используется для печати некоторых данных о товарах из Woocommerce на моем веб-сайте Wordpress.Данные Wordpress как JSON

<?php 
    $args = array(
       'post_type' => 'product', 
       'posts_per_page' => 200, 
       'product_cat' =>'pants' 
      ); 
    $loop = new WP_Query($args); 

    while ($loop->have_posts()) : $loop->the_post(); 
    global $product; 


    echo '<br /><a href="'.get_permalink().'">' . woocommerce_get_product_thumbnail().' '.the_title(). ' '.the_content().' '.get_post_meta(get_the_ID(), '_regular_price', true).' '.get_post_meta(get_the_ID(), '_sale_price', true).'</a>'; 
    endwhile; 
    wp_reset_query(); 
?> 

Это данные, которые мне нужны для таких продуктов, как их имя, образ, рег. цена и цена продажи и т. д. Этот код делает это успешно и перекликается с данными на странице. Код возвращает эти данные для каждого продукта, так что список продуктов с их именем, изображением и т. Д. Печатается на странице html.

Однако мне нужно получить те же данные, что и этот код, но в формате JSON.

Многие продукты будут возвращены с каждым как объект JSON в этом формате:

[{"term_id":"64","name":"Argentina","slug":"argentina","term_group":"0","term_taxonomy_id":"64","taxonomy":"product_cat","description":"","parent":"13","count":"20","meta_id":"154","woocommerce_term_id":"64","meta_key":"order","meta_value":"0","cat_ID":"64","category_count":"20","category_description":"","cat_name":"Argentina","category_nicename":"argentina","category_parent":"13"},] 

JSON выше возвращается, когда я делаю это echo json_encode($loop->get_posts());

Как получить те же данные, что вторит на страницу, возвращенную в JSON, а не как HTML.

Пожалуйста, помогите нам в этом. Некоторое время я искал ответ.

Это просто невозможно? Кажется, никто не ответил. Любая помощь будет оценена по достоинству.

EDIT:

Когда я echo json_encode($loop);, я получаю следующее:

{"query_vars":{"post_type":"product","posts_per_page":200,"product_cat":"Alcopops","error":"","m":0,"p":0,"post_parent":"","subpost":"","subpost_id":"","attachment":"","attachment_id":0,"name":"","static":"","pagename":"","page_id":0,"second":"","minute":"","hour":"","day":0,"monthnum":0,"year":0,"w":0,"category_name":"","tag":"","cat":"","tag_id":"","author_name":"","feed":"","tb":"","paged":0,"comments_popup":"","meta_key":"","meta_value":"","preview":"","s":"","sentence":"","fields":"","menu_order":"","category__in":[],"category__not_in":[],"category__and":[],"post__in":[],"post__not_in":[],"tag__in":[],"tag__not_in":[],"tag__and":[],"tag_slug__in":[],"tag_slug__and":[],"post_parent__in":[],"post_parent__not_in":[],"ignore_sticky_posts":false,"suppress_filters":false,"cache_results":true,"update_post_term_cache":true,"update_post_meta_cache":true,"nopaging":false,"comments_per_page":"50","no_found_rows":false,"taxonomy":"product_cat","term":"Alcopops","order":"DESC"},"tax_query":{"queries":[{"taxonomy":"product_cat","terms":["Alcopops"],"include_children":true,"field":"slug","operator":"IN"}],"relation":"AND"},"meta_query":{"queries":[],"relation":null},"post_count":3,"current_post":-1,"in_the_loop":false,"comment_count":0,"current_comment":-1,"found_posts":"3","max_num_pages":1,"max_num_comment_pages":0,"is_single":false,"is_preview":false,"is_page":false,"is_archive":true,"is_date":false,"is_year":false,"is_month":false,"is_day":false,"is_time":false,"is_author":false,"is_category":false,"is_tag":false,"is_tax":true,"is_search":false,"is_feed":false,"is_comment_feed":false,"is_trackback":false,"is_home":false,"is_404":false,"is_comments_popup":false,"is_paged":false,"is_admin":false,"is_attachment":false,"is_singular":false,"is_robots":false,"is_posts_page":false,"is_post_type_archive":true,"query_vars_hash":"5bcaf536a84f30a7d5cd599078fa354d","query_vars_changed":false,"thumbnails_cached":false,"query":{"post_type":"product","posts_per_page":200,"product_cat":"Alcopops"},"request":"SELECT SQL_CALC_FOUND_ROWS wp_posts.ID FROM wp_posts INNER JOIN wp_term_relationships ON (wp_posts.ID = wp_term_relationships.object_id) WHERE 1=1 AND (wp_term_relationships.term_taxonomy_id IN (26)) AND wp_posts.post_type = 'product' AND (wp_posts.post_status = 'publish') GROUP BY wp_posts.ID ORDER BY wp_posts.post_date DESC LIMIT 0, 200","posts":[{"ID":254,"post_author":"3","post_date":"2013-10-17 23:24:19","post_date_gmt":"2013-10-17 23:24:19","post_content":"","post_title":"Green Sands","post_excerpt":"","post_status":"publish","comment_status":"open","ping_status":"closed","post_password":"","post_name":"green-sands-2","to_ping":"","pinged":"","post_modified":"2013-10-17 23:24:19","post_modified_gmt":"2013-10-17 23:24:19","post_content_filtered":"","post_parent":0,"guid":"http:\/\/cbbnideas.com\/brydens-website\/?post_type=product&p=254","menu_order":0,"post_type":"product","post_mime_type":"","comment_count":"0","filter":"raw","format_content":null},{"ID":246,"post_author":"3","post_date":"2013-10-17 23:15:41","post_date_gmt":"2013-10-17 23:15:41","post_content":"Ginger Shandy is an exciting blend of the natural ginger root extract and beer. It has a crisp ginger taste that is carefully balanced with a slight, sweet note and beer flavour without any after taste.\r\nTaste - clean, ginger flavour\r\nAroma - ginger aroma\r\nVisual - clear, golden colour","post_title":"Carib Shandy Ginger","post_excerpt":"","post_status":"publish","comment_status":"open","ping_status":"closed","post_password":"","post_name":"carib-shandy-ginger-2","to_ping":"","pinged":"","post_modified":"2013-10-17 23:25:47","post_modified_gmt":"2013-10-17 23:25:47","post_content_filtered":"","post_parent":0,"guid":"http:\/\/cbbnideas.com\/brydens-website\/?post_type=product&p=246","menu_order":0,"post_type":"product","post_mime_type":"","comment_count":"0","filter":"raw","format_content":null},{"ID":43,"post_author":"1","post_date":"2013-09-27 13:50:21","post_date_gmt":"2013-09-27 13:50:21","post_content":"Sorrel Shandy is a blend of sorrel extract and beer. Its flavour can be described as a pleasant, sweet, smooth, refreshing sorrel flavour, carefully balanced sweet note and beer flavour.\u00a0Taste - clean, sorrel flavour.\u00a0Aroma - slightly sweet, floral aroma.","post_title":"Carib Shandy Sorrel","post_excerpt":"Sorrel Shandy is a blend of sorrel extract and beer. Its flavour can be described as a pleasant, sweet, smooth, refreshing sorrel flavour, carefully balanced sweet note and beer flavour.","post_status":"publish","comment_status":"open","ping_status":"closed","post_password":"","post_name":"carib-shandy-sorrel-3","to_ping":"","pinged":"","post_modified":"2013-10-14 19:52:28","post_modified_gmt":"2013-10-14 19:52:28","post_content_filtered":"","post_parent":0,"guid":"http:\/\/cbbnideas.com\/brydens-website\/?post_type=product&p=43","menu_order":0,"post_type":"product","post_mime_type":"","comment_count":"0","filter":"raw","format_content":null}],"post":{"ID":254,"post_author":"3","post_date":"2013-10-17 23:24:19","post_date_gmt":"2013-10-17 23:24:19","post_content":"","post_title":"Green Sands","post_excerpt":"","post_status":"publish","comment_status":"open","ping_status":"closed","post_password":"","post_name":"green-sands-2","to_ping":"","pinged":"","post_modified":"2013-10-17 23:24:19","post_modified_gmt":"2013-10-17 23:24:19","post_content_filtered":"","post_parent":0,"guid":"http:\/\/cbbnideas.com\/brydens-website\/?post_type=product&p=254","menu_order":0,"post_type":"product","post_mime_type":"","comment_count":"0","filter":"raw","format_content":null}} 
+0

возможно вместо вторя внутри loop, вы назначили 'get_whatever()' версии этих вызовов для php arra, а затем закодировали массив ... –

+0

Что помогает на экране, когда вы эхо из json encode par т? Вы пробовали просто использовать 'echo json_encode ($ loop);'? – Howli

+0

@Howlin См. Изменение выше. – Tester

ответ

2

изменить код, начиная с время цикла до конца с этим

$jsondata = array(); 
while ($loop->have_posts()) : $loop->the_post(); 
global $product; 

$jsondata[] = array(
    'image' =>woocommerce_get_product_thumbnail(), 
    'title' => get_the_title(), 
    'content' => get_the_content(), 
    'regular_price' => get_post_meta(get_the_ID(), '_regular_price', true), 
    'sale_price'=> get_post_meta(get_the_ID(), '_sale_price', true) 
); 
endwhile; 
wp_reset_query(); 

ob_clean(); 
echo json_encode($jsondata); 
exit(); 
+0

Пробовал это, но 'title' и' content' отображаются как значение «null» '' title ": null," content ": null'. Тем не менее, продажная цена и регулярные цены появляются. – Tester

+0

Заголовок и контент появятся в верхней части страницы, но не в JSON – Tester

+0

извините. Используйте get_the_title() вместо the_title() – Nihat

Смежные вопросы