-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathrather-simple-polylang-free-extras.php
More file actions
309 lines (264 loc) · 8.96 KB
/
rather-simple-polylang-free-extras.php
File metadata and controls
309 lines (264 loc) · 8.96 KB
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
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
<?php
/**
* Plugin Name: Rather Simple Polylang Free Extras
* Plugin URI:
* Update URI: false
* Version: 1.0
* Requires at least: 6.8
* Requires PHP: 7.4
* Requires Plugins: polylang
* Author: Oscar Ciutat
* Author URI: http://oscarciutat.com/code/
* Text Domain: rather-simple-polylang-free-extras
* Domain Path: /languages
* Description: Enhances the free version of Polylang with basic REST API support, a language filter for block-based widgets and basic localization for block template parts.
* License: GPLv2 or later
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License, version 2, as
* published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*
* @package rather_simple_polylang_free_extras
*/
/**
* Core class used to implement the plugin.
*/
class Rather_Simple_Polylang_Free_Extras {
/**
* Plugin instance.
*
* @var object $instance
*/
protected static $instance = null;
/**
* Access this plugin’s working instance.
*/
public static function get_instance() {
if ( ! self::$instance ) {
self::$instance = new self();
}
return self::$instance;
}
/**
* Used for regular plugin work.
*/
public function plugin_setup() {
add_action( 'enqueue_block_editor_assets', array( $this, 'enqueue_block_editor_assets' ) );
add_action( 'rest_api_init', array( $this, 'rest_api_init' ) );
add_filter( 'register_block_type_args', array( $this, 'register_block_type_args' ), 10, 2 );
add_filter( 'render_block', array( $this, 'render_block' ), 10, 2 );
add_filter( 'pre_get_block_template', array( $this, 'get_localized_block_template_part' ), 10, 3 );
}
/**
* Constructor. Intentionally left empty and public.
*/
public function __construct() {}
/**
* Enqueues block editor assets
*
* @throws Error If block is not built.
*/
public function enqueue_block_editor_assets() {
$current_screen = get_current_screen();
// Only proceed if we are on the block-based widgets screen.
if ( 'widgets' !== $current_screen->base || ! $current_screen->is_block_editor ) {
return;
}
$dir = __DIR__;
$script_asset_path = "$dir/build/index.asset.php";
if ( ! file_exists( $script_asset_path ) ) {
throw new Error(
'You need to run `npm start` or `npm run build` for the block first.'
);
}
$script_asset = require $script_asset_path;
// Load styles.
wp_enqueue_style(
'rather-simple-polylang-free-extras-css',
plugins_url( 'build/index.css', __FILE__ ),
array(),
filemtime( plugin_dir_path( __FILE__ ) . 'build/index.css' )
);
// Load scripts.
wp_enqueue_script(
'rather-simple-polylang-free-extras',
plugins_url( 'build/index.js', __FILE__ ),
$script_asset['dependencies'],
filemtime( plugin_dir_path( __FILE__ ) . 'build/index.js' ),
array(
'in_footer' => true,
'strategy' => 'defer',
)
);
// Translate scripts.
wp_set_script_translations( 'rather-simple-polylang-free-extras', 'rather-simple-polylang-free-extras', plugin_dir_path( __FILE__ ) . 'languages' );
}
/**
* Initializes REST API filters for Polylang language support.
*/
public function rest_api_init() {
// Loop through all post types enabled for REST.
foreach ( get_post_types( array( 'show_in_rest' => true ) ) as $post_type ) {
// Check if Polylang is actually managing translations for this post type.
if ( function_exists( 'pll_is_translated_post_type' ) && ! pll_is_translated_post_type( $post_type ) ) {
continue;
}
add_filter(
"rest_{$post_type}_query",
array( $this, 'rest_polylang_apply_lang' ),
10,
2
);
}
// Loop through all taxonomies enabled for REST.
foreach ( get_taxonomies( array( 'show_in_rest' => true ) ) as $taxonomy ) {
// Check if Polylang is actually managing translations for this taxonomy.
if ( function_exists( 'pll_is_translated_taxonomy' ) && ! pll_is_translated_taxonomy( $taxonomy ) ) {
continue;
}
add_filter(
"rest_{$taxonomy}_query",
array( $this, 'rest_polylang_apply_lang' ),
10,
2
);
}
}
/**
* Applies Polylang language filter to REST API queries.
*
* @param array $args The REST API query arguments.
* @param WP_REST_Request $request The current REST API request.
* @return array Modified query arguments with language applied.
*/
public function rest_polylang_apply_lang( $args, $request ) {
// Ensure Polylang is active.
if ( ! function_exists( 'pll_languages_list' ) ) {
return $args;
}
// Extract the 'lang' parameter from the request.
$lang = $request->get_param( 'lang' );
// If no language is specified, use the site default language.
if ( ! $lang ) {
$lang = pll_default_language();
}
// Ensure the language code is actually registered in Polylang.
if ( ! in_array( $lang, pll_languages_list(), true ) ) {
return $args;
}
// Add the language to the query.
$args['lang'] = $lang;
return $args;
}
/**
* Adds a 'pll_lang' attribute to all blocks,
* including server-side rendered blocks.
* Using 'pll_lang' for consistency with Polylang Pro.
*
* Gutenberg only registers attributes for SSR blocks on the server.
* Without this filter, attributes added via `blocks.registerBlockType`
* in JavaScript would be ignored during rendering.
*
* @param array $args Array of arguments for registering a block type.
* @param string $block_name Block name including namespace.
*
* @return array Modified block type arguments.
*/
public function register_block_type_args( $args, $block_name ) {
// List of blocks to exclude.
$excluded_blocks = array(
'core/widget-area',
'core/legacy-widget',
);
// If this is an excluded block, return args unchanged.
if ( in_array( $block_name, $excluded_blocks, true ) ) {
return $args;
}
// Ensure the 'attributes' key exists in the args array to avoid errors.
if ( ! isset( $args['attributes'] ) ) {
$args['attributes'] = array();
}
// Add the 'pll_lang' attribute into the block schema.
$args['attributes']['pll_lang'] = array(
'type' => 'string',
'default' => '',
);
return $args;
}
/**
* Toggles block display based on the 'pll_lang' value.
*
* @param string $block_content The original block content.
* @param array $block The full block, including name and attributes.
* @return string The filtered block content.
*/
public function render_block( $block_content, $block ) {
global $post;
// Ensure we are on a valid post and Polylang is active.
if ( ! $post instanceof WP_Post || ! function_exists( 'pll_get_post_language' ) ) {
return $block_content;
}
// Extract the 'pll_lang' attribute from the block.
$pll_lang = $block['attrs']['pll_lang'] ?? '';
if ( '' !== $pll_lang ) {
// Get the language slug of the current post.
$post_language = pll_get_post_language( $post->ID, 'slug' );
// If the post language doesn't match the block language, hide the block.
if ( $post_language !== $pll_lang ) {
return '';
}
}
return $block_content;
}
/**
* Loads a localized version of the block template part if available.
*
* @param object $template The template object.
* @param string $id The template ID.
* @param string $template_type The template type.
* @return object The localized template or the original template.
*/
public function get_localized_block_template_part( $template, $id, $template_type ) {
// Make sure Polylang exists.
if ( ! function_exists( 'pll_current_language' ) ) {
return $template;
}
// Only target template parts.
if ( 'wp_template_part' !== $template_type ) {
return $template;
}
$lang = pll_current_language();
if ( ! $lang ) {
return $template;
}
// $id format: theme_slug//slug
$parts = explode( '//', $id );
if ( count( $parts ) !== 2 ) {
return $template;
}
list( $theme, $slug ) = $parts;
$localized_slug = "{$slug}__{$lang}";
$localized_id = "{$theme}//{$localized_slug}";
// Prevent recursion.
remove_filter( 'pre_get_block_template', array( self::get_instance(), 'get_localized_block_template_part' ), 10 );
// Try to load localized version.
$localized_template_part = get_block_template( $localized_id, $template_type );
// Re-add filter.
add_filter( 'pre_get_block_template', array( self::get_instance(), 'get_localized_block_template_part' ), 10, 3 );
if ( $localized_template_part ) {
return $localized_template_part;
}
// Fallback to original.
return $template;
}
}
add_action( 'plugins_loaded', array( Rather_Simple_Polylang_Free_Extras::get_instance(), 'plugin_setup' ) );