Last active
December 22, 2019 01:50
-
-
Save stnc/f01362f2e7f2f8086a9e4c652e1e08ae to your computer and use it in GitHub Desktop.
wordpress categories with it depends posts (for api)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/** | |
* uses : http://examplewp.com/wp-json/wp/v2/categoriesAndDepencyPostList | |
* Registers REST API endpoints -- for accordion tab and categories with it depends posts | |
* | |
* @since 1.0.0 | |
*/ | |
add_action('rest_api_init', 'register_categoriesAndDepencyPostList1'); | |
function register_categoriesAndDepencyPostList1() | |
{ | |
register_rest_route('wp/v2', '/categoriesAndDepencyPostList/', | |
array( | |
'methods' => 'GET', | |
'callback' => 'categoriesAndDepencyPostList1', | |
'permission_callback' => function ($request) { | |
return is_user_logged_in(); | |
}, | |
) | |
); | |
} | |
/** | |
* Gets categories and depency post list | |
* | |
* @since 6.2.0 | |
* @param WP_REST_Request $request The request sent from WP REST API. | |
* @return array Gets quiz list | |
*/ | |
function categoriesAndDepencyPostList1 (WP_REST_Request $request) | |
{ | |
// print_r($request->get_params()); | |
$categories = get_categories(array( | |
'orderby' => 'id', | |
'order' => 'ASC', | |
)); | |
$data = []; | |
$i = 0; | |
foreach ($categories as $key_ => $category) { | |
$posts_args = array( | |
'category__and' => array($category->term_id), | |
'post_status' => 'publish', | |
'orderby' => 'id', | |
'order' => 'ASC', | |
'no_found_rows' => true, | |
); | |
// The Featured Posts query. | |
$posts = new WP_Query($posts_args); | |
$posts = $posts->get_posts(); | |
foreach ($posts as $key2 => $post) { | |
$random = substr(md5(mt_rand()), 0, 3); | |
$data[$i]['catId'] = $category->term_id; | |
$data[$i]['catTitle'] = $category->name; | |
$data[$i]['key'] = 'st' . $random; | |
$data[$i]['posts'][$key2]['postId'] = $post->ID; | |
$data[$i]['posts'][$key2]['title'] = get_the_title($post->ID); | |
} | |
// Reset the post data | |
wp_reset_postdata(); | |
$i++; | |
} | |
return $data; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment