first trial v2
This commit is contained in:
48
wp-api-consumer.php
Normal file
48
wp-api-consumer.php
Normal file
@@ -0,0 +1,48 @@
|
||||
<?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 theme’s 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 );
|
||||
|
||||
Reference in New Issue
Block a user