JavaScript for WordPress › Forums › Gutenberg Development › Dynamic block not showing in frontend › Reply To: Dynamic block not showing in frontend
April 18, 2018 at 5:15 pm
#45350
Participant
My index.js
/**
* Block dependencies
*/
// import icon from './icon';
import './style.scss';
// import './editor.scss';
// import classnames from 'classnames';
/**
* Internal block libraries
*/
const { __ } = wp.i18n;
const { registerBlockType } = wp.blocks;
const { Spinner, withAPIData } = wp.components;
export default registerBlockType(
'gutenbergtest/dynamicblock',
{
title:__('Dynamic block'),
description:__('Dynamic block for gutenberg'),
icon: 'editor-alignright',
category: 'widgets',
keywords: [
__('dynamic'),
__('test')
],
edit: withAPIData( props => {
return {
posts: <code>/wp/v2/posts?per_page=3</code>
};
} )( ( { isSelected, className, setAttributes, posts } ) => {
if( ! posts.data ) {
return (
<p className={ className }>
<Spinner/>
{ __( 'Loading Posts', 'gutenbergtest' ) }
</p>
);
}
if( 0 === posts.data.length ) {
return <p>{ __( 'No Posts', 'gutenbergtest' ) }</p>;
}
return (
<ul className={ className }> {
posts.data.map( post => {
return (
<li>
<a className={ className } href={ post.link }>{ post.title.rendered }</a>
</li>
);
} ) }
</ul>
);
}),
save(){
return null;
},
});
My index.php file
<?php
/**
* Server rendering for /blocks/examples/12-dynamic
*/
function jsforwpblocks_dynamic_block_render( $attributes ) {
$recent_posts = wp_get_recent_posts( [
'numberposts' => 3,
'post_status' => 'publish',
] );
if ( 0 === count( $recent_posts ) ) {
return '<p>No posts</p>';
}
$markup = '<ul>';
foreach( $recent_posts as $post ) {
$post_id = $post['ID'];
$markup .= sprintf(
'<li><a href="%1$s">%2$s</a></li>',
esc_url( get_permalink( $post_id ) ),
esc_html( get_the_title( $post_id ) )
);
}
$markup .= '<ul>';
return $markup;
}
function jsforwpblocks_register_blocks() {
// Hook server side rendering into render callback
register_block_type( 'gutenbergtest/dynamicblock', [
'render_callback' => 'jsforwpblocks_dynamic_block_render',
] );
}
// Make sure that Gutenberg is available
if ( function_exists( 'register_block_type' ) ) {
add_action( 'init', 'jsforwpblocks_register_blocks' );
}
Load index.php in
include(plugin_dir_path(__FILE__) . 'blocks/test/dynamic/index.php');