-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathwp-reverse-title.php
More file actions
510 lines (456 loc) · 18.5 KB
/
Copy pathwp-reverse-title.php
File metadata and controls
510 lines (456 loc) · 18.5 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
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
<?php
/**
* Plugin Name: Reverse Title
* Description: Reverses the page title and site name on posts, pages, and custom post types and introduces a user-configurable custom separator.
* Version: 1.0.3
* Author: Christefano Reyes
* Plugin URI: https://github.com/christefano/wp-reverse-title/
* Author URI: https://github.com/christefano/
* Text Domain: wp-reverse-title
* License: GPL v2 or later
* License URI: https://www.gnu.org/licenses/gpl-2.0.html
* Requires at least: 5.0
* Requires PHP: 7.4
* Tested up to: 6.7
*/
if ( ! defined( 'ABSPATH' ) ) {
exit;
}
define( 'WP_REVERSE_TITLE_VERSION', '1.0.3' );
define( 'WP_REVERSE_TITLE_OPT_OUT_KEY', '_wp_reverse_title_opt_out' );
define( 'WP_REVERSE_TITLE_BASENAME', plugin_basename( __FILE__ ) );
register_uninstall_hook( __FILE__, 'wp_reverse_title_uninstall' );
// ---------------------------------------------------------------------------
// Title reversal (front-end filters - intentionally outside is_admin())
// ---------------------------------------------------------------------------
add_filter( 'document_title_separator', 'wp_reverse_title_separator' );
add_filter( 'document_title_parts', 'wp_reverse_title_parts' );
/**
* Returns whether title reversal should apply on the current request.
*
* Cached in a static variable since both document_title_separator and
* document_title_parts need this result within the same page load.
*
* Accepts a $refresh parameter to bust the cache, which is needed in
* WP-CLI, PHPUnit, or any multi-request scenario sharing a PHP process.
*
* Uses get_queried_object_id() rather than get_the_ID() for the post meta
* lookup, since get_the_ID() relies on the global $post loop state which
* may not be set in all contexts (e.g. REST API title generation).
*
* @param bool $refresh Force recompute even if already cached.
* @return bool
*/
function wp_reverse_title_should_reverse( $refresh = false ) {
static $result = null;
if ( $refresh || null === $result ) {
$singular = is_singular();
$opted_out = $singular && (bool) get_post_meta( get_queried_object_id(), WP_REVERSE_TITLE_OPT_OUT_KEY, true );
// Archives, search, and 404 titles are only reversed when the site-wide
// setting is enabled. is_home() covers the blog posts index when a static
// front page is set; is_front_page() is always excluded below.
$reverse_archives = (bool) get_option( 'wp_reverse_title_reverse_archives', false );
$archive_context = $reverse_archives && ( is_archive() || is_search() || is_404() || is_home() );
$result = (bool) apply_filters(
'wp_reverse_title_enabled',
! is_front_page() && ! $opted_out && ( $singular || $archive_context )
);
}
return $result;
}
/**
* Replaces the default title separator when a reversal is active on the
* current request. Registered before document_title_parts because WordPress
* calls document_title_separator first inside wp_get_document_title().
*
* Also applies the custom separator on the front page when the site has a
* tagline set under Settings -> General, keeping the separator consistent
* across the whole site without affecting the title order on the front page.
*
* Note: sanitize_text_field() is used on save and will silently strip
* anything that looks like an HTML tag (e.g. "<3" becomes empty). This is
* intentional - the separator renders inside a <title> tag.
*
* Only called by WordPress via the document_title_separator filter, which
* runs inside wp_get_document_title() before document_title_parts.
*
* @param string $sep The current separator.
* @return string The custom separator, or the original if none is set or no reversal is happening.
*/
function wp_reverse_title_separator( $sep ) {
$custom_sep = trim( get_option( 'wp_reverse_title_separator', '' ) );
$applies = wp_reverse_title_should_reverse() ||
( '' !== $custom_sep && is_front_page() && '' !== trim( get_bloginfo( 'description' ) ) );
if ( ! $applies ) {
return $sep;
}
/**
* Filters the title separator used in reversed titles only.
* Also applies on the front page when the site has a tagline.
*
* @param string $custom_sep The separator from Settings, or empty string for WP default.
*/
$custom_sep = apply_filters( 'wp_reverse_title_separator', $custom_sep );
return ( '' !== $custom_sep ) ? $custom_sep : $sep;
}
/**
* Reverses the document title parts (e.g. "Post Title – Site Name" becomes
* "Site Name – Post Title") on any singular post, page, or custom post type,
* excluding the front page and any post with the per-post opt-out checked.
*
* The condition is passed through the 'wp_reverse_title_enabled' filter,
* allowing other plugins or themes to override the logic without modifying
* this file.
*
* The separator is handled in wp_reverse_title_separator() above, which runs
* first because WordPress calls document_title_separator before
* document_title_parts inside wp_get_document_title().
*
* array_reverse() is called with preserve_keys = true intentionally -
* WordPress assembles the <title> from array values in order, so key
* preservation is correct here.
*
* @param array $title Associative array of title parts from WordPress.
* @return array Modified (or unchanged) title parts array.
*/
function wp_reverse_title_parts( $title ) {
if ( ! wp_reverse_title_should_reverse() ) {
return $title;
}
return array_reverse( $title, true ); // true = preserve keys
}
// ---------------------------------------------------------------------------
// Plugin action links (Settings, README, View more details, Donate)
// ---------------------------------------------------------------------------
if ( is_admin() ) {
add_filter( 'plugin_action_links_' . WP_REVERSE_TITLE_BASENAME, 'wp_reverse_title_action_links' );
add_filter( 'plugin_row_meta', 'wp_reverse_title_row_meta', 10, 2 );
add_action( 'admin_menu', 'wp_reverse_title_add_settings_page' );
add_action( 'admin_init', 'wp_reverse_title_register_settings' );
add_action( 'add_meta_boxes', 'wp_reverse_title_add_meta_box' );
add_action( 'save_post', 'wp_reverse_title_save_meta_box' );
}
/**
* Adds Settings and README links to the plugin entry on the Plugins admin list.
*
* @param array $links Existing action links.
* @return array Modified action links with Settings and README prepended.
*/
function wp_reverse_title_action_links( $links ) {
$extra = array(
sprintf( '<a href="%s">%s</a>', esc_url( admin_url( 'options-general.php?page=wp-reverse-title' ) ), __( 'Settings', 'wp-reverse-title' ) ),
sprintf( '<a href="%s" target="_blank" rel="noopener noreferrer">%s</a>', esc_url( 'https://github.com/christefano/wp-reverse-title/blob/main/README.md' ), __( 'README', 'wp-reverse-title' ) ),
);
return array_merge( $extra, $links );
}
/**
* Adds View more details and Donate links to the plugin row meta on the Plugins admin list.
*
* @param array $links Existing row meta links.
* @param string $file Plugin file path being rendered.
* @return array Modified row meta links.
*/
function wp_reverse_title_row_meta( $links, $file ) {
if ( WP_REVERSE_TITLE_BASENAME !== $file ) {
return $links;
}
$links[] = sprintf(
'<a href="%s" target="_blank" rel="noopener noreferrer">%s</a>',
esc_url( 'https://github.com/christefano/wp-reverse-title/' ),
__( 'View more details', 'wp-reverse-title' )
);
$links[] = sprintf(
'<a href="%s" target="_blank" rel="noopener noreferrer">%s</a>',
esc_url( 'https://macchess.org/donate' ),
__( 'Donate', 'wp-reverse-title' )
);
return $links;
}
// ---------------------------------------------------------------------------
// Settings page (Settings -> Reverse Title)
// ---------------------------------------------------------------------------
/**
* Registers the Reverse Title settings page under the Settings menu.
*/
function wp_reverse_title_add_settings_page() {
add_options_page(
__( 'Reverse Title', 'wp-reverse-title' ),
__( 'Reverse Title', 'wp-reverse-title' ),
'manage_options',
'wp-reverse-title',
'wp_reverse_title_render_settings_page'
);
}
/**
* Registers the plugin settings with the WordPress Settings API.
*/
function wp_reverse_title_register_settings() {
register_setting(
'wp_reverse_title_settings',
'wp_reverse_title_separator',
array(
'type' => 'string',
'sanitize_callback' => 'sanitize_text_field',
'default' => '',
'autoload' => 'yes',
)
);
register_setting(
'wp_reverse_title_settings',
'wp_reverse_title_show_meta_box',
array(
'type' => 'boolean',
'sanitize_callback' => function( $value ) { return (bool) $value; },
'default' => true,
'autoload' => 'yes',
)
);
register_setting(
'wp_reverse_title_settings',
'wp_reverse_title_reverse_archives',
array(
'type' => 'boolean',
'sanitize_callback' => function( $value ) { return (bool) $value; },
'default' => false,
'autoload' => 'yes',
)
);
add_settings_section(
'wp_reverse_title_main',
'',
'__return_false',
'wp-reverse-title'
);
add_settings_field(
'wp_reverse_title_separator',
__( 'Custom separator', 'wp-reverse-title' ),
'wp_reverse_title_render_separator_field',
'wp-reverse-title',
'wp_reverse_title_main'
);
add_settings_field(
'wp_reverse_title_show_meta_box',
__( 'Per-post opt-out', 'wp-reverse-title' ),
'wp_reverse_title_render_meta_box_field',
'wp-reverse-title',
'wp_reverse_title_main'
);
add_settings_field(
'wp_reverse_title_reverse_archives',
__( 'Archives and search', 'wp-reverse-title' ),
'wp_reverse_title_render_archives_field',
'wp-reverse-title',
'wp_reverse_title_main'
);
}
/**
* Detects emoji (pictographic) characters in a string.
*
* Restricted to the high pictographic planes plus the emoji variation selector
* (U+FE0F) so that legitimate text-style symbols the plugin recommends - the
* chess bishop ♝, the middle dot ·, the pipe |, and the en dash – - are never
* flagged as emoji.
*
* @param string $str The string to test.
* @return bool True when the string contains at least one emoji character.
*/
function wp_reverse_title_has_emoji( $str ) {
return (bool) preg_match( '/[\x{1F000}-\x{1FAFF}\x{1F1E6}-\x{1F1FF}]|\x{FE0F}/u', $str );
}
/**
* Renders the custom separator input field with a live preview.
*/
function wp_reverse_title_render_separator_field() {
$value = get_option( 'wp_reverse_title_separator', '' );
?>
<input
type="text"
name="wp_reverse_title_separator"
id="wp_reverse_title_separator"
value="<?php echo esc_attr( $value ); ?>"
style="width: 300px;"
/>
<?php if ( wp_reverse_title_has_emoji( $value ) ) : ?>
<p class="description" style="color: #a00;">
<strong><?php esc_html_e( 'Warning:', 'wp-reverse-title' ); ?></strong>
<?php
printf(
/* translators: %s: link to the SearchPilot emoji title-tag case study. */
esc_html__( 'This separator contains an emoji. Emoji in title tags can cause a measurable drop in search traffic - see this %s. Unicode symbols like · or ♝ are safe.', 'wp-reverse-title' ),
'<a href="' . esc_url( 'https://www.searchpilot.com/resources/case-studies/seo-testing-lessons-emoji-title-tags' ) . '" target="_blank" rel="noopener noreferrer">' . esc_html__( 'case study', 'wp-reverse-title' ) . '</a>'
);
?>
</p>
<?php endif; ?>
<p class="description">
<?php esc_html_e( 'Replaces the default WordPress title separator (–) in reversed titles. Leave blank to use the WordPress default. Accepts any length of text - use this to add a custom tagline or slogan between your site name and page title.', 'wp-reverse-title' ); ?>
</p>
<p style="margin-top: 8px;">
<strong><?php esc_html_e( 'Preview:', 'wp-reverse-title' ); ?></strong>
<span id="wp_reverse_title_preview" style="font-family: monospace; margin-left: 6px;"></span>
</p>
<script>
( function() {
var input = document.getElementById( 'wp_reverse_title_separator' );
var preview = document.getElementById( 'wp_reverse_title_preview' );
var site = <?php echo wp_json_encode( get_bloginfo( 'name' ) ); ?>;
var example = <?php echo wp_json_encode( __( 'About', 'wp-reverse-title' ) ); ?>;
function updatePreview() {
var sep = input.value.trim();
preview.textContent = sep === ''
? site + ' \u2013 ' + example
: site + ' ' + sep + ' ' + example;
}
input.addEventListener( 'input', updatePreview );
updatePreview();
} )();
</script>
<?php
}
/**
* Renders the meta box enable/disable checkbox field.
*/
function wp_reverse_title_render_meta_box_field() {
$enabled = (bool) get_option( 'wp_reverse_title_show_meta_box', true );
?>
<label for="wp_reverse_title_show_meta_box">
<input
type="checkbox"
name="wp_reverse_title_show_meta_box"
id="wp_reverse_title_show_meta_box"
value="1"
<?php checked( $enabled ); ?>
/>
<?php esc_html_e( 'Show the opt-out meta box on all public post types', 'wp-reverse-title' ); ?>
</label>
<p class="description">
<?php esc_html_e( 'When enabled, a Reverse Title meta box appears in the editor sidebar allowing individual posts to opt out of title reversal.', 'wp-reverse-title' ); ?>
</p>
<?php
}
/**
* Renders the archives/search reversal enable/disable checkbox field.
*/
function wp_reverse_title_render_archives_field() {
$enabled = (bool) get_option( 'wp_reverse_title_reverse_archives', false );
?>
<label for="wp_reverse_title_reverse_archives">
<input
type="checkbox"
name="wp_reverse_title_reverse_archives"
id="wp_reverse_title_reverse_archives"
value="1"
<?php checked( $enabled ); ?>
/>
<?php esc_html_e( 'Also reverse titles on archives, search results, and 404 pages', 'wp-reverse-title' ); ?>
</label>
<p class="description">
<?php esc_html_e( 'By default only singular posts, pages, and custom post types are reversed. Enable this to also reverse category, tag, author, date, search, and 404 titles. The front page is always excluded.', 'wp-reverse-title' ); ?>
</p>
<?php
}
/**
* Renders the full Settings -> Reverse Title page.
*/
function wp_reverse_title_render_settings_page() {
if ( ! current_user_can( 'manage_options' ) ) {
return;
}
?>
<div class="wrap">
<!-- Reverse Title <?php echo esc_html( WP_REVERSE_TITLE_VERSION ); ?> -->
<h1><?php esc_html_e( 'Reverse Title', 'wp-reverse-title' ); ?></h1>
<form method="post" action="options.php">
<?php
settings_fields( 'wp_reverse_title_settings' );
do_settings_sections( 'wp-reverse-title' );
submit_button();
?>
</form>
</div>
<?php
}
// ---------------------------------------------------------------------------
// Per-post opt-out meta box (all public post types)
// ---------------------------------------------------------------------------
/**
* Registers the opt-out meta box on all public post types, including posts,
* pages, and any registered custom post types. Only runs when the per-post
* opt-out setting is enabled under Settings -> Reverse Title.
*/
function wp_reverse_title_add_meta_box() {
if ( ! get_option( 'wp_reverse_title_show_meta_box', true ) ) {
return;
}
$post_types = get_post_types( array( 'public' => true ), 'names' );
foreach ( $post_types as $post_type ) {
add_meta_box(
'wp_reverse_title_opt_out',
__( 'Reverse Title', 'wp-reverse-title' ),
'wp_reverse_title_render_meta_box',
$post_type,
'side',
'default'
);
}
}
/**
* Renders the opt-out checkbox inside the meta box.
*
* @param WP_Post $post The current post object.
*/
function wp_reverse_title_render_meta_box( $post ) {
wp_nonce_field( 'wp_reverse_title_meta_box', 'wp_reverse_title_nonce' );
$opted_out = (bool) get_post_meta( $post->ID, WP_REVERSE_TITLE_OPT_OUT_KEY, true );
?>
<label for="wp_reverse_title_opt_out">
<input
type="checkbox"
name="wp_reverse_title_opt_out"
id="wp_reverse_title_opt_out"
value="1"
<?php checked( $opted_out ); ?>
/>
<?php esc_html_e( "Don't reverse page title and site name for this post", 'wp-reverse-title' ); ?>
</label>
<?php
}
/**
* Saves the opt-out checkbox value when the post is saved.
*
* @param int $post_id The ID of the post being saved.
*/
function wp_reverse_title_save_meta_box( $post_id ) {
if (
( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE ) ||
wp_is_post_revision( $post_id ) ||
! isset( $_POST['wp_reverse_title_nonce'] ) ||
! wp_verify_nonce( sanitize_text_field( wp_unslash( $_POST['wp_reverse_title_nonce'] ) ), 'wp_reverse_title_meta_box' ) ||
! current_user_can( 'edit_post', $post_id )
) {
return;
}
$opt_out = isset( $_POST['wp_reverse_title_opt_out'] )
? sanitize_text_field( wp_unslash( $_POST['wp_reverse_title_opt_out'] ) )
: '';
if ( ! empty( $opt_out ) ) {
update_post_meta( $post_id, WP_REVERSE_TITLE_OPT_OUT_KEY, '1' );
} else {
delete_post_meta( $post_id, WP_REVERSE_TITLE_OPT_OUT_KEY );
}
}
// ---------------------------------------------------------------------------
// Uninstall
// ---------------------------------------------------------------------------
/**
* Cleans up plugin data on uninstall.
* Removes both plugin options and all per-post opt-out meta entries.
*
* @return void
*/
function wp_reverse_title_uninstall() {
delete_option( 'wp_reverse_title_separator' );
delete_option( 'wp_reverse_title_show_meta_box' );
delete_option( 'wp_reverse_title_reverse_archives' );
delete_post_meta_by_key( WP_REVERSE_TITLE_OPT_OUT_KEY );
}