PHP code example of cloak-labs / wp-virtual-fields

1. Go to this page and download the library: Download cloak-labs/wp-virtual-fields library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

cloak-labs / wp-virtual-fields example snippets


register_virtual_fields(['post', 'page', 'testimonial'], [
  VirtualField::make('pathname')
    ->value(fn ($post) => parse_url(get_permalink($post->ID), PHP_URL_PATH),
  VirtualField::make('featured_image')
    ->value(function ($post) {
      $image_id = get_post_thumbnail_id($post->ID);
      $sizes = ['medium', 'large', 'full'];
      $result = [];

      foreach ($sizes as $size) {
        $img = wp_get_attachment_image_src($image_id, $size);
        $url = is_array($img) ? $img['0'] : false;
        $result[$size] = $url;
      }

      return $result;
    })
]);

[ // WP_Post object
  ...
  'pathname' => '/blog/post-xyz/',
  'featured_image' => [
    'medium' => 'https://example.com/wp-content/uploads/2023/10/example-img-300x225.jpg',
    'large' => 'https://example.com/wp-content/uploads/2023/10/example-img-1024x768.jpg',
    'full' => 'https://example.com/wp-content/uploads/2023/10/example-img.jpg',
  ]
  ...
]

register_virtual_fields(['post', 'page'], [
  VirtualField::make('pathname')
    ->value(fn ($post) => parse_url(get_permalink($post->ID), PHP_URL_PATH)
    ->excludeFrom(['rest']) // exclude from REST API
]);