Next and Previous Post

Hi All, I am just exploring frontity for an upcoming website. Its basically like an ebook design where we have various chapters organized as posts and we need the functionality of next and previous post so that user can just click and he can read next or come back to previous post.

Also can you refer something about how to include breadcrumbs in post.

Gratitude and love from India!

Hi @sumankocher3

Welcome to the community.

The WordPress REST API does not include next/previous links in the JSON response by default. You will need to add them to the REST API yourself.

You can do that by adding the following PHP code to a custom plugin, or to your theme’s functions.php file:

add_filter( 'rest_prepare_post', 'add_prev_next_to_rest' , 10, 3 );

function add_prev_next_to_rest( $response, $post, $request ) {
    global $post;
    // Get the next post.
    $next = get_adjacent_post( false, '', false );
    // Get the previous post.
    $previous = get_adjacent_post( false, '', true );
    // Only send id and slug (or null, if there is no next/previous post).
    $response->data['next'] = ( is_a( $next, 'WP_Post') ) ? array( "id" => $next->ID, "slug" => $next->post_name ) : null;
    $response->data['previous'] = ( is_a( $previous, 'WP_Post') ) ? array( "id" => $previous->ID, "slug" => $previous->post_name ) : null;

    return $response;
}

This will add something similar to this in the returned JSON which you can access from your JS code:

next: {
id: 14,
slug: "san-francisco"
},
previous: {
id: 5,
slug: "chicago"
},

Hope this helps. Do please let us know what you’re building with Frontity. Post a link so we can see your site.

Thanks ! Gratitude again, just trying to learn with all of your help. Hope to build first prototype soon.

Can you also guide about the breadcrumbs ?

Hi @sumankocher3

What do you want to do with breadcrumbs? Breadcrumbs are usually used to indicate a category hierarchy.

What have you already tried?

Yes my posts have categories, subcategories and subcategories so wanted to show user.

Is fetching subcategories different then fetching categories?

Hi @sumankocher3

No, when the posts are fetched all category and sub-category IDs are included in the returned JSON. However, the hierarchy is not preserved, so when you construct your breadcrumbs you will need to know which category ID is a sub-category of which other category ID by looking in the WP admin pages.

Thanks a zillion ! I have noticed a issue here, my category names are in non English in my regional language and when I try to just copy it, its not accepted but when I put its url version its accepted like :

(Original Category : Not Accepted )

category/रामधारी-सिंह-दिनकर/

(This is accepted)

category/%e0%a4%b0%e0%a4%be%e0%a4%ae%e0%a4%a7%e0%a4%be%e0%a4%b0%e0%a5%80-%e0%a4%b8%e0%a4%bf%e0%a4%82%e0%a4%b9-%e0%a4%a6%e0%a4%bf%e0%a4%a8%e0%a4%95%e0%a4%b0/

Is this a standard behaviour with non English links or I am doing something wrong?