以 JSON 格式从 Wordpress 获取所有帖子 [英] Get all posts from Wordpress as JSON
问题描述
我正在尝试使用 post_typeproduct"从我的 Wordpress 网站获取所有帖子.
I am trying ti get all the posts form my Wordpress website with the post_type "product".
我尝试了以下方法,但不起作用.
I tried the below but it doesn't work.
<?php
$args = array( 'post_type' => 'product', 'post_status' => 'publish');
$loop = new WP_Query( $args );
$array = array();
while ( $loop->have_posts() ) : $loop->the_post();
global $product;
$array[] = array(
'id' => get_the_ID(),
'title' => get_the_title()
);
endwhile;
wp_reset_query();
ob_clean();
echo json_encode($array);
exit();
?>
虽然当我添加 'posts_per_page' =>450
到 $args
,它返回类型的帖子,但是如果我添加一个大于 450 的值,例如 500,它不会再次返回任何内容.
Although when I add 'posts_per_page' => 450
to $args
, it returns posts of the type, however if I add a value higher than 450 such as 500, it returns nothing again.
我正在使用它来遍历所有产品帖子,并将名称、价格等添加到循环中的数组中.
I am using this to loop through all product posts and add the name, price etc. to an array in the loop.
如何修复 $args
以获取所有产品帖子.
How do I fix the $args
to get all the product posts.
我最近也尝试过:
<?php
$args="SELECT * FROM wp_posts WHERE wp_posts.`post_type` = 'product' AND wp_posts.`post_status` = 'publish'";
$loop = get_results( $args );
$array = array();
while ( $loop->have_posts() ) : $loop->the_post();
global $product;
$array[] = array(
'id' => get_the_ID(),
'title' => get_the_title()
);
endwhile;
// wp_reset_query();
ob_clean();
echo json_encode($array);
exit();
?>
推荐答案
请检查您的表格中的数据.是否有任何帖子类型的产品.如果是,那么简单的查询应该可以工作
please check your table for data. Is there any post of post type products. if yes then the simple query should work
SELECT * FROM $wpdb->posts WHERE $wpdb->posts.`post_type` = 'product' AND $wpdb->posts.`post_status` = 'publish'
您可以直接在 phpmyadmin 中运行此代码.看看有没有帖子.并将 $wpdb 替换为您表的前缀.
you can run this code in phpmyadmin directly. and see if any post is there. and please replace $wpdb with the prefix of you tables.
这篇关于以 JSON 格式从 Wordpress 获取所有帖子的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!