Created
June 8, 2023 07:36
-
-
Save AliNaraghiA/f1193e437f19c5b2efc7dfb1b664afe9 to your computer and use it in GitHub Desktop.
returns custom api with category *chanfe the Fa to any thing you want. i use this for multiple language site
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 | |
/** | |
* Plugin Name:Ali Custom API | |
* Plugin URI: | |
* Description: Crushing | |
* Version: 1.0 | |
* Author: Ali | |
* Author URI: | |
*/ | |
add_action( 'rest_api_init', 'register_custom_endpoints' ); | |
function register_custom_endpoints() { | |
register_rest_route( 'myplugin/v1', '/posts-by-category/', array( | |
'methods' => 'GET', | |
'callback' => 'get_posts_by_category', | |
) ); | |
} | |
function get_posts_by_category( $request ) { | |
$category_name = 'Fa'; | |
$category = get_category_by_slug( $category_name ); | |
$category_id = $category->term_id; | |
$args = array( | |
'category' => $category_id, | |
'posts_per_page' => -1, | |
); | |
$posts = get_posts( $args ); | |
$data = array(); | |
foreach ( $posts as $post ) { | |
$data[] = array( | |
'id' => $post->ID, | |
'title' => $post->post_title, | |
'content' => $post->post_content, | |
); | |
} | |
return new WP_REST_Response( $data, 200 ); | |
} | |
?> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
add_action( 'rest_api_init', 'register_custom_endpoints' );
function register_custom_endpoints() {
register_rest_route( 'myplugin/v1', '/posts-by-category/', array(
'methods' => 'GET',
'callback' => 'get_posts_by_category',
) );
}
function get_posts_by_category( $request ) {
$category_name = 'En';
$category = get_category_by_slug( $category_name );
$category_id = $category->term_id;
}