Add "Pull Page" functionality to admin bar and REST API endpoint

This commit is contained in:
Matt Batchelder
2026-02-21 12:19:19 -05:00
parent d56d46490a
commit 158fb53d24
3 changed files with 226 additions and 0 deletions

View File

@@ -8,6 +8,82 @@
if ( ! defined( 'ABSPATH' ) ) exit;
// ─── Admin bar pull button (front-end) ──────────────────────────────────────
add_action( 'admin_bar_menu', function ( WP_Admin_Bar $wp_admin_bar ) {
// Front-end only, logged-in admins, singular pages/posts
if ( is_admin() ) return;
if ( ! is_user_logged_in() ) return;
if ( ! current_user_can( 'manage_options' ) ) return;
if ( ! is_singular() ) return;
$post = get_queried_object();
if ( ! $post instanceof WP_Post ) return;
$wp_admin_bar->add_node( [
'id' => 'oribi-sync-pull',
'title' => '<span class="ab-icon dashicons dashicons-download" aria-hidden="true"></span><span class="ab-label">Pull Page</span>',
'href' => '#',
'meta' => [
'title' => 'Pull this page and theme from Git',
],
] );
}, 100 );
// Front-end script that wires up the admin bar pull button
add_action( 'wp_footer', function () {
if ( ! is_user_logged_in() ) return;
if ( ! current_user_can( 'manage_options' ) ) return;
if ( ! is_singular() ) return;
if ( ! is_admin_bar_showing() ) return;
$post = get_queried_object();
if ( ! $post instanceof WP_Post ) return;
$api_url = rest_url( 'oribi-sync/v1/pull-page' );
$nonce = wp_create_nonce( 'wp_rest' );
$post_id = (int) $post->ID;
?>
<script>
(function () {
'use strict';
var btn = document.getElementById('wp-admin-bar-oribi-sync-pull');
if (!btn) return;
btn.addEventListener('click', function (e) {
e.preventDefault();
var link = btn.querySelector('a');
var label = btn.querySelector('.ab-label');
if (link) { link.style.opacity = '0.5'; link.style.pointerEvents = 'none'; }
if (label) { label.textContent = 'Pulling…'; }
fetch(<?php echo wp_json_encode( $api_url ); ?>, {
method: 'POST',
credentials: 'same-origin',
headers: {
'Content-Type': 'application/json',
'X-WP-Nonce': <?php echo wp_json_encode( $nonce ); ?>
},
body: JSON.stringify({ post_id: <?php echo $post_id; ?> })
})
.then(function (r) { return r.json(); })
.then(function () {
// Hard reload — append a cache-busting param to force a fresh response
var url = new URL(window.location.href);
url.searchParams.set('_nocache', Date.now());
window.location.replace(url.toString());
})
.catch(function (err) {
if (label) { label.textContent = 'Pull Page'; }
if (link) { link.style.opacity = ''; link.style.pointerEvents = ''; }
alert('Oribi Sync pull failed: ' + err);
});
});
})();
</script>
<?php
} );
// ─── Register admin menu ──────────────────────────────────────────────────────
add_action( 'admin_menu', function () {
add_options_page(