Skip to content

Instantly share code, notes, and snippets.

@kevindaus
Forked from Crocoblock/macro-example.php
Last active November 24, 2022 12:14
Show Gist options
  • Save kevindaus/acef207901fd9d8f9b63d5c9af2257c2 to your computer and use it in GitHub Desktop.
Save kevindaus/acef207901fd9d8f9b63d5c9af2257c2 to your computer and use it in GitHub Desktop.
How to create custom macro in Crocoblock JetEngine
<?php
/**
* Heres how to add custom macro for JetEngine.
* In This example - get the current user property, such as ID, user_email, etc.
* Note!
* Register macros on jet-engine/register-macros action only,
* as the base macro class \Jet_Engine_Base_Macros is not available before that action;
* after it - all macros are registered already
*/
add_action( 'jet-engine/register-macros', function(){
/**
* Current_User_Prop class.
* Adds macro, that returns given property of the current user.
*
* Has methods (all JetEngine macros classes should have those):
* macros_tag() - sets macros tag
* macros_name() - sets human-readable macros name for UI
* macros_callback() - function that returns needed value
* macros_args() - optional argument list for the macro; argument format is the same as in Elementor
* https://developers.elementor.com/docs/controls/regular-control/
* In this example, the macro has one control: 'prop_key'
* which is the property, that should be get from the current user
*
*/
class Current_User_Prop extends \Jet_Engine_Base_Macros {
/**
* Macros tag - this macro will look like %current_user_prop|ID% if typed manually
*/
public function macros_tag() {
return 'current_user_prop';
}
/**
* Macros name in UI
*/
public function macros_name() {
return esc_html__( 'Current user property', 'jet-engine' );
}
/**
* Macros arguments - see this https://developers.elementor.com/docs/controls/regular-control/ for reference
* An empty array may be returned if the macro has no arguments
*/
public function macros_args() {
return array(
'prop_key' => array(
'label' => __( 'Property', 'jet-engine' ),
'type' => 'text',
'default' => '',
),
);
}
/**
* Macros callback - gets existing property from the current logged in user
*/
public function macros_callback( $args = array() ) {
$prop_key = ! empty( $args['prop_key'] ) ? $args['prop_key'] : null;
$object = wp_get_current_user();
if ( $object && 'WP_User' === get_class( $object ) ) {
$user = $object;
}
if ( ! $user || ! isset( $user->$prop_key ) ) {
return 'prop not found';
}
return $user->$prop_key;
}
}
/**
* Create an instance of Current_User_Prop to add current_user_prop macro
* of course you may create a separate file with the class, include it instead of declaring the class right in the action,
* and then create an instance of it
*/
new Current_User_Prop();
} );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment