-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmy-first-dynamic-gutenberg-block.php
66 lines (59 loc) · 1.45 KB
/
my-first-dynamic-gutenberg-block.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
<?php
/**
* Created by PhpStorm.
* User: rafalfaro
* Date: 07/11/18
* Time: 08:48
*
* @package WordPress
*
* Plugin Name: My First Dynamic Gutenberg Block
*/
/**
* Registers block and required scripts
*/
function register_dynamic_block_action() {
wp_register_script(
'my-first-dynamic-gutenberg-block-script',
plugins_url( 'myblock.js', __FILE__ ),
array( 'wp-blocks', 'wp-element' ),
true
);
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',
)
);
}
add_action( 'init', 'register_dynamic_block_action' );
/**
* Renders the block content
*
* @param array $atts block attributes.
*
* @return string Rendered block markup
*/
function my_plugin_render_block_latest_post( $atts ) {
$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'];
if ( function_exists( 'get_field' ) ) {
$cf = get_field( 'just_a_test' , $post_id ) ? get_field( 'just_a_test' , $post_id ) : '';
}
return sprintf(
'<span>'.$cf.'</span><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 ) )
);
}
add_action( 'init', 'my_plugin_render_block_latest_post' );