WordPress – output categories, posts and images to JSON - php

I'm trying to recreate a JSON file with a specific structure and only getting so far as I'm not that familiar with PHP.
I'd like to list all used/non-empty categories, then all posts within each category and then all images/other details used in each post.
I'm not sure how the code should look in the loop. I'd need the JSON to be exactly like below (brackets) as I'm feeding it to a D3 script:
{
"project": "Farm", // website name
"about": "What we have on the farm.",
"categories": [ //post categories
{
"slug": "fruits",
"title": "Fruits",
"description": "All about fruits.",
"posts": [ // all posts within a category
{
"slug": "apples",
"title": "Apples",
"excerpt": "Apple trees and fruits.",
"tags": "tree, apple",
"post_images": [
{
"id": 25,
"title": "Apple trees.",
"filename": "apple-trees.jpg",
"desc": "Rows of apple trees.",
"tags": ""
},
(...)
The PHP script so far (in functions.php):
function export_to_json() {
global $post;
$post_args = array(
'post_type' => 'post',
'post_status' => 'publish',
'posts_per_page' => -1,
);
$cat_args = array(
'orderby' => 'name',
'order' => 'ASC'
);
$posts = array();
$cats = get_categories( $cat_args );
foreach( $cats as $cat ) {
$query = new WP_Query( $post_args );
while ( $query->have_posts() ): $query->the_post();
$posts[] = array(
'categories' => [
'title' => $cat->cat_name,
'description' => $cat->description,
'posts' => [
'title' => get_the_title(),
'excerpt' => get_the_excerpt(),
'images' => get_attached_media( 'image' ),
'tags' => get_tags()
]
]
);
endwhile;
wp_reset_query();
}
$data = json_encode($posts, JSON_PRETTY_PRINT);
$upload_dir = wp_get_upload_dir();
$file_name = date('Y-m-d') . '.json';
$save_path = $upload_dir['basedir'] . '/' . $file_name;
$f = fopen($save_path, "w");
fwrite($f, $data);
fclose($f);
}
add_action('save_post', 'export_to_json');
The script is wrong because categories get repeated for each post and I'd like all posts within a category to be properly nested.
Any help with this would be much appreciated. Thanks.

Here you go:
function export_to_json() {
global $post;
$categories = array();
$cat_args = array(
'orderby' => 'name',
'order' => 'ASC'
);
$cats = get_categories( $cat_args );
foreach( $cats as $cat ) {
$post_args = array(
'post_type' => 'post',
'post_status' => 'publish',
'posts_per_page' => -1,
'category__in' => $cat->term_id
);
$get_posts = array();
$posts = get_posts( $post_args );
foreach($posts as $post){
$tags = get_the_tags($post->ID);
$i = 0;
$tag_names = '';
$post_images = array();
if( $tags) {
foreach( $tags as $tag ) { $i++;
$comma = $i == count($tags) ? '' : ', ';
$tag_names .= $tag->name . $comma;
}
}
$images = get_post_gallery($post->ID, false);
if($images){
$image_ids = explode(",", $images['ids']);
foreach ($image_ids as $image ){
$img = wp_prepare_attachment_for_js($image);
$post_images[] = array(
"id" => $img['id'],
"title" => $img['name'],
"filename" => $img['filename'],
"desc" => $img['description'], //Pulls the image description
'tags' => $tag_names
);
}
}
$get_posts[] = array(
'slug' => $post->post_name,
'title' => get_the_title(),
'excerpt' => get_the_excerpt(),
'tags' => $tag_names,
'post_images' => $post_images
);
}
$categories[] = array(
'slug' => $cat->slug,
'title' => $cat->cat_name,
'description' => $cat->description,
'posts' => $get_posts
);
}
$output = array(
'project' => get_bloginfo('name'),
'about' => get_bloginfo('description'),
'categories' => $categories
);
$data = json_encode($output, JSON_PRETTY_PRINT);
}

Related

WooCommerce - Get product variation SKU in loop

I'm trying to get the product variation SKU's but it always returns blank. I've tried everything I can think of so far and I have been unable to find any answer here.
foreach ($available_variations as $variation) {
$variation_id = $variation->ID;
$variant = new WC_Product_Variation($variation_id);
// Get data from the product variation
$excerpt_var = wpautop($variation['variation_description']);
$sku = $variation['sku'];
$price = $variation['display_regular_price'];
$price = number_format($price, 0, ',', ' ');
if ($price != null) {
$price = $price . ",-";
}
$results[] = array(
"id" => $available_variations,
"cat" => $cat->name,
"sku" => $sku,
"title" => $title,
"price" => $price != null ? $price : "",
"excerpt" => $excerpt_var,
"thumbnail" => $thumbnail,
"type" => "variation"
);
}
Whole function to get all prods and variations is here:
function get_all_prods_for_csv() {
$results = array(); // Rows to be returned
// Settings
$taxonomy = 'product_cat';
$title = '';
$empty = 0;
// Query arguments
$args_cat = array(
'taxonomy' => $taxonomy,
'orderby' => 'menu_order',
'show_count' => 0, // 1 for yes, 0 for no
'pad_counts' => 0, // 1 for yes, 0 for no
'hierarchical' => 0, // 1 for yes, 0 for no
'title_li' => $title,
'hide_empty' => $empty
);
// For all categories
foreach (get_categories( $args_cat ) as $cat) {
// If root category
if ($cat->category_parent === 0) {
$category_id = $cat->term_id;
$category_slug = $cat->slug;
$cat_thumbnail_id = get_woocommerce_term_meta( $cat->term_id, 'thumbnail_id', true );
$cat_image = wp_get_attachment_url( $cat_thumbnail_id );
$results[] = array(
"id" => $category_id,
"cat" => $cat->name,
"sku" => '',
"title" => '',
"price" => '',
"excerpt" => category_description( $category_id ),
"thumbnail" => $thumbnail,
"type" => "category"
);
// Get all products for current category
// Query arguments
$args_prod = array(
'post_type' => 'product',
'posts_per_page' => -1,
'order' => 'asc',
'orderby' => 'menu_order',
'tax_query' => array(
array(
'taxonomy' => 'product_cat',
'field' => 'id',
'terms' => $category_id
)
)
);
$products = get_posts( $args_prod );
// For all products
foreach ( $products as $prod ) {
$product = wc_get_product($prod->ID);
// Get data from the product
$title = $product->get_title();
$thumbnail = get_the_post_thumbnail_url($prod->ID);
$excerpt = wpautop($product->get_short_description()); // wpautop(get_the_excerpt($prod->ID));
// If single variation
if( $product->is_type( 'simple' ) ) {
$price = $product->get_price();
$price = number_format($price, 0, ',', ' ');
$results[] = array(
"id" => $prod->ID,
"cat" => $cat->name,
"sku" => $product->get_sku(),
"title" => $title,
"price" => $price != null ? $price . "" : "",
"excerpt" => $excerpt,
"thumbnail" => $thumbnail,
"type" => "simple"
);
} else if ( $product->is_type( 'variable' ) ) {
$available_variations = $product->get_available_variations();
$counting_variations = 1;
foreach ($available_variations as $variation) {
$counting_variations++;
}
$results[] = array(
"id" => $prod->ID,
"cat" => $cat->name,
"sku" => "",
"title" => $title,
"price" => "",
"excerpt" => $excerpt,
"thumbnail" => $thumbnail,
"type" => "variation_root"
);
foreach ($available_variations as $variation) {
$variation_id = $variation->ID;
$variant = new WC_Product_Variation($variation_id);
// Get data from the product variation
$excerpt_var = wpautop($variation['variation_description']);
$sku = $variation['sku'];
$price = $variation['display_regular_price'];
$price = number_format($price, 0, ',', ' ');
if ($price != null) {
$price = $price . ",-";
}
$results[] = array(
"id" => $available_variations,
"cat" => $cat->name,
"sku" => $sku,
"title" => $title,
"price" => $price != null ? $price : "",
"excerpt" => $excerpt_var,
"thumbnail" => $thumbnail,
"type" => "variation"
);
}
}
}
}
}
return $results;
}
This line
$sku = $variation['sku'];
should be
$sku = $variant['sku'];
since you get the object as that variable $variant.

How to export category name and category link in wordpress json

all queries work except category name and category link, if I use "get_the_category()" it shows several things I don't need, like "category_count" , "category_description" etc.
and i need to know how to separate jsons by post category
this is my code
$args = array(
'post_type' => 'post',
'post_status' => 'publish',
'posts_per_page' => 10,
);
$query = new WP_Query( $args );
$posts = array();
while( $query->have_posts() ) : $query->the_post();
$posts[] = array(
'id' => get_the_ID(),
'date' => get_the_date(),
'title' => get_the_title(),
'link' => get_the_permalink(),
'image' => get_the_post_thumbnail_url(),
'category' => get_the_category ( 'cat_name' ),
'categoryLink' => get_category_link ( $category_id )
);
endwhile;
wp_reset_query();
$data = json_encode($posts);
$upload_dir = wp_get_upload_dir();
$file_name = date('Y-m-d') . '.json';
$save_path = $upload_dir['basedir'] . '/' . $file_name;
$f = fopen( $save_path , "w" );
fwrite($f , $data);
fclose($f);
}
add_action( 'save_post', 'export_posts_in_json' ); ```
get_the_category requires a post id (or boolean false) - See: https://developer.wordpress.org/reference/functions/get_the_category/
get_category_link requires an integer or category object - See: https://developer.wordpress.org/reference/functions/get_category_link/
Check your parameters and see if that helps.

PHP merge arrays and send through wp_insert_post()

I am trying to merge the following arrays.
I want this result:
foreach( $datas as $data ) {
$my_post = array(
'post_title' => $title['title_value'],
'post_status' => 'pending',
'post_type' => $type['type_value'],
'post_author' => $author['author_value'],
);
wp_insert_post( $my_post );
}
My data:
$title = title1,title2,,title4,title5 // 5 datas separated with coma
$type = type1,type2,type3,type4,, // 5 datas separated with coma
$author = ,author2,author3,author4,author5 // 5 datas separated with coma
What I have done:
$datas = array(
'title' => explode( ",", $title ),
'type' => explode( ",", $type ),
'author' => explode( ",", $author ),
);
foreach( $datas as $data ) {
// foreach( $data as $d ) {
// }
}
Does anybody know how to do this?
Hope you can understand the question. Thank you in advance.
If your all data(title,type and author) have same data count you can use this way
$title_array = explode(',', $title);
$type_array = explode(',', $type);
$author_array = explode(',', $author);
if (count($title_array) > 0)
{
foreach ($title_array as $title_index => $title_value)
{
$my_post = array(
'post_title' => $title_value,
'post_status' => 'pending',
'post_type' => $type_array[$title_index],
'post_author' => $author_array[$title_index],
);
wp_insert_post($my_post);
}
}

php create json multiple arrays

php create json multiple arrays. Following code with php i need output like that json .. so many array and object confusing me. we using wordpres
<?php
$categories = get_categories( array(
'orderby' => 'name',
'parent' => 0
));
foreach ( $categories as $category ) {
$category_id = $category->term_id;
$category_name = $category->name;
echo $category_name;
echo "<br>";
$args = array(
'post_type' => 'post',
'post_status' => 'publish',
'category' => $category_id
);
$myposts = get_posts( $args );
foreach( $myposts as $post ){
$category_postname = $post->post_title;
echo $category_postname;
echo "<br>";
}
}
?>
Php output is"
Testcat1
pos1
post2
Testcat2
post3
post4
TestCat3
post5
post 6
I need create Json like this:
{
"data": [
{
"cat": "Testcat1",
"post": [
{
"name": "post1"
},
{
"name": "post2"
}
]
},
{
"cat": "Testcat2",
"post": [
{
"name": "post3"
},
{
"name": "post4"
}
]
},
{
"cat": "Testcat3",
"post": [
{
"name": "post5"
},
{
"name": "post6"
}
]
}
]
}
i need like this json output.
You should put everything in an array and the json_encode it. I commented out your echos, so you could use them if you need later.
<?php
$categories = get_categories( array(
'orderby' => 'name',
'parent' => 0
));
// init empty array with root "data"
$array = array( 'data' => array() );
// set counter to 0 for array later on
$n = 0;
foreach ( $categories as $category ) {
$category_id = $category->term_id;
$category_name = $category->name;
// store cat.name
$array['data'][$n]['cat'] = $category_name;
// echo $category_name;
// echo "<br>";
$args = array(
'post_type' => 'post',
'post_status' => 'publish',
'category' => $category_id
);
$myposts = get_posts( $args );
// init posts counter
$i = 0;
foreach( $myposts as $post ){
$category_postname = $post->post_title;
$array['data'][$n]['post'][$i]['name'] = $category_postname;
$array['data'][$n]['post'][$i]['id'] = $post->ID;
// echo $category_postname;
// echo "<br>";
// increment post loop counter
$i++;
}
// increment counter for array
$n++;
}
echo json_encode( $array );
?>

Wordpress: Cannot use object of type stdClass as array

I get this array error
"Fatal error: Cannot use object of type stdClass as array"
in Wordpress on file category.php. The issue arrives when I don't have any subcategories of a category, so I try to handle if the subcategory list is 0.
But I keep getting the same error, can someone see the error I do here?
The error appears starting in the line:
"if ($category[0]->category_parent == 0) {"
And the whole code within the brackets.
<?php
$args = array(
'type' => 'post',
'child_of' => $cat_id,
'parent' => get_query_var(''),
'orderby' => 'name',
'order' => 'ASC',
'hide_empty' => 0,
'hierarchical' => 1,
'exclude' => '',
'include' => '',
'number' => '',
'taxonomy' => 'category',
'pad_counts' => true );
$categories = get_categories($args);
if ($category[0]->category_parent == 0) {
$tag = $category[0]->cat_ID;
$tag_extra_fields = get_option(MY_CATEGORY_FIELDS);
if (isset($tag_extra_fields[$tag])) {
$category_icon_code = $tag_extra_fields[$tag]['category_icon_code'];
$category_icon_color = $tag_extra_fields[$tag]['category_icon_color'];
}
} else {
$tag = $category[0]->category_parent;
$tag_extra_fields = get_option(MY_CATEGORY_FIELDS);
if (isset($tag_extra_fields[$tag])) {
$category_icon_code = $tag_extra_fields[$tag]['category_icon_code'];
$category_icon_color = $tag_extra_fields[$tag]['category_icon_color'];
}
}
foreach($categories as $category) { ?>

Categories