Skip to content

Commit

Permalink
Initial commit
Browse files Browse the repository at this point in the history
  • Loading branch information
rafalfaro18 committed Nov 8, 2018
0 parents commit 5644224
Show file tree
Hide file tree
Showing 2 changed files with 89 additions and 0 deletions.
52 changes: 52 additions & 0 deletions my-first-dynamic-gutenberg-block.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
<?php
/**
* Created by PhpStorm.
* User: rafalfaro
* Date: 07/11/18
* Time: 08:48
*
* @package WordPress
*
* Plugin Name: My First Dynamic Gutenberg Block
*/

/**
* Renders the block content
*
* @param array $attributes block attributes.
* @param array $content block content.
*
* @return string Rendered block markup
*/
function my_plugin_render_block_latest_post( $attributes, $content ) {
$recent_posts = wp_get_recent_posts(
array(
'numberposts' => 1,
'post_status' => 'publish',
)
);
if ( count( $recent_posts ) === 0 ) {
return 'No posts';
}
$post = $recent_posts[0];
$post_id = $post['ID'];
return sprintf(
'<a class="wp-block-my-plugin-latest-post" href="%1$s">%2$s</a>',
esc_url( get_permalink( $post_id ) ),
esc_html( get_the_title( $post_id ) )
);
}

wp_register_script(
'my-first-dynamic-gutenberg-block-script',
plugins_url( 'myblock.js', __FILE__ ),
array( 'wp-blocks', 'wp-element' )
);

register_block_type(
'my-first-dynamic-gutenberg-block/latest-post',
array(
'editor_script' => 'my-first-dynamic-gutenberg-block-script',
'render_callback' => 'my_plugin_render_block_latest_post',
)
);
37 changes: 37 additions & 0 deletions myblock.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
var el = wp.element.createElement,
registerBlockType = wp.blocks.registerBlockType,
withSelect = wp.data.withSelect;

registerBlockType( 'my-first-dynamic-gutenberg-block/latest-post', {
title: 'Latest Post Custom Block',
icon: 'megaphone',
category: 'widgets',

edit: withSelect( function( select ) {
return {
posts: select( 'core' ).getEntityRecords( 'postType', 'post' )
};
} )( function( props ) {

if ( ! props.posts ) {
return "Loading...";
}

if ( props.posts.length === 0 ) {
return "No posts";
}
var className = props.className;
var post = props.posts[ 0 ];

return el(
'a',
{ className: className, href: post.link },
post.title.rendered
);
} ),

save: function() {
// Rendering in PHP
return null;
},
} );

0 comments on commit 5644224

Please sign in to comment.