Files
wp-spaceapi-consumer/wp-api-consumer.php
2025-05-11 17:02:23 +01:00

49 lines
1.6 KiB
PHP
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

<?php
/**
* Plugin Name: WP API Consumer
* Plugin URI: https://gitea.alluna.pt/jfig/wp-api-consumer
* Description: Shows the live value of https://nodered.jfig.net/api/v1/door-open in a menu item or via shortcode.
* Version: 1.0
* License: GPL-2.0+
*/
defined( 'ABSPATH' ) || exit;
/**
* Fetch the Boolean once every 10 s (adjust TTL to taste).
*/
function ds_get_state() {
$state = get_transient( 'ds_state' );
if ( false === $state ) {
$r = wp_remote_get( 'https://nodered.jfig.net/api/v1/door-open', [ 'timeout' => 4 ] ); // 4 s hard stop
$state = is_wp_error( $r ) ? '' : trim( wp_remote_retrieve_body( $r ) );
set_transient( 'ds_state', $state, 10 );
}
return $state;
}
/**
* Returns a coloured dot (🟢 / 🔴) or ⚪ if the API is unreachable.
*/
function ds_render() {
$s = strtolower( ds_get_state() );
if ( 'true' === $s ) return '<span class="door-state door-open" aria-label="door open">🟢</span>';
if ( 'false' === $s ) return '<span class="door-state door-closed" aria-label="door closed">🔴</span>';
return '<span class="door-state door-unknown" aria-label="status unknown">⚪</span>';
}
add_shortcode( 'door_state', 'ds_render' ); // [door_state]
/**
* Automatically append the indicator to a menu (optional).
* Replace 'primary' with your themes menu slug if different.
*/
function ds_menu_item( $items, $args ) {
if ( 'primary' === $args->theme_location ) {
$items .= '<li class="menu-item menu-item-door-state">' . ds_render() . '</li>';
}
return $items;
}
add_filter( 'wp_nav_menu_items', 'ds_menu_item', 10, 2 );