-
Notifications
You must be signed in to change notification settings - Fork 0
/
example-query-loop-button.php
62 lines (52 loc) · 2.11 KB
/
example-query-loop-button.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
<?php
/**
* Plugin Name: Example Query Loop Button
* Description: Example block extension that allows button blocks to link to permalinks and custom fields.
* Requires at least: 6.4
* Requires PHP: 8.0
* Version: 0.1.0
* Author: bacoords
* License: GPL-2.0-or-later
* License URI: https://www.gnu.org/licenses/gpl-2.0.html
* Text Domain: example-query-loop-button
*
* @package create-block
*/
namespace example_query_loop_button;
use WP_HTML_Tag_Processor;
/**
* Enqueue specific modifications for the block editor.
*
* @return void
*/
function wpdev_enqueue_editor_modifications() {
$asset_file = include plugin_dir_path( __FILE__ ) . 'build/index.asset.php';
wp_enqueue_script( 'example-query-loop-button', plugin_dir_url( __FILE__ ) . 'build/index.js', $asset_file['dependencies'], $asset_file['version'], true );
}
add_action( 'enqueue_block_editor_assets', __NAMESPACE__ . '\wpdev_enqueue_editor_modifications' );
/**
* Filter button blocks for possible link attributes
*
* @param string $block_content The block content about to be rendered.
* @param array $block The full block, including name and attributes.
* @return string
*/
function filter_button_block_render_block( $block_content, $block ) {
if ( isset( $block['attrs']['isPostLink'] ) && 'permalink' === $block['attrs']['isPostLink'] ) {
$p = new WP_HTML_Tag_Processor( $block_content );
if ( $p->next_tag( 'a' ) ) {
$p->set_attribute( 'href', get_permalink() );
$p->set_attribute( 'rel', 'bookmark' );
$block_content = $p->get_updated_html();
}
}
if ( isset( $block['attrs']['isPostLink'] ) && 'custom_field' === $block['attrs']['isPostLink'] && isset( $block['attrs']['customFieldName'] ) ) {
$p = new WP_HTML_Tag_Processor( $block_content );
if ( $p->next_tag( 'a' ) ) {
$p->set_attribute( 'href', get_post_meta( get_the_ID(), $block['attrs']['customFieldName'], true ) );
$block_content = $p->get_updated_html();
}
}
return $block_content;
}
add_filter( 'render_block_core/button', __NAMESPACE__ . '\filter_button_block_render_block', 10, 2 );