-
Notifications
You must be signed in to change notification settings - Fork 0
/
query-loop-shortcode.php
77 lines (65 loc) · 2.26 KB
/
query-loop-shortcode.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
67
68
69
70
71
72
73
74
75
76
77
<?php
/**
* Plugin Name: Query Loop Shortcode
* Description: Display a shortcode within a query loop based on the loop ID, not the parent post/page ID.
* Requires at least: 6.1
* Requires PHP: 7.0
* Version: 0.1.1
* Author: Ted Tang
* License: GPL-2.0-or-later
* License URI: https://www.gnu.org/licenses/gpl-2.0.html
* Text Domain: query-loop-shortcode
*
* @package QueryLoopShortCode
*/
namespace QueryLoopShortcode;
// Exit if accessed directly.
defined( 'ABSPATH' ) || exit;
if ( ! defined( 'QLSC_ROOT_FILE' ) ) {
define( 'QLSC_ROOT_FILE', __FILE__ );
}
/**
* Registers the block using the metadata loaded from the `block.json` file.
* Behind the scenes, it registers also all assets so they can be enqueued
* through the block editor in the corresponding context.
*
* @see https://developer.wordpress.org/reference/functions/register_block_type/
*/
function create_block_query_loop_shortcode_block_init() {
register_block_type( __DIR__ . '/build' , [ 'render_callback' => __NAMESPACE__ . '\\query_loop_shortcode_render_block' ]);
}
add_action( 'init', __NAMESPACE__ . '\\create_block_query_loop_shortcode_block_init' );
/**
* Renders the `qlsc/query-loop-shortcode` block on the server.
*
* @param array $attributes Block attributes.
* @param string $content Block default content.
* @param WP_Block $block Block instance.
* @return string Returns the filtered post meta field for the current post.
*/
function query_loop_shortcode_render_block( $attributes, $content, $block ) {
if ( isset( $block->context['postId'] ) ) {
// Get post_id from the context first.
$post_id = $block->context['postId'];
} else {
// Fallback to the current post id.
$post_id = get_queried_object_id();
}
$shortcode = $content ?? '';
if ( empty( $shortcode ) ) {
return '';
}
global $wp_query;
$restore = $wp_query;
$wp_query = null;
$args = array(
'p' => $post_id, // ID of a page, post, or custom type
'post_type' => 'any'
);
$wp_query = new \WP_Query($args);
$content = do_shortcode($shortcode);
$wp_query = $restore;
// Get the block markup.
return $content;
//return query_loop_shortcode_get_block_markup( $content, $attributes, $block, $post_id, $classes );
}