Advanced Views Docs
Live PlaygroundDownload PluginGet PRO
  • πŸ’‘Help Centre
  • ⚑Getting Started
    • Introduction
      • Key Aspects
      • Creating Your First View
      • Creating Your First Card
      • Plugin Terms
      • Plugin Interface
        • Field Options
    • Installation
      • Advanced Views Lite
      • Advanced Views Pro
      • Comparison Table
      • Upgrading from Lite to Pro
    • Supported data vendors
    • Starter theme
  • 🌟Display Content
    • WordPress
      • Post
      • Taxonomy terms
      • User
      • Comments
      • Menus
    • WooCommerce Product
    • Meta fields
      • Basic fields
        • Number
      • Content fields
        • Image
        • File
        • WYSIWYG
        • oEmbed
        • Gallery
      • Choice fields
        • Select/checkbox/radio
        • True / False
      • Relationship fields
        • Link
        • Post_object
        • Page Link
        • Relationship
        • Taxonomy
        • User
      • Advanced fields
        • Google Map
        • Google Map Multiple Markers
        • ACF OpenStreetMap Field
        • Date/time picker
      • Layout fields
        • Group (Pro)
        • Repeater (Pro)
        • Flexible (Pro)
    • Object fields
    • Custom Data (Pro)
    • Custom Gutenberg Blocks (Pro)
    • Mount Points (Pro)
    • Front-end assets management (Pro)
  • πŸ¦Έβ€β™‚οΈQuery Content
    • Basic Filters
    • Meta Filters (Pro)
      • Current Post
      • Comparison
      • Dynamic Injection
    • Taxonomy Filters (Pro)
    • Pagination (Pro)
    • Custom Data (Pro)
  • πŸ†Shortcode Attributes
    • Common Arguments
    • View Shortcode
    • Card Shortcode
  • πŸ§™β€β™‚οΈTemplates
    • Customizing the Template
    • Template engines
      • Twig
      • Blade
    • CSS & JS
      • BEM Methodology
      • WordPress Interactivity API
    • File system storage
    • Pre-built components
    • Reusable components library (Pro)
    • Live reload
    • Multilingual
    • Custom Ajax & Rest API (Pro)
  • β˜•Guides
    • Display Custom Post Type (CPT) on another post
    • Display Employees (CPT) of a Company (CPT)
    • Display Nested Repeater Fields
    • Map Marker from ACF Image
    • Display all CPT items on a single map
  • πŸ› οΈTools
    • Export/Import
    • Demo Import
    • Settings
    • Preview
  • 🏹Troubleshooting
    • Compatibility
    • Report a bug
    • Payment Issues
    • Lite Support (Forum)
    • Pro Support
  • βš™οΈCustomization
    • Filters and Hooks
      • View
      • Card
    • Suggest a feature
    • Performance
Powered by GitBook
On this page
  • About the feature
  • 1. Custom query arguments
  • 2. Custom template arguments
  • Custom Data snippet
  • PHP-DI support
  • Example

Was this helpful?

  1. Query Content

Custom Data (Pro)

PreviousPagination (Pro)NextCommon Arguments

Last updated 11 months ago

Was this helpful?

The page below describes the Custom Data feature for Card. You can read about the Custom Data feature for View .

About the feature

Using the Custom Data feature you can add extra arguments to the Card query, and extra variables to the Card template.

1. Custom query arguments

Card provides a user interface for all the main . However, to avoid overloading the user interface, we haven't included all possible arguments.

In advanced cases, you may need to use arguments that are missing from the UI. In the Pro Edition, you can achieve this by using the Custom Data feature, which can be found under the Advanced tab of your Card settings.

This feature allows you to extend the current Card by merging them with arguments returned from a custom PHP snippet. The data return should return an associative array, which will be merged with the settings from the UI.

2. Custom template arguments

Using this feature, you can also add any custom variables to your Card template.

Tip: Use the custom template arguments only for data that isn't supported by Advanced Views.

Bad use case: your Card queries posts of the current user, and you need to display a user name in top of the list. Instead of creating a new View for displaying the user info, and pasting View's shortcode to the Card template, you use the custom template arguments.

Good use case: your Card queries WooCommerce Products by specific author (seller), and you need to display a live seller's rate that is deducted dynamically, and not available in the User meta.

Custom Data snippet

The field with the snippet can be found in the Advanced tab of your Card.

