Skip to content

Instantly share code, notes, and snippets.

@ribeirovictor
Last active June 18, 2019 23:18
Show Gist options
  • Select an option

  • Save ribeirovictor/b3e89471320327f3cf301c067623aa96 to your computer and use it in GitHub Desktop.

Select an option

Save ribeirovictor/b3e89471320327f3cf301c067623aa96 to your computer and use it in GitHub Desktop.

Revisions

  1. ribeirovictor revised this gist Jun 18, 2019. No changes.
  2. ribeirovictor revised this gist Jun 18, 2019. No changes.
  3. ribeirovictor revised this gist Jun 18, 2019. 1 changed file with 3 additions and 1 deletion.
    4 changes: 3 additions & 1 deletion functions.php
    Original file line number Diff line number Diff line change
    @@ -1,3 +1,5 @@
    <?php

    // API Posts

    function get_post_items() {
    @@ -28,4 +30,4 @@ function register_api_endpoints() {
    'callback' => 'get_post_items',
    ) );
    }
    add_action( 'rest_api_init', 'register_api_endpoints' );
    add_action( 'rest_api_init', 'register_api_endpoints' );
  4. ribeirovictor created this gist Jun 18, 2019.
    31 changes: 31 additions & 0 deletions functions.php
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,31 @@
    // API Posts

    function get_post_items() {
    $args = array (
    'post_status' => 'publish',
    'posts_per_page' => 3,
    );

    $items = array();

    if ( $posts = get_posts( $args ) ) {
    foreach ( $posts as $post ) {
    $items[] = array(
    'id' => $post->ID,
    'link' => get_permalink($post->ID),
    'title' => $post->post_title,
    'image' => wp_get_attachment_image_src(get_post_thumbnail_id($post->ID), "medium"),
    'teaser' => $post->post_excerpt
    );
    }
    }
    return $items;
    }

    function register_api_endpoints() {
    register_rest_route( 'api/v1', '/posts', array(
    'methods' => 'GET',
    'callback' => 'get_post_items',
    ) );
    }
    add_action( 'rest_api_init', 'register_api_endpoints' );