Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save AliNaraghiA/f1193e437f19c5b2efc7dfb1b664afe9 to your computer and use it in GitHub Desktop.
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
<?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 );
}
?>
@AliNaraghiA
Copy link
Author

more information

@AliNaraghiA
Copy link
Author

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;

$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,
        'slug' => $post->post_name,
        'excerpt' => $post->post_excerpt,
        'featured_image' => get_the_post_thumbnail_url( $post->ID ),
        'content' => $post->post_content,
        'date' => $post->post_date,
    );
}

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