The snippet is a PHP code, which must return an instance of the Custom_Card_Data class.

  • using the get_variables() method you can pass custom variables to the Card template

  • using the get_query_arguments() method you can pass custom arguments to the Card query

  • using the get_default_variables() method you can access to the default twig variables (that filled out automatically by the plugin)

  • using the get_default_query_arguments() method you can access to the default query arguments (that filled out automatically by the plugin)

  • using the get_container() method you can access the PHP-DI Container (see the related chapter of this page)

<?php

declare(strict_types=1);

use Org\Wplake\Advanced_Views\Pro\Bridge\Cards\Custom_Card_Data;

return new class extends Custom_Card_Data {
    /**
     * @return array<string,mixed>
     */
    public function get_variables(): array
    {
        return [
            // "another_var" => $this->get_custom_arguments()["another"] ?? "",
        ];
    }

    /**
     * @return array<string,mixed>
     */
    public function get_variables_for_validation(): array
    {
        // it's to return dummy data here [ "another_var" => "dummy string", ]
        return $this->get_variables();
    }

    public function get_query_arguments(): array
    {
        // https://developer.wordpress.org/reference/classes/wp_query/#parameters
        return [
            // "author" => get_current_user_id(),
            // "post_parent" => $this->get_custom_arguments()["post_parent"] ?? 0,
        ];
    }
    
     /**
     * @return array<string,mixed>
     */
    public function get_ajax_response(): array
    {
        // $message = $this->get_container()->get(MyClass::class)->myMethod();
        return [
	   // "message" => $message,
	];
     }
};

Tip: if you pass custom variables using the get_variables() method, we recommend to change the get_variables_for_validation() method and return dummy data there.

Advanced Views has the built-in automatic template validation, which called on the Save action. There is no sense to return real data in this case, and it's better to return dummy data, to avoid potential issues with missing functions.

For example, if you use WP functions inside, they may be front-end only, and aren't available in the wp-admin area, which will lead to the failed validation.

PHP-DI support

Example

A simple example is below:

1. Define a container in your theme:

<?php

use DI\Container;

$container = new Container();

add_filter( 'acf_views/container', function () use ( $container ) {
	return $container;
} );

3. Request Container inside the Custom_Data:

<?php

declare(strict_types=1);

use Org\Wplake\Advanced_Views\Pro\Bridge\Cards\Custom_Card_Data;
use MyTheme\MyClass;

return new class() extends Custom_Card_Data {
    /**
     * @return array<string,mixed>
     */
    public function get_variables(): array {
       $container = $this->get_container();

       if ( null === $container ) {
          return array();
       }

       $my_class = $container->get( MyClass::class );

       return array(
          'my_var_with_complex_calculation' => $my_class->get_var(),
       );
    }
};

You won't see a significant benefit if your MyClass has no dependencies. But let's say the class has 2-3 constructor arguments (e.g., a logger and a theme object). To get the MyClass instance, you would need to create those instances initially. Furthermore, one of those arguments may have its own arguments, and your creation code will turn into a multi-line creation.

Additionally, PHP-DI supports and encourages the use of interfaces, so you can call

->get(MapInterface::class)->calculate() in your code, while defining which exact class should be used for each interface in the container configuration.

using the get_ajax_response() method you define the Ajax callback for the block.

using the get_custom_arguments() method you can access the . The field is available in the both methods above.

is a well-known dependency injection container. If you haven't used it, we recommend checking it out and harnessing its capabilities.

Advanced Views supports PHP-DI out-of-the-box. To simplify access to your theme's PHP class instances inside the Custom_Data instances, you can employ the PHP-DI container. To do this, you need to define the container in your theme using the hook. Then, you can access it using the get_container() method in any method of the Custom_Data class.

If you're unfamiliar with , the benefits of the code above may be unclear to you. We could replace $container->get with new MyClass() and it would work perfectly. However, the container is a powerful tool, especially for more complex cases.

With PHP-DI, you don't need to worry about the constructor, as PHP-DI will use to get the necessary instances and pass them to the constructor on the fly.

An additional benefit is that the ->get method, ->make, creates the instance only once, reusing it for other calls. This way, you get a smart 'global' variables pool, allowing you to handle dependencies easily and efficiently.

Unlike the , which is , it doesn't turn your code into single-instance classes. You still define constructors, clearly specifying class dependencies, while avoiding the hassle of manual creation.

πŸ¦Έβ€β™‚οΈ
here
WP_Query arguments
WP_Query arguments
Read more
custom arguments passed to the shortcode
PHP-DI
PHP-DI concepts
PHP's reflection feature
unlike
singleton pattern
considered an anti-pattern
advanced_views/container