0

I am quite new to block development and react. I am trying to make a block which shows a list of custom posts of choice. I as able to create attributes to save user preferences like post type, count, status, etc. Now I want to fetch the posts. Where I am not sure if should use php endpoint or WP JSON API to fetch posts? I saw in may places they are either using some custom php endpoint or just using the render_callback to call php function which takes care of fetching and showing posts. Is there any downsides using the REST API with JS rather than fetching in good old WP_Query way?

import './editor.scss';
import './style.scss';

const { __ } = wp.i18n; // Import __() from wp.i18n
const { registerBlockType } = wp.blocks; // Import registerBlockType() from wp.blocks

registerBlockType( 'cgb/block-myposts', {
    title: __( 'myposts - CGB Block' ),
    icon: 'shield',
    category: 'common',
    keywords: [
        __( 'myposts — CGB Block' ),
        __( 'CGB Example' ),
        __( 'create-guten-block' ),
    ],

    edit: ( props ) => {
        // I want to fetch posts here and show
    },

    save: ( props ) => {
        return null;
    },
} );

1 Answer 1

1

A few things I noticed. The edit area of the block only shows up in the editor - not the front end. The save area is where you want to add posts that show up on the front end.

Personally, I would go with jQuery / AJAX / and JSON for this. (so you would be using the Wp JSON API).

I would do something like this:

const {__} =  wp.i18n;

( function( blocks, element ) {
    var el = element.createElement;

    blocks.registerBlockType( 'cgb/block-myposts', {
    title: __( 'myposts - CGB Block' ),
    icon: 'shield',
    category: 'common',
    keywords: [
        __( 'myposts — CGB Block' ),
        __( 'CGB Example' ),
        __( 'create-guten-block' ),
    ],

    edit: function(props) {
            return (
                el( 'div', { className: props.className },
                    el('div', {'class': 'postarea'})))},

    save: function(props) {
            return (
                el( 'div', { className: props.className},
                    el('div', {'class': 'postarea'}
)))} );
}(
    window.wp.blocks,
    window.wp.element
) );

Feel free to add as you need for your exact project. Just remember the save area is the area that will show up on the front end. After this, you will use jQuery to retrieve the class: postarea and insert the posts you want.

There are a few ways to solve this problem - depending on the user experience you want.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.