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 );
?>
Related
I want to print (meta_value) from all fields
"Post_views_count" from table (post_meta) But provided that this happens in every category.
I want to count every visit inaide selected category , and in the end appear the name of category and every category generate visitors inside it .
This is the code that i used it and work good but the page are too slowly due to recurrent queries
<?php
$args = array(
'orderby' => 'name',
'parent' => 0,
'depth' => 0
);
// Extract all categories
$categories = get_categories( $args );
foreach ( $categories as $category ) {
// Extract all posts within each category
$args = array(
'cat' => $category->term_id,
'orderby' =>'post_date',
'post_type' => 'post',
'posts_per_page' => '-1',
);
$query = new WP_Query( $args );
// Views variable
$allview_cat = 0;
if ( $query->have_posts() ) {
$posttype = get_post_type(get_the_ID());
while ( $query->have_posts() ) {
$query->the_post();
$do_not_duplicate[] = $post->ID;
// Query that extracts all fields containing post_views_count + post id
$post_id = $wpdb->get_results("SELECT meta_value FROM $wpdb->postmeta WHERE (meta_key = 'post_views_count' AND post_id = $post->ID );");
$post_id = array_map(function($item){
return $item->{'meta_value'};
}
,$post_id);
foreach($post_id as $m_key => $m_value) {
$allview_cat = $m_value + $allview_cat ."<br>";
}
} // end while
} // end if
// Views variable
echo $allview_cat;
}
?>
<?php
$args = array(
'orderby' => 'name',
'parent' => 0,
'depth' => 0
);
$categories = get_categories( $args );
foreach ( $categories as $category ) {
$cat_id = $category->term_id;
$args_post = array(
'cat' => $cat_id,
'post_type' => 'post',
'posts_per_page' => '-1',
);
$query = new WP_Query( $args_post );
$allview = array();
if ( $query->have_posts() ) {
while ( $query->have_posts() ) {
$query->the_post();
$post_id = get_the_ID();
if ( !isset( $allview[$cat_id] ) {
$allview[$cat_id] = 0;
}
$post_views_count = get_post_meta( $post_id, 'post_views_count' );
$allview[$cat_id] = (int)$allview[$cat_id] + (int)$post_views_count;
}
}
}
//display results
foreach ( $allview as $cat => $value ) {
echo $cat . ' = ' . $value;
}
?>
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);
}
I'm using this code...
function include_post_types() {
$post_types = get_post_types( array (
'show_ui' => true
),
'objects' );
$return = '';
foreach ( $post_types as $post_type ) {
$my_sitemap_options = get_option( 'my_sitemap_settings' );
$post_type_name = $post_type->name;
if ($my_sitemap_options['post_types'] && in_array($post_type_name, $my_sitemap_options['post_types'])) {
$the_excluded = $post_type_name;
$return .= "'" . $the_excluded . "', ";
}
}
return $return;
}
... to return a list of custom post types that I have selected from an options page. This works fine, and if I do this...
echo included_post_types();
...I see this...
'clothes', 'shoes', 'jackets',
...which is what I excpected.
But the problem is when I try to use included_post_types() in a loop to only show posts with those post types, like this:
$sitemap_post_args = array(
'post_type' => array(included_post_types()),
'posts_per_page' => -1,
'orderby' =>'post_type',
'order' =>'asc'
);
$loop = new WP_Query($sitemap_post_args);
global $post_type;
global $post;
echo '<ul>';
$last_post_type = '';
while($loop->have_posts()): $loop->the_post();
$current_post_type = $post->post_type;
$current_post_type_object = get_post_type_object( $current_post_type );
if($current_post_type != $last_post_type) echo "<br /><li><strong>" . $current_post_type_object->labels->name . "</strong></li>";?>
<li><?php echo get_the_title(); ?></li>
<?php echo "\n";
$last_post_type = $current_post_type;
endwhile;
wp_reset_query();
echo '</ul>';
It simply doesn't display anything on my page, but it doesn't throw an error either.
I'm almost certain the problem is this line:
'post_type' => array(included_post_types()),
I even tried it like this...
'post_type' => included_post_types(),
...but it did not work.
If I try this...
'post_type' => array('clothes', 'shoes', 'jackets', ),
...it works, but I need to be able to use the function name.
Any suggestions would be helpful.
please replace below code with yours. It should be help.
function include_post_types() {
$post_types = get_post_types( array (
'show_ui' => true
),
'objects' );
$return = array();
foreach ( $post_types as $post_type ) {
$my_sitemap_options = get_option( 'my_sitemap_settings' );
$post_type_name = $post_type->name;
if ($my_sitemap_options['post_types'] && in_array($post_type_name, $my_sitemap_options['post_types'])) {
$the_excluded = $post_type_name;
$return[] = $the_excluded;
}
}
return $return;
}
and also replace below code that show posts
$post_type_list = include_post_types();
$sitemap_post_args = array(
'post_type' => $post_type_list,
'posts_per_page' => -1,
'orderby' =>'post_type',
'order' =>'asc'
);
Here is my code:
$args = array(
'posts_per_page' => - 1,
'post_type' => array('post-type-name'),
'tax_query' => $taxquery,
'orderby' => 'meta_value_num',
'meta_key' => 'date_of_issue',
'order' => 'DESC',
);
global $post;
$post_list = get_posts($args);
if ($post_list) {
foreach ($post_list as $post_item) { ?>
<?php
$fields = CFS()->get('anouncements', $post_item->ID);
if ( ! empty ( $fields ) ){
foreach ($fields as $field_eti) { ?>
<div class="item"><?php echo $field_eti['date_of_issue']; ?></div>
<?php }
}
?>
<?php
}
}
I'm using Custom Field suite plugin. I want to order those fields by this date which is one of the custom fields of that loop ($field_eti['date_of_issue'];). How you see in my $args I added that meta_key and ordered it by custom field value which is date. But ordering isn't right.
Try this: I have updated my answer.
foreach ($post_list as $post_item) {
setup_postdata($post_item); // Set postdata
?>
<?php
$fields = CFS()->get('anouncements');
$temp=array();
if ( ! empty ( $fields ) ){
foreach ($fields as $field_eti) {
$temp[] = strtotime($field_eti['date_of_issue']);
?>
<div class="item"><?php echo $field_eti['date_of_issue']; ?></div>
<?php }
$new_field_eti[] = arsort($temp);
print_r($new_field_eti);
}
?>
<?php
}
I'm trying to combine 2 custom post types: 1) CPT = event 2) CPT = location, in the same foreach loop.
e.g.
<?php
$events = get_posts( array( post_type => event));
$locations = get_posts( array( post_type => location));
foreach($events as $event ) {
foreach($locations as $location ) {
echo $event->post_title;
echo $location->post_title;
}
}
?>
This however will only duplicate each post title. I also tried the following but it didn't work.
<?php
foreach($events as $index => $event ) {
$event->post_title;
$event->post_title[$index];
}
I'm not sure what you want as an output. This should give you a list of all titles:
foreach($events as $event ) {
$titles[]=$event->post_title;
}
foreach($locations as $location ) {
$titles[]=$location->post_title;
}
echo '<ul>';
foreach($titles as $title ) {
echo '<li>'.$title.'</li>';
}
echo '</ul>';
First thing you should do is switch to using WP_Query instead of get_posts and you can do the following quick dirty example:
// The Query args
$args = array(
'post_type' => array( 'event', 'location' )
);
// The Query
$the_query = new WP_Query( $args );
// The Loop
if ( $the_query->have_posts() ) {
echo '<ul>';
while( $the_query->have_posts() ){
$post = $the_query->the_post();
echo '<li>' . get_the_title() . '<li>';
}
echo '</ul>';
}
I guess I found what you need:
$args = array(
'post_type' => 'event'
);
/* Get events */
$events = get_posts( $args );
foreach($events as $event ) {
echo '<article><h2>';
$event->post_title;
echo '<span>';
/*get location of event*/
$args2 = array(
'post_type' => 'location',
'meta_key' => '_location_ID',
'meta_value' => get_post_meta($event->ID,'_location_ID')
);
$locations = get_posts( $args2 );
foreach($locations as $location ) {
echo $location->post_title;
}
echo '</span></h2></article>';
}