"] shortcode. * * @package Revys */ if ( ! defined( 'ABSPATH' ) ) { exit; } /** * Registers and renders the reviews shortcode. */ class Revys_Shortcode { /** * Hook registration + front-end styles. * * @return void */ public static function init() { add_shortcode( 'revys_reviews', array( __CLASS__, 'render' ) ); add_action( 'wp_enqueue_scripts', array( __CLASS__, 'register_styles' ) ); } /** * Register the legacy front-end stylesheet, and enqueue the styles of the * widgets used in the queried post (shortcode or block) so they are * printed in the head. Widgets rendered elsewhere enqueue their styles at * render time (Revys_Render::enqueue_assets). * * @return void */ public static function register_styles() { wp_register_style( 'revys-front', REVYS_PLUGIN_URL . 'assets/revys.css', array(), REVYS_VERSION ); if ( ! is_singular() ) { return; } $post = get_queried_object(); if ( ! $post instanceof WP_Post ) { return; } foreach ( self::widget_ids_in( (string) $post->post_content ) as $widget_id ) { Revys_Render::enqueue_assets( $widget_id ); } } /** * Widget ids used in a post content: `[revys_reviews widget="…"]` * shortcodes and `revys/reviews` blocks (nested blocks included). * * @param string $content Post content. * @return string[] */ public static function widget_ids_in( $content ) { $ids = array(); if ( false !== strpos( $content, '[revys_reviews' ) && preg_match_all( '/' . get_shortcode_regex( array( 'revys_reviews' ) ) . '/', $content, $matches, PREG_SET_ORDER ) ) { foreach ( $matches as $m ) { if ( '[' === $m[1] && ']' === $m[6] ) { continue; // Escaped shortcode `[[revys_reviews]]`. } $atts = shortcode_parse_atts( $m[3] ); if ( is_array( $atts ) && ! empty( $atts['widget'] ) ) { $ids[] = sanitize_text_field( (string) $atts['widget'] ); } } } if ( has_block( 'revys/reviews', $content ) ) { $stack = parse_blocks( $content ); while ( $stack ) { $block = array_shift( $stack ); if ( 'revys/reviews' === $block['blockName'] && ! empty( $block['attrs']['widget'] ) ) { $ids[] = sanitize_text_field( (string) $block['attrs']['widget'] ); } if ( ! empty( $block['innerBlocks'] ) ) { $stack = array_merge( $stack, $block['innerBlocks'] ); } } } return array_values( array_unique( array_filter( $ids ) ) ); } /** * Render the shortcode. * * @param array $atts Shortcode attributes. * @return string */ public static function render( $atts ) { $atts = shortcode_atts( array( 'widget' => '', ), $atts, 'revys_reviews' ); $widget_id = sanitize_text_field( (string) $atts['widget'] ); if ( '' === $widget_id ) { return ''; } // Styles are enqueued by Revys_Render (see register_styles above). return Revys_Render::render( $widget_id ); } }