Initial import of 404 Enhacer

This commit is contained in:
2026-11-16 12:24:05 -05:00
commit cf03c388c3
15 changed files with 1724 additions and 0 deletions
+7
View File
@@ -0,0 +1,7 @@
node_modules/
dist/
.kilocode/
.env
.env.*
*.local
.DS_Store
+54
View File
@@ -0,0 +1,54 @@
<?php
/**
* Plugin Name: 404 Enhancer
* Plugin URI: https://example.com/404-enhancer
* Description: Enhances the 404 page with a custom message, featured image, hand-picked content, a search form, URL-based suggestions, cross-links and a "did you mean" hint.
* Version: 0.3
* Requires at least: 6.0
* Requires PHP: 7.4
* Author: Your Name
* Text Domain: 404-enhancer
* Domain Path: /languages
*
* @package 404_Enhancer
*/
if ( ! defined( 'ABSPATH' ) ) {
exit;
}
define( 'FE_VERSION', '0.3' );
define( 'FE_PLUGIN_FILE', __FILE__ );
define( 'FE_PLUGIN_DIR', plugin_dir_path( __FILE__ ) );
define( 'FE_PLUGIN_URL', plugin_dir_url( __FILE__ ) );
define( 'FE_SLUG', dirname( plugin_basename( __FILE__ ) ) );
require_once FE_PLUGIN_DIR . 'includes/class-fe-settings.php';
require_once FE_PLUGIN_DIR . 'includes/class-fe-suggestions.php';
require_once FE_PLUGIN_DIR . 'includes/class-fe-template.php';
require_once FE_PLUGIN_DIR . 'includes/class-fe-updater.php';
/**
* Loads the plugin text domain for translations.
*/
function fe_load_textdomain() {
load_plugin_textdomain( '404-enhancer', false, FE_SLUG . '/languages' );
}
add_action( 'plugins_loaded', 'fe_load_textdomain' );
/**
* Seeds default options on activation.
*/
function fe_activate() {
if ( false === get_option( 'fe_enabled_post_types' ) ) {
add_option( 'fe_enabled_post_types', array( 'post' ) );
}
if ( false === get_option( 'fe_suggestions_per_page' ) ) {
add_option( 'fe_suggestions_per_page', 6 );
}
}
register_activation_hook( __FILE__, 'fe_activate' );
FE_Settings::init();
FE_Template::init();
FE_Updater::init();
+26
View File
@@ -0,0 +1,26 @@
<?php
/**
* Temporary CLI test for the FE_Settings AJAX endpoint. Run as its own process
* because wp_send_json_* calls wp_die. NOT part of the plugin. Delete after running.
*/
error_reporting( E_ALL );
ini_set( 'display_errors', '0' ); // Keep output pure JSON.
define( 'WP_USE_THEMES', false );
define( 'DOING_AJAX', true );
require dirname( __DIR__, 3 ) . '/wp-load.php';
$admin_id = 1;
if ( ! get_userdata( $admin_id ) ) {
$admin_id = (int) get_users( array( 'role' => 'administrator', 'number' => 1, 'fields' => 'ID' ) )[0];
}
wp_set_current_user( $admin_id );
$_POST['s'] = 'hello';
$_POST['nonce'] = wp_create_nonce( 'fe_admin_nonce' );
$_REQUEST['nonce'] = $_POST['nonce'];
$_REQUEST['s'] = $_POST['s'];
$_REQUEST['action'] = 'fe_search_posts';
FE_Settings::ajax_search_posts(); // Echoes JSON and dies.
+19
View File
@@ -0,0 +1,19 @@
<?php
error_reporting( E_ALL );
ini_set( 'display_errors', '1' );
define( 'WP_USE_THEMES', true );
$_SERVER['REQUEST_URI'] = '/this-page-does-not-exist-2024/';
$_SERVER['REQUEST_METHOD'] = 'GET';
require dirname( __DIR__, 3 ) . '/wp-load.php';
echo "loaded WP " . get_bloginfo( 'version' ) . "\n";
echo "stylesheet: " . get_stylesheet() . "\n";
echo "template: " . get_template() . "\n";
$GLOBALS['wp_query']->set_404();
echo "is_404: " . var_export( is_404(), true ) . "\n";
echo "plugin active: " . var_export( is_plugin_active( '404-enhancer/404-enhancer.php' ), true ) . "\n";
echo "template_include filter result: " . apply_filters( 'template_include', 'x' ) . "\n";
ob_start();
include dirname( __DIR__ ) . '/templates/404.php';
$html = ob_get_clean();
echo "rendered len=" . strlen( $html ) . "\n";
echo substr( $html, 0, 300 ) . "\n";
+48
View File
@@ -0,0 +1,48 @@
<?php
/**
* Temporary CLI render test: boots WordPress with themes and renders templates/404.php
* as if a visitor hit a missing URL. NOT part of the plugin. Delete after running.
*/
error_reporting( E_ALL );
ini_set( 'display_errors', '1' );
define( 'WP_USE_THEMES', true );
$_SERVER['REQUEST_URI'] = '/this-page-does-not-exist-2024/';
$_SERVER['REQUEST_METHOD'] = 'GET';
require dirname( __DIR__, 3 ) . '/wp-load.php';
$GLOBALS['wp_query']->set_404();
status_header( 404 );
update_option( 'fe_custom_message', '<p>Sorry, we moved things around.</p>' );
update_option( 'fe_enabled_post_types', array( 'post', 'page' ) );
update_option( 'fe_suggestions_per_page', 3 );
ob_start();
include __DIR__ . '/templates/404.php';
$html = ob_get_clean();
$fail = 0;
function check( $label, $cond, $extra = '' ) {
global $fail;
if ( ! $cond ) {
$fail++;
}
printf( "%s %-52s %s\n", $cond ? 'PASS' : 'FAIL', $label, $extra );
}
check( 'renders without fatal', strlen( $html ) > 500, 'len=' . strlen( $html ) );
check( 'has .fe-404 wrapper', false !== strpos( $html, 'class="fe-404"' ) );
check( 'has heading', false !== strpos( $html, 'fe-404-heading' ) );
check( 'shows requested path', false !== strpos( $html, '/this-page-does-not-exist-2024/' ) );
check( 'shows custom message', false !== strpos( $html, 'Sorry, we moved things around.' ) );
check( 'has search form', false !== strpos( $html, 'fe-search-form' ) && false !== strpos( $html, 'name="s"' ) );
check( 'search prefilled from URL tokens', false !== strpos( $html, 'value="this does exist 2024"' ), '' );
check( 'has did-you-mean or sections container', false !== strpos( $html, 'fe-did-you-mean' ) || false !== strpos( $html, 'fe-section' ) );
check( 'stylesheet enqueued on 404', wp_style_is( 'fe-404', 'enqueued' ), '' );
check( 'no PHP warnings in output', false === strpos( $html, 'Warning:' ) && false === strpos( $html, 'Fatal error' ) && false === strpos( $html, 'Notice:' ) );
echo $fail ? "\nRENDER RESULT: $fail FAILURES\n" : "\nRENDER RESULT: ALL PASS\n";
exit( $fail ? 1 : 0 );
+113
View File
@@ -0,0 +1,113 @@
<?php
/**
* Temporary CLI smoke test for 404 Enhancer. Boots WordPress and exercises the plugin.
* NOT part of the plugin. Delete after running.
*/
error_reporting( E_ALL );
ini_set( 'display_errors', '1' );
define( 'WP_USE_THEMES', false );
define( 'DOING_AJAX', true ); // Before wp-load so WPAjaxDieStopException exists.
require dirname( __DIR__, 3 ) . '/wp-load.php';
require_once ABSPATH . 'wp-admin/includes/plugin.php';
// Act as the admin user so capability checks pass in CLI.
$admin_id = 1;
if ( ! get_userdata( $admin_id ) ) {
$admin_id = (int) get_users( array( 'role' => 'administrator', 'number' => 1, 'fields' => 'ID' ) )[0];
}
wp_set_current_user( $admin_id );
$fail = 0;
function check( $label, $cond, $extra = '' ) {
global $fail;
if ( ! $cond ) {
$fail++;
}
printf( "%s %-52s %s\n", $cond ? 'PASS' : 'FAIL', $label, $extra );
}
// 1. Activation.
$already = is_plugin_active( '404-enhancer/404-enhancer.php' );
if ( ! $already ) {
$result = activate_plugin( '404-enhancer/404-enhancer.php' );
check( 'activate_plugin no WP_Error', ! is_wp_error( $result ), is_wp_error( $result ) ? $result->get_error_message() : '' );
}
check( 'plugin active', is_plugin_active( '404-enhancer/404-enhancer.php' ) );
check( 'post types option exists', is_array( get_option( 'fe_enabled_post_types' ) ), json_encode( get_option( 'fe_enabled_post_types' ) ) );
check( 'per page option exists', is_numeric( get_option( 'fe_suggestions_per_page' ) ) );
// 2. Classes loaded.
check( 'FE_Settings loaded', class_exists( 'FE_Settings' ) );
check( 'FE_Suggestions loaded', class_exists( 'FE_Suggestions' ) );
check( 'FE_Template loaded', class_exists( 'FE_Template' ) );
check( 'FE_Updater loaded', class_exists( 'FE_Updater' ) );
// 3. Options round-trip with sanitizers.
update_option( 'fe_custom_message', '<p>Hello <script>alert(1)</script>404</p>' );
check( 'message saved', get_option( 'fe_custom_message' ) !== false );
check( 'per page sanitize via register', FE_Settings::sanitize_per_page( 99 ) === 24 );
check( 'post types sanitize', FE_Settings::sanitize_post_types( array( 'post', 'evil<script>', '' ) ) === array( 'post' ) );
update_option( 'fe_enabled_post_types', array( 'post', 'page' ) );
update_option( 'fe_suggestions_per_page', 3 );
check( 'enabled types getter', FE_Settings::get_enabled_post_types() === array( 'post', 'page' ) );
check( 'per page getter', FE_Settings::get_per_page() === 3 );
// 4. Suggestions against the real DB.
$tokens = FE_Suggestions::tokenize( '/hello-world/' );
check( 'tokenize hello-world', $tokens === array( 'hello', 'world' ), json_encode( $tokens ) );
$related = FE_Suggestions::get_related( $tokens, array( 'post', 'page' ), 5 );
check( 'get_related returns array', is_array( $related ), 'count=' . count( $related ) );
foreach ( $related as $p ) {
echo ' related: [' . $p->post_type . '] ' . $p->post_title . ' -> ' . get_permalink( $p ) . "\n";
}
$random = FE_Suggestions::get_random( 'post', 3 );
check( 'get_random returns array', is_array( $random ), 'count=' . count( $random ) );
$ids = array_slice( wp_list_pluck( get_posts( array( 'post_type' => 'any', 'posts_per_page' => 5, 'fields' => 'ids' ) ), 'ID' ), 0, 3 );
$ids = array_map( 'intval', get_posts( array( 'post_type' => array( 'post', 'page' ), 'posts_per_page' => 3, 'fields' => 'ids' ) ) );
$featured = FE_Suggestions::get_featured( $ids, array( 'post', 'page' ) );
check( 'get_featured returns array', is_array( $featured ), 'ids=' . json_encode( $ids ) . ' count=' . count( $featured ) );
$did = FE_Suggestions::get_did_you_mean( 'hello-wrld', array( 'post', 'page' ) );
check( 'did_you_mean returns post|null', null === $did || $did instanceof WP_Post, null === $did ? 'null' : $did->post_name );
$cross = array();
if ( ! empty( $related ) ) {
$cross = FE_Suggestions::get_cross_links( $related[0]->ID, array( 'post', 'page' ), array( $related[0]->ID ), 3 );
check( 'get_cross_links returns array', is_array( $cross ), 'count=' . count( $cross ) );
} else {
check( 'get_cross_links skipped (no related)', true );
}
// 5. Updater no-op when unconfigured (must not fatal, must not inject).
$transient = new stdClass();
$transient->checked = array( '404-enhancer/404-enhancer.php' => '0.3' );
$transient->response = array();
$out = FE_Updater::check_for_updates( $transient );
check( 'updater no-op unconfigured', empty( $out->response ) );
// 6. Template include filter returns plugin template on 404.
$q = $GLOBALS['wp_query'];
$q->set_404();
$path = FE_Template::include_template( '/theme/404.php' );
check( 'template filter path', false !== strpos( $path, 'templates/404.php' ), $path );
$filtered = apply_filters( 'fe_404_template', '/custom/override.php' );
check( 'fe_404_template filter works', $filtered === '/custom/override.php' );
// 7. Settings page renders without fatal (admin_init never fires in CLI, so register manually;
// admin template functions are only loaded in admin context, so require them too).
require_once ABSPATH . 'wp-admin/includes/template.php';
FE_Settings::register_settings();
ob_start();
FE_Settings::render_settings_page();
$html = ob_get_clean();
check( 'settings page renders', false !== strpos( $html, 'fe_featured_image_id' ) && false !== strpos( $html, 'fe-post-search' ), 'len=' . strlen( $html ) );
// 8. AJAX handler is exercised by _cli_ajax.php in a separate process (wp_send_json* terminates).
echo $fail ? "\nRESULT: $fail FAILURES\n" : "\nRESULT: ALL PASS\n";
exit( $fail ? 1 : 0 );
+36
View File
@@ -0,0 +1,36 @@
<?php
define('ABSPATH', '/tmp/');
function absint($v){ return abs((int)$v); }
function sanitize_key($k){ return preg_replace('/[^a-z0-9_\-]/', '', strtolower($k)); }
function sanitize_title($t){ return strtolower(preg_replace('/[^a-z0-9]+/i', '-', trim($t))); }
function get_post_types($args=array(), $output='names'){ return array('post','page','attachment'); }
$dir = __DIR__ . '/includes/';
require $dir . 'class-fe-suggestions.php';
require $dir . 'class-fe-settings.php';
$fail = 0;
function check($label, $actual, $expected) {
global $fail;
$ok = $actual === $expected;
if (!$ok) $fail++;
printf("%s %-58s got=%s\n", $ok ? 'PASS' : 'FAIL', $label, json_encode($actual));
}
check('tokenize blog post', FE_Suggestions::tokenize('/blog/my-great-post-2024/'), array('blog','great','post','2024'));
check('tokenize strips ext+stopword', FE_Suggestions::tokenize('/products/sale-2024/index.html'), array('products','sale','2024'));
check('tokenize simple', FE_Suggestions::tokenize('/foo-bar/'), array('foo','bar'));
check('tokenize digit split', FE_Suggestions::tokenize('/top10tips/'), array('top','tips'));
check('tokenize empty', FE_Suggestions::tokenize('/'), array());
check('search term', FE_Suggestions::search_term_from_tokens(array('great','post')), 'great post');
check('slug from path', FE_Suggestions::slug_from_path('/a/b/My Page v2/'), 'my-page-v2');
check('slug from root', FE_Suggestions::slug_from_path('/'), '');
check('per_page clamp low', FE_Settings::sanitize_per_page(0), 1);
check('per_page clamp high', FE_Settings::sanitize_per_page(99), 24);
check('per_page normal', FE_Settings::sanitize_per_page('7'), 7);
check('post types filter', FE_Settings::sanitize_post_types(array('post','bogus','page','')), array('post','page'));
check('post ids sanitize', FE_Settings::sanitize_post_ids(array('5','0','abc','5','12')), array(5,12));
check('lev close', levenshtein('my-pge', 'my-page') <= max(2, (int)(strlen('my-pge')/3)), true);
check('lev far', levenshtein('totally-different', 'my-page') <= max(2, (int)(strlen('totally-different')/3)), false);
exit($fail ? 1 : 0);
+143
View File
@@ -0,0 +1,143 @@
/* 404 Enhancer front-end styles. Scoped under .fe-404 to avoid theme collisions. */
.fe-404 {
max-width: 1100px;
margin: 0 auto;
padding: 2rem 1.25rem 4rem;
}
.fe-sr-only {
position: absolute;
width: 1px;
height: 1px;
padding: 0;
margin: -1px;
overflow: hidden;
clip: rect(0, 0, 0, 0);
white-space: nowrap;
border: 0;
}
/* Hero */
.fe-404-hero {
display: flex;
flex-wrap: wrap;
gap: 2rem;
align-items: center;
margin-bottom: 3rem;
}
.fe-404-hero-image {
flex: 0 1 320px;
}
.fe-404-hero-image img {
max-width: 100%;
height: auto;
display: block;
}
.fe-404-hero-text {
flex: 1 1 320px;
}
.fe-404-heading {
margin-top: 0;
}
.fe-404-requested code {
background: rgba(0, 0, 0, 0.06);
padding: 0.1em 0.4em;
border-radius: 3px;
word-break: break-all;
}
.fe-404-message {
margin: 1rem 0;
}
/* Search form */
.fe-search-form {
display: flex;
gap: 0.5rem;
max-width: 480px;
margin: 1.25rem 0 0.5rem;
}
.fe-search-form input[type="search"] {
flex: 1;
min-width: 0;
padding: 0.5rem 0.75rem;
}
.fe-search-form button {
padding: 0.5rem 1.25rem;
cursor: pointer;
}
.fe-did-you-mean {
font-style: italic;
}
/* Sections and cards */
.fe-section {
margin-bottom: 2.5rem;
}
.fe-section-title {
margin-bottom: 1rem;
}
.fe-card-grid {
list-style: none;
margin: 0;
padding: 0;
display: grid;
grid-template-columns: repeat(auto-fill, minmax(220px, 1fr));
gap: 1rem;
}
.fe-card {
border: 1px solid rgba(0, 0, 0, 0.12);
border-radius: 6px;
overflow: hidden;
transition: box-shadow 0.15s ease-in-out;
}
.fe-card:hover {
box-shadow: 0 2px 10px rgba(0, 0, 0, 0.12);
}
.fe-card-link {
display: block;
height: 100%;
color: inherit;
text-decoration: none;
}
.fe-card-thumb img {
width: 100%;
height: 140px;
object-fit: cover;
display: block;
}
.fe-card-body {
display: block;
padding: 0.75rem 1rem 1rem;
}
.fe-card-title {
display: block;
font-weight: 600;
margin-bottom: 0.35rem;
}
.fe-card-excerpt {
display: block;
font-size: 0.875em;
opacity: 0.8;
}
+106
View File
@@ -0,0 +1,106 @@
/* 404 Enhancer admin script: featured image picker + featured content AJAX picker. */
jQuery(document).ready(function ($) {
'use strict';
/* Featured image via the media library frame. */
var frame;
$('#fe-upload-btn').on('click', function (e) {
e.preventDefault();
if (!frame) {
frame = wp.media({
title: FEAdmin.i18n.chooseImage,
button: { text: FEAdmin.i18n.useImage },
library: { type: 'image' },
multiple: false
});
frame.on('select', function () {
var attachment = frame.state().get('selection').first().toJSON();
$('#fe_featured_image_id').val(attachment.id);
$('#fe-featured-preview').attr('src', attachment.url).show();
$('#fe-remove-btn').show();
});
}
frame.open();
});
$('#fe-remove-btn').on('click', function (e) {
e.preventDefault();
$('#fe_featured_image_id').val('');
$('#fe-featured-preview').attr('src', '').hide();
$(this).hide();
});
/* Featured content picker: debounced AJAX search + chips. */
var $search = $('#fe-post-search');
var $results = $('#fe-search-results');
var $list = $('#fe-featured-list');
var timer = null;
function selectedIds() {
return $list.find('li').map(function () { return String($(this).data('id')); }).get();
}
function addChip(post) {
if (-1 !== $.inArray(String(post.id), selectedIds())) {
return;
}
var $chip = $('<li class="fe-chip"></li>').attr('data-id', post.id);
$chip.append(document.createTextNode(post.title + ' '));
$chip.append($('<span class="fe-chip-type"></span>').text(post.type));
$chip.append($('<input type="hidden">').attr('name', 'fe_featured_post_ids[]').val(post.id));
$chip.append($('<button type="button" class="fe-chip-remove" aria-label="Remove">&times;</button>'));
$list.append($chip);
}
function renderResults(posts) {
$results.empty();
var ids = selectedIds();
var visible = posts.filter(function (p) { return -1 === $.inArray(String(p.id), ids); });
if (!visible.length) {
$results.append($('<li></li>').text(FEAdmin.i18n.noResults)).show();
return;
}
visible.forEach(function (post) {
var $item = $('<li></li>').append(
$('<button type="button" class="fe-result"></button>').text(post.title + ' (' + post.type + ')')
);
$item.find('button').on('click', function () {
addChip(post);
$search.val('');
$results.hide().empty();
});
$results.append($item);
});
$results.show();
}
$search.on('input', function () {
var term = $search.val();
clearTimeout(timer);
if (!term || term.length < 2) {
$results.hide().empty();
return;
}
timer = setTimeout(function () {
$.post(FEAdmin.ajaxUrl, {
action: FEAdmin.action,
nonce: FEAdmin.nonce,
s: term
}, function (response) {
if (response && response.success && response.data && response.data.posts) {
renderResults(response.data.posts);
}
});
}, 300);
});
$results.on('mousedown', function (e) { e.preventDefault(); }); // Keep input focus while clicking a result.
$(document).on('click', function (e) {
if (!$(e.target).closest('#fe-featured-picker').length) {
$results.hide();
}
});
$list.on('click', '.fe-chip-remove', function () {
$(this).closest('li').remove();
});
});
+411
View File
@@ -0,0 +1,411 @@
<?php
/**
* Admin settings page for 404 Enhancer.
*
* @package 404_Enhancer
*/
if ( ! defined( 'ABSPATH' ) ) {
exit;
}
/**
* Registers the settings page, settings fields, sanitizers and admin assets.
*/
final class FE_Settings {
const OPTION_MESSAGE = 'fe_custom_message';
const OPTION_IMAGE = 'fe_featured_image_id';
const OPTION_POSTTYPES = 'fe_enabled_post_types';
const OPTION_FEATURED = 'fe_featured_post_ids';
const OPTION_PER_PAGE = 'fe_suggestions_per_page';
/**
* Registers all admin hooks.
*/
public static function init() {
add_action( 'admin_menu', array( __CLASS__, 'add_menu_page' ) );
add_action( 'admin_init', array( __CLASS__, 'register_settings' ) );
add_action( 'admin_enqueue_scripts', array( __CLASS__, 'enqueue_assets' ) );
add_action( 'wp_ajax_fe_search_posts', array( __CLASS__, 'ajax_search_posts' ) );
}
/**
* Adds the settings page under the Settings menu.
*/
public static function add_menu_page() {
add_options_page(
__( '404 Enhancer Settings', '404-enhancer' ),
__( '404 Enhancer', '404-enhancer' ),
'manage_options',
'fe-settings',
array( __CLASS__, 'render_settings_page' )
);
}
/**
* Registers settings, sections and fields with sanitize callbacks.
*/
public static function register_settings() {
register_setting(
'fe_settings_group',
self::OPTION_MESSAGE,
array(
'type' => 'string',
'sanitize_callback' => 'wp_kses_post',
'default' => '',
)
);
register_setting(
'fe_settings_group',
self::OPTION_IMAGE,
array(
'type' => 'integer',
'sanitize_callback' => 'absint',
'default' => 0,
)
);
register_setting(
'fe_settings_group',
self::OPTION_POSTTYPES,
array(
'type' => 'array',
'sanitize_callback' => array( __CLASS__, 'sanitize_post_types' ),
'default' => array( 'post' ),
)
);
register_setting(
'fe_settings_group',
self::OPTION_FEATURED,
array(
'type' => 'array',
'sanitize_callback' => array( __CLASS__, 'sanitize_post_ids' ),
'default' => array(),
)
);
register_setting(
'fe_settings_group',
self::OPTION_PER_PAGE,
array(
'type' => 'integer',
'sanitize_callback' => array( __CLASS__, 'sanitize_per_page' ),
'default' => 6,
)
);
add_settings_section(
'fe_section_display',
__( 'Display', '404-enhancer' ),
'__return_null',
'fe-settings'
);
add_settings_field(
self::OPTION_MESSAGE,
__( 'Custom message', '404-enhancer' ),
array( __CLASS__, 'field_message' ),
'fe-settings',
'fe_section_display'
);
add_settings_field(
self::OPTION_IMAGE,
__( 'Featured image', '404-enhancer' ),
array( __CLASS__, 'field_image' ),
'fe-settings',
'fe_section_display'
);
add_settings_section(
'fe_section_content',
__( 'Content suggestions', '404-enhancer' ),
'__return_null',
'fe-settings'
);
add_settings_field(
self::OPTION_POSTTYPES,
__( 'Post types to suggest', '404-enhancer' ),
array( __CLASS__, 'field_post_types' ),
'fe-settings',
'fe_section_content'
);
add_settings_field(
self::OPTION_FEATURED,
__( 'Featured content', '404-enhancer' ),
array( __CLASS__, 'field_featured_posts' ),
'fe-settings',
'fe_section_content'
);
add_settings_field(
self::OPTION_PER_PAGE,
__( 'Suggestions per section', '404-enhancer' ),
array( __CLASS__, 'field_per_page' ),
'fe-settings',
'fe_section_content'
);
}
/**
* Sanitizes the enabled post types list against existing public post types.
*
* @param mixed $value Raw submitted value.
* @return string[] Sanitized post type names.
*/
public static function sanitize_post_types( $value ) {
$value = is_array( $value ) ? $value : array();
$valid = get_post_types( array( 'public' => true ), 'names' );
$sanitized = array();
foreach ( $value as $post_type ) {
$post_type = sanitize_key( (string) $post_type );
if ( '' !== $post_type && in_array( $post_type, $valid, true ) ) {
$sanitized[] = $post_type;
}
}
return array_values( array_unique( $sanitized ) );
}
/**
* Sanitizes the featured post ID list.
*
* @param mixed $value Raw submitted value.
* @return int[] Attachment/post IDs greater than zero.
*/
public static function sanitize_post_ids( $value ) {
$value = is_array( $value ) ? $value : array();
$ids = array_map( 'absint', $value );
return array_values( array_unique( array_filter( $ids ) ) );
}
/**
* Sanitizes the per-section suggestion count.
*
* @param mixed $value Raw submitted value.
* @return int Clamped between 1 and 24.
*/
public static function sanitize_per_page( $value ) {
$value = absint( $value );
if ( $value < 1 ) {
$value = 1;
}
if ( $value > 24 ) {
$value = 24;
}
return $value;
}
/**
* Enqueues media library and admin script only on the settings page.
*
* @param string $hook_suffix Current admin page hook.
*/
public static function enqueue_assets( $hook_suffix ) {
if ( 'settings_page_fe-settings' !== $hook_suffix ) {
return;
}
wp_enqueue_media();
wp_enqueue_script(
'fe-admin',
FE_PLUGIN_URL . 'assets/js/fe-admin.js',
array( 'jquery' ),
FE_VERSION,
true
);
wp_localize_script(
'fe-admin',
'FEAdmin',
array(
'ajaxUrl' => admin_url( 'admin-ajax.php' ),
'nonce' => wp_create_nonce( 'fe_admin_nonce' ),
'action' => 'fe_search_posts',
'i18n' => array(
'chooseImage' => __( 'Select or upload an image', '404-enhancer' ),
'useImage' => __( 'Use this image', '404-enhancer' ),
'searchPh' => __( 'Search posts to feature…', '404-enhancer' ),
'noResults' => __( 'No matching published content.', '404-enhancer' ),
),
)
);
}
/**
* Renders the settings page.
*/
public static function render_settings_page() {
if ( ! current_user_can( 'manage_options' ) ) {
return;
}
?>
<div class="wrap">
<h1><?php echo esc_html( get_admin_page_title() ); ?></h1>
<form method="post" action="options.php">
<?php
settings_fields( 'fe_settings_group' );
do_settings_sections( 'fe-settings' );
submit_button();
?>
</form>
</div>
<?php
}
/**
* Renders the custom message editor field.
*/
public static function field_message() {
$message = get_option( self::OPTION_MESSAGE, '' );
wp_editor(
$message,
self::OPTION_MESSAGE,
array(
'textarea_rows' => 5,
'media_buttons' => false,
'teeny' => true,
)
);
echo '<p class="description">' . esc_html__( 'Shown near the top of the 404 page, above the search form.', '404-enhancer' ) . '</p>';
}
/**
* Renders the featured image picker field.
*/
public static function field_image() {
$image_id = absint( get_option( self::OPTION_IMAGE, 0 ) );
$image_url = $image_id ? wp_get_attachment_url( $image_id ) : '';
?>
<img id="fe-featured-preview" src="<?php echo esc_url( $image_url ? $image_url : '' ); ?>" alt="" style="max-width: 300px; display: <?php echo $image_id ? 'block' : 'none'; ?>; margin-bottom: 10px;">
<input type="hidden" id="fe_featured_image_id" name="<?php echo esc_attr( self::OPTION_IMAGE ); ?>" value="<?php echo esc_attr( $image_id ); ?>">
<button type="button" class="button" id="fe-upload-btn"><?php esc_html_e( 'Choose image', '404-enhancer' ); ?></button>
<button type="button" class="button" id="fe-remove-btn" style="display: <?php echo $image_id ? 'inline-block' : 'none'; ?>;"><?php esc_html_e( 'Remove', '404-enhancer' ); ?></button>
<p class="description"><?php esc_html_e( 'Optional image shown on the 404 page.', '404-enhancer' ); ?></p>
<?php
}
/**
* Renders the post type checkbox field.
*/
public static function field_post_types() {
$post_types = get_post_types( array( 'public' => true ), 'objects' );
$enabled = self::get_enabled_post_types();
// Hidden empty value guarantees the option is submitted even when nothing is checked.
echo '<input type="hidden" name="' . esc_attr( self::OPTION_POSTTYPES ) . '[]" value="">';
foreach ( $post_types as $pt ) {
printf(
'<label style="display: block; margin-bottom: 4px;"><input type="checkbox" name="%1$s[]" value="%2$s" %3$s> %4$s</label>',
esc_attr( self::OPTION_POSTTYPES ),
esc_attr( $pt->name ),
checked( in_array( $pt->name, $enabled, true ), true, false ),
esc_html( $pt->labels->name )
);
}
echo '<p class="description">' . esc_html__( 'Content from these post types is used for URL-based suggestions and random picks.', '404-enhancer' ) . '</p>';
}
/**
* Renders the featured content AJAX picker field.
*/
public static function field_featured_posts() {
$featured = self::get_featured_post_ids();
// Hidden empty value so the option is submitted when no posts are selected.
echo '<input type="hidden" name="' . esc_attr( self::OPTION_FEATURED ) . '[]" value="">';
?>
<div id="fe-featured-picker">
<ul id="fe-featured-list" style="margin: 0 0 8px;">
<?php foreach ( $featured as $post_id ) : ?>
<?php $post = get_post( $post_id ); ?>
<?php if ( $post ) : ?>
<li class="fe-chip" data-id="<?php echo esc_attr( $post_id ); ?>">
<?php echo esc_html( get_the_title( $post ) ); ?>
<?php printf( '<span class="fe-chip-type">%s</span>', esc_html( get_post_type_object( $post->post_type )->labels->singular_name ) ); ?>
<input type="hidden" name="<?php echo esc_attr( self::OPTION_FEATURED ); ?>[]" value="<?php echo esc_attr( $post_id ); ?>">
<button type="button" class="fe-chip-remove" aria-label="<?php esc_attr_e( 'Remove', '404-enhancer' ); ?>">&times;</button>
</li>
<?php endif; ?>
<?php endforeach; ?>
</ul>
<input type="search" id="fe-post-search" class="regular-text" placeholder="<?php esc_attr_e( 'Search posts to feature…', '404-enhancer' ); ?>" autocomplete="off">
<ul id="fe-search-results" style="display: none;"></ul>
</div>
<p class="description"><?php esc_html_e( 'Hand-picked content shown first on the 404 page, in the order selected.', '404-enhancer' ); ?></p>
<?php
}
/**
* Renders the suggestions-per-section number field.
*/
public static function field_per_page() {
$value = self::get_per_page();
printf(
'<input type="number" min="1" max="24" name="%s" value="%d">',
esc_attr( self::OPTION_PER_PAGE ),
esc_attr( $value )
);
echo '<p class="description">' . esc_html__( 'How many items each suggestion section on the 404 page shows.', '404-enhancer' ) . '</p>';
}
/**
* AJAX endpoint returning published posts matching a search string.
*/
public static function ajax_search_posts() {
check_ajax_referer( 'fe_admin_nonce', 'nonce' );
if ( ! current_user_can( 'manage_options' ) ) {
wp_send_json_error( array( 'message' => 'forbidden' ), 403 );
}
$term = isset( $_POST['s'] ) ? sanitize_text_field( wp_unslash( $_POST['s'] ) ) : '';
$post_types = self::get_enabled_post_types();
if ( empty( $post_types ) ) {
$post_types = array( 'post' );
}
$query = new WP_Query(
array(
's' => $term,
'post_type' => $post_types,
'post_status' => 'publish',
'posts_per_page' => 10,
'orderby' => 'title',
'order' => 'ASC',
'no_found_rows' => true,
)
);
$results = array();
foreach ( $query->posts as $post ) {
$results[] = array(
'id' => $post->ID,
'title' => get_the_title( $post ),
'type' => get_post_type_object( $post->post_type )->labels->singular_name,
'url' => get_permalink( $post ),
);
}
wp_send_json_success( array( 'posts' => $results ) );
}
/**
* Returns the enabled post types with a sensible fallback.
*
* @return string[]
*/
public static function get_enabled_post_types() {
$enabled = get_option( self::OPTION_POSTTYPES, array( 'post' ) );
$enabled = is_array( $enabled ) ? $enabled : array( 'post' );
if ( empty( $enabled ) ) {
$enabled = array( 'post' );
}
return $enabled;
}
/**
* Returns the featured post IDs.
*
* @return int[]
*/
public static function get_featured_post_ids() {
$ids = get_option( self::OPTION_FEATURED, array() );
return is_array( $ids ) ? array_map( 'absint', $ids ) : array();
}
/**
* Returns the suggestions-per-section setting.
*
* @return int
*/
public static function get_per_page() {
return self::sanitize_per_page( get_option( self::OPTION_PER_PAGE, 6 ) );
}
}
+298
View File
@@ -0,0 +1,298 @@
<?php
/**
* Content suggestion engine for the 404 page.
*
* @package 404_Enhancer
*/
if ( ! defined( 'ABSPATH' ) ) {
exit;
}
/**
* Derives search terms from the requested URL and builds suggestion queries.
*/
final class FE_Suggestions {
/**
* Common English stopwords excluded from URL tokens.
*
* @var string[]
*/
private static $stopwords = array(
'the', 'and', 'for', 'are', 'but', 'not', 'you', 'all', 'any', 'can', 'had', 'her', 'was', 'one', 'our', 'out',
'day', 'get', 'has', 'him', 'his', 'how', 'its', 'new', 'now', 'old', 'see', 'way', 'who', 'with', 'www', 'com',
'net', 'org', 'html', 'htm', 'php', 'asp', 'aspx', 'index', 'page',
);
/**
* Returns the raw requested path (no query string), decoded.
*
* @return string
*/
public static function get_requested_path() {
$request_uri = isset( $_SERVER['REQUEST_URI'] ) ? sanitize_text_field( wp_unslash( $_SERVER['REQUEST_URI'] ) ) : '';
$path = (string) wp_parse_url( $request_uri, PHP_URL_PATH );
return rawurldecode( $path );
}
/**
* Splits a URL path into meaningful search tokens.
*
* Pure function (no WP calls) so it can be unit tested.
*
* @param string $path URL path, e.g. /blog/my-great-post-2024/.
* @return string[] Tokens, e.g. ['blog', 'great', 'post', '2024'].
*/
public static function tokenize( $path ) {
$path = trim( (string) $path, '/' );
$path = preg_replace( '/\.[a-z0-9]{1,5}$/i', '', $path ); // Strip file extension.
$parts = preg_split( '/[^a-z0-9]+/i', $path, -1, PREG_SPLIT_NO_EMPTY );
if ( ! is_array( $parts ) ) {
return array();
}
$tokens = array();
foreach ( $parts as $part ) {
$part = strtolower( $part );
// Split camelCase and digit boundaries: "post2024" -> "post", "2024".
foreach ( preg_split( '/(?<=[a-z])(?=[0-9])|(?<=[0-9])(?=[a-z])/i', $part ) as $sub ) {
$sub = strtolower( $sub );
if ( strlen( $sub ) < 3 || in_array( $sub, self::$stopwords, true ) || is_numeric( $sub ) && strlen( $sub ) < 4 ) {
continue;
}
$tokens[] = $sub;
}
}
return array_values( array_unique( $tokens ) );
}
/**
* Builds the human readable search term from URL tokens.
*
* @param string[] $tokens Tokens from tokenize().
* @return string
*/
public static function search_term_from_tokens( array $tokens ) {
return implode( ' ', $tokens );
}
/**
* Returns the last path segment as a slug candidate for "did you mean".
*
* @param string $path URL path.
* @return string
*/
public static function slug_from_path( $path ) {
$path = trim( (string) $path, '/' );
if ( '' === $path ) {
return '';
}
$segments = explode( '/', $path );
$last = (string) end( $segments );
$last = preg_replace( '/\.[a-z0-9]{1,5}$/i', '', $last );
return sanitize_title( $last );
}
/**
* Runs a full-text query for the URL tokens and ranks results by how many
* tokens appear in title/content.
*
* @param string[] $tokens Search tokens.
* @param string[] $post_types Post types to include.
* @param int $count Max results.
* @return WP_Post[] Ranked posts.
*/
public static function get_related( array $tokens, array $post_types, $count ) {
if ( empty( $tokens ) ) {
return array();
}
$query = new WP_Query(
array(
's' => implode( ' ', $tokens ),
'post_type' => $post_types,
'post_status' => 'publish',
'posts_per_page' => max( $count * 3, 10 ),
'no_found_rows' => true,
'update_post_term_cache' => false,
)
);
if ( empty( $query->posts ) ) {
return array();
}
$scored = array();
foreach ( $query->posts as $post ) {
$haystack = strtolower( $post->post_title . ' ' . $post->post_content );
$score = 0;
foreach ( $tokens as $token ) {
if ( false !== strpos( $haystack, $token ) ) {
$score++;
}
}
$scored[] = array( $score, $post );
}
usort(
$scored,
function ( $a, $b ) {
if ( $a[0] === $b[0] ) {
return strcmp( $b[1]->post_date, $a[1]->post_date );
}
return $b[0] - $a[0];
}
);
return array_slice( array_map( function ( $row ) { return $row[1]; }, $scored ), 0, $count );
}
/**
* Finds the published post whose slug is closest to the requested slug.
*
* @param string $requested_slug Slug derived from the URL.
* @param string[] $post_types Post types to consider.
* @return WP_Post|null Closest match, or null when nothing is close enough.
*/
public static function get_did_you_mean( $requested_slug, array $post_types ) {
if ( '' === $requested_slug ) {
return null;
}
/**
* Filters how many recent posts are scanned for slug similarity.
*
* @param int $max_candidates Candidate pool size.
*/
$max_candidates = (int) apply_filters( 'fe_did_you_mean_candidates', 200 );
$query = new WP_Query(
array(
'post_type' => $post_types,
'post_status' => 'publish',
'posts_per_page' => $max_candidates,
'orderby' => 'date',
'order' => 'DESC',
'no_found_rows' => true,
'update_post_term_cache' => false,
'fields' => 'all',
)
);
$best = null;
$best_dist = PHP_INT_MAX;
$threshold = max( 2, (int) ( strlen( $requested_slug ) / 3 ) );
foreach ( $query->posts as $post ) {
if ( strlen( $post->post_name ) > 255 || strlen( $requested_slug ) > 255 ) {
continue;
}
$dist = levenshtein( $requested_slug, $post->post_name );
if ( $dist < $best_dist ) {
$best_dist = $dist;
$best = $post;
}
}
if ( $best && $best_dist <= $threshold ) {
return $best;
}
return null;
}
/**
* Returns posts sharing taxonomy terms with a given post (cross-links).
*
* @param int $post_id Reference post ID.
* @param string[] $post_types Post types to include.
* @param int[] $exclude_ids Post IDs to exclude.
* @param int $count Max results.
* @return WP_Post[]
*/
public static function get_cross_links( $post_id, array $post_types, array $exclude_ids, $count ) {
$taxonomies = get_object_taxonomies( get_post_type( $post_id ), 'names' );
$taxonomies = array_values( array_filter( $taxonomies, 'is_taxonomy_viewable' ) );
if ( empty( $taxonomies ) ) {
return array();
}
$term_ids = array();
foreach ( $taxonomies as $taxonomy ) {
$terms = wp_get_object_terms( $post_id, $taxonomy, array( 'fields' => 'ids' ) );
if ( ! is_wp_error( $terms ) ) {
$term_ids = array_merge( $term_ids, $terms );
}
}
if ( empty( $term_ids ) ) {
return array();
}
$query = new WP_Query(
array(
'post_type' => $post_types,
'post_status' => 'publish',
'posts_per_page' => $count,
'post__not_in' => array_merge( array( $post_id ), $exclude_ids ),
'tax_query' => array(
array(
'taxonomy' => $taxonomies[0],
'field' => 'term_id',
'terms' => $term_ids,
),
),
'no_found_rows' => true,
'update_post_term_cache' => false,
'orderby' => 'date',
'order' => 'DESC',
)
);
return $query->posts;
}
/**
* Returns random published posts of one type using a random offset
* instead of orderby=rand (which sorts the whole table).
*
* @param string $post_type Post type.
* @param int $count Number of posts.
* @return WP_Post[]
*/
public static function get_random( $post_type, $count ) {
$counts = wp_count_posts( $post_type );
$total = isset( $counts->publish ) ? (int) $counts->publish : 0;
if ( $total < 1 ) {
return array();
}
$offset = 0;
if ( $total > $count ) {
$offset = random_int( 0, $total - $count );
}
$query = new WP_Query(
array(
'post_type' => $post_type,
'post_status' => 'publish',
'posts_per_page' => $count,
'offset' => $offset,
'orderby' => 'date',
'order' => 'DESC',
'no_found_rows' => true,
'update_post_term_cache' => false,
)
);
return $query->posts;
}
/**
* Returns the hand-picked featured posts, in the order they were selected.
*
* @param int[] $ids Featured post IDs.
* @param string[] $post_types Allowed post types.
* @return WP_Post[]
*/
public static function get_featured( array $ids, array $post_types ) {
$ids = array_filter( array_map( 'absint', $ids ) );
if ( empty( $ids ) ) {
return array();
}
$query = new WP_Query(
array(
'post_type' => $post_types,
'post_status' => 'publish',
'post__in' => $ids,
'orderby' => 'post__in',
'posts_per_page' => count( $ids ),
'no_found_rows' => true,
'update_post_term_cache' => false,
)
);
return $query->posts;
}
}
+68
View File
@@ -0,0 +1,68 @@
<?php
/**
* Swaps in the custom 404 template and enqueues its assets.
*
* @package 404_Enhancer
*/
if ( ! defined( 'ABSPATH' ) ) {
exit;
}
/**
* Handles the front-end 404 template.
*/
final class FE_Template {
/**
* Registers front-end hooks.
*/
public static function init() {
add_action( 'template_redirect', array( __CLASS__, 'handle_404' ) );
add_action( 'wp_enqueue_scripts', array( __CLASS__, 'enqueue_assets' ) );
}
/**
* On 404 requests: send no-cache headers and swap the template.
*/
public static function handle_404() {
if ( ! is_404() ) {
return;
}
nocache_headers();
add_filter( 'template_include', array( __CLASS__, 'include_template' ) );
}
/**
* Filters the template path for 404 requests.
*
* Themes can override the template via the `fe_404_template` filter.
*
* @param string $template Current template path.
* @return string
*/
public static function include_template( $template ) {
$custom = FE_PLUGIN_DIR . 'templates/404.php';
/**
* Filters the 404 template path.
*
* @param string $custom Default template inside the plugin.
*/
return apply_filters( 'fe_404_template', $custom );
}
/**
* Enqueues the 404 stylesheet only on 404 pages.
*/
public static function enqueue_assets() {
if ( ! is_404() ) {
return;
}
wp_enqueue_style(
'fe-404',
FE_PLUGIN_URL . 'assets/css/fe-404.css',
array(),
FE_VERSION
);
}
}
+216
View File
@@ -0,0 +1,216 @@
<?php
/**
* Self-hosted plugin updater for a Gitea instance (rudrastyh-style).
*
* Configuration, in order of precedence:
* 1. Constants: FE_GITEA_API_URL, FE_GITEA_OWNER, FE_GITEA_REPO, FE_GITEA_TOKEN.
* 2. The `fe_updater_config` filter returning an array with keys
* api_url, owner, repo, token.
*
* The updater is a no-op until api_url/owner/repo are set.
*
* @package 404_Enhancer
*/
if ( ! defined( 'ABSPATH' ) ) {
exit;
}
/**
* Checks a Gitea repository for releases and injects them into the
* WordPress update transients.
*/
final class FE_Updater {
const CACHE_KEY = 'fe_gitea_latest_release';
const CACHE_TTL = 6 * HOUR_IN_SECONDS;
/**
* Registers update hooks.
*/
public static function init() {
add_filter( 'pre_set_site_transient_update_plugins', array( __CLASS__, 'check_for_updates' ) );
add_filter( 'plugins_api', array( __CLASS__, 'plugin_info' ), 10, 3 );
}
/**
* Returns the updater configuration.
*
* @return array{api_url: string, owner: string, repo: string, token: string}
*/
private static function config() {
$config = array(
'api_url' => defined( 'FE_GITEA_API_URL' ) ? (string) FE_GITEA_API_URL : '',
'owner' => defined( 'FE_GITEA_OWNER' ) ? (string) FE_GITEA_OWNER : '',
'repo' => defined( 'FE_GITEA_REPO' ) ? (string) FE_GITEA_REPO : '',
'token' => defined( 'FE_GITEA_TOKEN' ) ? (string) FE_GITEA_TOKEN : '',
);
/**
* Filters the Gitea updater configuration.
*
* @param array $config Keys: api_url, owner, repo, token.
*/
return wp_parse_args( apply_filters( 'fe_updater_config', $config ), $config );
}
/**
* Whether the updater has enough configuration to run.
*
* @return bool
*/
private static function is_configured() {
$config = self::config();
return '' !== $config['api_url'] && '' !== $config['owner'] && '' !== $config['repo'];
}
/**
* Fetches the latest usable release from the Gitea API (cached).
*
* @return array|null Keys: version, tag, name, body, html_url, package. Null on failure.
*/
private static function get_latest_release() {
if ( ! self::is_configured() ) {
return null;
}
$config = self::config();
$cache = get_transient( self::CACHE_KEY );
if ( false !== $cache && is_array( $cache ) ) {
return $cache;
}
$url = trailingslashit( $config['api_url'] ) . 'repos/' . rawurlencode( $config['owner'] ) . '/' . rawurlencode( $config['repo'] ) . '/releases?limit=30';
$args = array(
'timeout' => 10,
'headers' => array( 'Accept' => 'application/json' ),
);
if ( '' !== $config['token'] ) {
$args['headers']['Authorization'] = 'token ' . $config['token'];
}
$response = wp_remote_get( $url, $args );
if ( is_wp_error( $response ) || 200 !== (int) wp_remote_retrieve_response_code( $response ) ) {
return null;
}
$releases = json_decode( (string) wp_remote_retrieve_body( $response ), true );
if ( ! is_array( $releases ) ) {
return null;
}
$api_host = (string) wp_parse_url( $config['api_url'], PHP_URL_HOST );
$best = null;
foreach ( $releases as $release ) {
if ( ! empty( $release['draft'] ) || ! empty( $release['prerelease'] ) ) {
continue;
}
$version = ltrim( (string) ( $release['tag_name'] ?? '' ), 'vV' );
if ( '' === $version || ! preg_match( '/^\d+(\.\d+)*/', $version ) ) {
continue;
}
$package = '';
if ( ! empty( $release['assets'] ) && is_array( $release['assets'] ) ) {
foreach ( $release['assets'] as $asset ) {
$name = (string) ( $asset['name'] ?? '' );
$link = (string) ( $asset['browser_download_url'] ?? '' );
if ( '.zip' === substr( strtolower( $name ), -4 ) && self::same_host( $link, $api_host ) ) {
// Prefer an asset named after the plugin slug.
if ( FE_SLUG . '.zip' === strtolower( $name ) ) {
$package = $link;
break;
}
if ( '' === $package ) {
$package = $link;
}
}
}
}
if ( '' === $package ) {
continue;
}
$candidate = array(
'version' => $version,
'tag' => (string) $release['tag_name'],
'name' => (string) ( $release['name'] ?: $release['tag_name'] ),
'body' => (string) ( $release['body'] ?? '' ),
'html_url' => (string) ( $release['html_url'] ?? '' ),
'package' => $package,
);
if ( null === $best || version_compare( $candidate['version'], $best['version'], '>' ) ) {
$best = $candidate;
}
}
if ( null !== $best ) {
set_transient( self::CACHE_KEY, $best, self::CACHE_TTL );
}
return $best;
}
/**
* Checks whether a URL belongs to the configured Gitea host.
*
* @param string $url Candidate URL.
* @param string $api_host Expected host.
* @return bool
*/
private static function same_host( $url, $api_host ) {
$host = wp_parse_url( $url, PHP_URL_HOST );
return is_string( $host ) && strtolower( $host ) === strtolower( (string) $api_host );
}
/**
* Injects the remote version into the update_plugins transient.
*
* @param object $transient Update transient value.
* @return object
*/
public static function check_for_updates( $transient ) {
if ( ! is_object( $transient ) ) {
$transient = new stdClass();
}
$release = self::get_latest_release();
if ( null === $release ) {
return $transient;
}
if ( version_compare( $release['version'], FE_VERSION, '>' ) ) {
$transient->response[ FE_SLUG ] = (object) array(
'slug' => FE_SLUG,
'plugin' => plugin_basename( FE_PLUGIN_FILE ),
'new_version' => $release['version'],
'url' => $release['html_url'],
'package' => $release['package'],
'tested' => get_bloginfo( 'version' ),
);
}
return $transient;
}
/**
* Serves plugin information for the "View details" modal.
*
* @param mixed $result Result object or false.
* @param string $action plugins_api action.
* @param object $args Request args.
* @return mixed
*/
public static function plugin_info( $result, $action, $args ) {
if ( 'plugin_information' !== $action || ! isset( $args->slug ) || FE_SLUG !== $args->slug ) {
return $result;
}
$release = self::get_latest_release();
if ( null === $release ) {
return $result;
}
return (object) array(
'name' => __( '404 Enhancer', '404-enhancer' ),
'slug' => FE_SLUG,
'version' => $release['version'],
'author' => 'Your Name',
'homepage' => $release['html_url'],
'download_link' => $release['package'],
'tested' => get_bloginfo( 'version' ),
'sections' => array(
'description' => __( 'Enhances the 404 page with a custom message, featured image, hand-picked content, search and URL-based suggestions.', '404-enhancer' ),
'changelog' => $release['body'] ? wp_kses_post( nl2br( $release['body'] ) ) : __( 'No changelog provided.', '404-enhancer' ),
),
);
}
}
+148
View File
@@ -0,0 +1,148 @@
<?php
/**
* Custom 404 template for 404 Enhancer.
*
* All dynamic output is escaped. Sections render only when they have content.
*
* @package 404_Enhancer
*/
if ( ! defined( 'ABSPATH' ) ) {
exit;
}
get_header();
$path = FE_Suggestions::get_requested_path();
$tokens = FE_Suggestions::tokenize( $path );
$slug = FE_Suggestions::slug_from_path( $path );
$search = FE_Suggestions::search_term_from_tokens( $tokens );
if ( '' === $search && '' !== $slug ) {
$search = str_replace( '-', ' ', $slug );
}
$post_types = FE_Settings::get_enabled_post_types();
$per_page = FE_Settings::get_per_page();
$message = get_option( FE_Settings::OPTION_MESSAGE, '' );
$image_id = absint( get_option( FE_Settings::OPTION_IMAGE, 0 ) );
$image_url = $image_id ? wp_get_attachment_url( $image_id ) : '';
$featured = FE_Suggestions::get_featured( FE_Settings::get_featured_post_ids(), $post_types );
$related = FE_Suggestions::get_related( $tokens, $post_types, $per_page );
$related_ids = wp_list_pluck( $related, 'ID' );
$did_you_mean = FE_Suggestions::get_did_you_mean( $slug, $post_types );
$cross_links = array();
if ( ! empty( $related ) ) {
$cross_links = FE_Suggestions::get_cross_links( $related[0]->ID, $post_types, $related_ids, $per_page );
}
$random = array();
foreach ( $post_types as $pt ) {
$random = array_merge( $random, FE_Suggestions::get_random( $pt, 3 ) );
}
$random = array_slice( $random, 0, $per_page );
$render_card = function ( $post ) {
setup_postdata( $post );
?>
<li class="fe-card">
<a class="fe-card-link" href="<?php echo esc_url( get_permalink( $post ) ); ?>">
<?php if ( has_post_thumbnail( $post ) ) : ?>
<span class="fe-card-thumb"><?php echo get_the_post_thumbnail( $post, 'medium', array( 'alt' => '' ) ); ?></span>
<?php endif; ?>
<span class="fe-card-body">
<span class="fe-card-title"><?php echo esc_html( get_the_title( $post ) ); ?></span>
<span class="fe-card-excerpt"><?php echo esc_html( wp_trim_words( get_the_excerpt( $post ), 18 ) ); ?></span>
</span>
</a>
</li>
<?php
};
$render_section = function ( $title, $posts ) use ( $render_card ) {
if ( empty( $posts ) ) {
return;
}
?>
<section class="fe-section">
<h2 class="fe-section-title"><?php echo esc_html( $title ); ?></h2>
<ul class="fe-card-grid">
<?php foreach ( $posts as $post ) : ?>
<?php $render_card( $post ); ?>
<?php endforeach; ?>
</ul>
</section>
<?php
};
/**
* Filters the 404 heading.
*
* @param string $title Default heading.
*/
$heading = apply_filters( 'fe_404_heading', __( 'Oops! That page can’t be found.', '404-enhancer' ) );
?>
<div class="fe-404">
<div class="fe-404-hero">
<?php if ( $image_url ) : ?>
<div class="fe-404-hero-image">
<img src="<?php echo esc_url( $image_url ); ?>" alt="<?php esc_attr_e( 'Illustration for the missing page', '404-enhancer' ); ?>">
</div>
<?php endif; ?>
<div class="fe-404-hero-text">
<h1 class="fe-404-heading"><?php echo esc_html( $heading ); ?></h1>
<?php if ( '' !== $path && '/' !== $path ) : ?>
<p class="fe-404-requested">
<?php
printf(
/* translators: %s: requested URL path. */
esc_html__( 'You requested %s, which doesn’t exist (anymore).', '404-enhancer' ),
'<code>' . esc_html( $path ) . '</code>'
);
?>
</p>
<?php endif; ?>
<?php if ( '' !== trim( (string) $message ) ) : ?>
<div class="fe-404-message"><?php echo wp_kses_post( $message ); ?></div>
<?php endif; ?>
<form role="search" method="get" class="fe-search-form" action="<?php echo esc_url( home_url( '/' ) ); ?>">
<label class="fe-sr-only" for="fe-search-input"><?php esc_html_e( 'Search the site', '404-enhancer' ); ?></label>
<input type="search" id="fe-search-input" name="s" value="<?php echo esc_attr( $search ); ?>" placeholder="<?php esc_attr_e( 'Search the site…', '404-enhancer' ); ?>">
<button type="submit"><?php esc_html_e( 'Search', '404-enhancer' ); ?></button>
</form>
<?php if ( $did_you_mean ) : ?>
<p class="fe-did-you-mean">
<?php
printf(
/* translators: %s: linked title of the suggested post. */
esc_html__( 'Did you mean %s?', '404-enhancer' ),
'<a href="' . esc_url( get_permalink( $did_you_mean ) ) . '">' . esc_html( get_the_title( $did_you_mean ) ) . '</a>'
);
?>
</p>
<?php endif; ?>
</div>
</div>
<?php
$render_section( __( 'Featured', '404-enhancer' ), $featured );
if ( '' !== $search ) {
$render_section(
sprintf(
/* translators: %s: search term derived from the requested URL. */
__( 'Related to “%s”', '404-enhancer' ),
$search
),
$related
);
}
$render_section( __( 'You might also like', '404-enhancer' ), $cross_links );
$render_section( __( 'While you’re here', '404-enhancer' ), $random );
?>
</div>
<?php
wp_reset_postdata();
get_footer();
+31
View File
@@ -0,0 +1,31 @@
<?php
/**
* Cleans up 404 Enhancer options and transients on uninstall.
*
* @package 404_Enhancer
*/
if ( ! defined( 'WP_UNINSTALL_PLUGIN' ) ) {
exit;
}
$fe_options = array(
'fe_custom_message',
'fe_featured_image_id',
'fe_enabled_post_types',
'fe_featured_post_ids',
'fe_suggestions_per_page',
);
foreach ( $fe_options as $fe_option ) {
delete_option( $fe_option );
}
global $wpdb;
$wpdb->query( // phpcs:ignore WordPress.DB.DirectDatabaseQuery
$wpdb->prepare(
"DELETE FROM {$wpdb->options} WHERE option_name LIKE %s OR option_name LIKE %s",
$wpdb->esc_like( '_transient_fe_gitea_' ) . '%',
$wpdb->esc_like( '_transient_timeout_fe_gitea_' ) . '%'
)
);