从Wordpress获取所有帖子作为JSON

Tes*_*ter 10 php wordpress

我正在尝试通过post_type"product"获取我的Wordpress网站上的所有帖子.

我尝试了以下但它不起作用.

<?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();
?>
Run Code Online (Sandbox Code Playgroud)

虽然当我添加'posts_per_page' => 450$args,它会返回该类型的帖子,但是如果我添加一个高于450的值,例如500,它将不再返回任何内容.

我正在使用它遍历所有产品帖子并将名称,价格等添加到循环中的数组.

如何修复$args以获取所有产品帖子.

编辑:

我最近也尝试过:

<?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();
    ?>
Run Code Online (Sandbox Code Playgroud)

P_E*_*que 11

这里不需要模拟循环.这是最直接的方式:

$args = array( 
    'post_type' => 'product', 
    'post_status' => 'publish', 
    'nopaging' => true 
);
$query = new WP_Query( $args ); // $query is the WP_Query Object
$posts = $query->get_posts();   // $posts contains the post objects

$output = array();
foreach( $posts as $post ) {    // Pluck the id and title attributes
    $output[] = array( 'id' => $post->ID, 'title' => $post->post_title );
}
echo json_encode( $output );
Run Code Online (Sandbox Code Playgroud)

或者你可以省略foreachecho json_encode( $posts );获得帖子的所有属性.


Mub*_*har 3

请检查您的表格中的数据。有没有帖子类的产品。如果是,那么简单的查询应该可以工作

SELECT * FROM $wpdb->posts WHERE $wpdb->posts.`post_type` = 'product' AND $wpdb->posts.`post_status` = 'publish'
Run Code Online (Sandbox Code Playgroud)

您可以直接在 phpmyadmin 中运行此代码。并查看是否有任何帖子。并请将 $wpdb 替换为您的表的前缀。