Wordpress JSON

<?php header ("Content-Type:application/json"); function show_categories($post){ $categories = get_the_category($post->ID); $catnames = []; foreach ($categories as $cat) { $catnames[] = esc_html($cat->cat_name); } $catnames[] = "All"; return $catnames; } $args = array('post_type' => 'videos', 'posts_per_page' => -1, 'orderby'=>"date", 'order'=>"asc"); $postType = new WP_Query( $args ); if( $postType->have_posts() ) { $data = []; while( $postType->have_posts() ) { $postType->the_post(); $data_elem = array( "id" => basename(get_permalink()), "title": get_field('title'), "pubDate": get_field('date'), "thumbURL": get_field('thumb_url'), "imgURL": get_field('thumb_url'), "videoURL": get_field('video_url'), "categories": show_categories($post), "description": get_field('description') ); $data[] = $data_elem; } }
Used in conjunction with ACF (Advanced Custom Fields) this will output a JASON array. Place this inside your index.php or whatever template you would like to use this on.

Be the first to comment

You can use [html][/html], [css][/css], [php][/php] and more to embed the code. Urls are automatically hyperlinked. Line breaks and paragraphs are automatically generated.