There are multiple ways to call get_field( 'short_title' )
only once:
Using global
variable:
You can declare the $acfvalue
variable global
and then use it inside your function. Since global
scope may have the same variable name, it's better to prefix it so that it doesn't create conflicts:
function hprice() {
global $wpse256370_acfvalue;
if( ! isset( $wpse256370_acfvalue ) ) {
$wpse256370_acfvalue = get_field( 'short_title' );
}
return '<h2>'. $wpse256370_acfvalue . " Price list in India" . '</h2>';
}
add_shortcode( 'pprice', 'hprice' );
function hspecs() {
global $wpse256370_acfvalue;
if( ! isset( $wpse256370_acfvalue ) ) {
$wpse256370_acfvalue = get_field( 'short_title' );
}
return '<h2>'. $wpse256370_acfvalue . " Full Specification" . '</h2>';
}
add_shortcode( 'pspecs', 'hspecs' );
function hreview() {
global $wpse256370_acfvalue;
if( ! isset( $wpse256370_acfvalue ) ) {
$wpse256370_acfvalue = get_field( 'short_title' );
}
return '<h2>'. $wpse256370_acfvalue . " Review" . '</h2>';
}
add_shortcode( 'preview', 'hreview' );
Using static
variable:
Using static
variable inside a function will be better than the global
variable way. Since it'll not pollute the global scope, so there is no need to prefix the variable name in this case:
function wpse256370_acfvalue() {
static $acfvalue;
if( ! isset( $acfvalue ) ) {
$acfvalue = get_field( 'short_title' );
}
return $acfvalue;
}
function hprice() {
return '<h2>'. wpse256370_acfvalue() . " Price list in India" . '</h2>';
}
add_shortcode( 'pprice', 'hprice' );
function hspecs() {
return '<h2>'. wpse256370_acfvalue() . " Full Specification" . '</h2>';
}
add_shortcode( 'pspecs', 'hspecs' );
function hreview() {
return '<h2>'. wpse256370_acfvalue() . " Review" . '</h2>';
}
add_shortcode( 'preview', 'hreview' );
Using class
:
The best way is to use a class, because by using a class you also avoid possible function name conflicts:
class WPSE_256370_Shortcode {
private static $instance;
private $acfvalue;
public static function init() {
self::getInstance();
add_shortcode( 'pprice', array( self::$instance, 'pprice' ) );
add_shortcode( 'pspecs', array( self::$instance, 'pspecs' ) );
add_shortcode( 'preview', array( self::$instance, 'preview' ) );
}
public static function getInstance() {
if( ! isset( self::$instance ) ) {
self::$instance = new self;
}
return self::$instance;
}
public function acfvalue() {
if( ! isset( $this->acfvalue ) ) {
$this->acfvalue = get_field( 'short_title' );
}
return $this->acfvalue;
}
public function pprice() {
return '<h2>'. $this->acfvalue() . " Price list in India" . '</h2>';
}
public function pspecs() {
return '<h2>'. $this->acfvalue() . " Full Specification" . '</h2>';
}
public function preview() {
return '<h2>'. $this->acfvalue() . " Review" . '</h2>';
}
}
WPSE_256370_Shortcode::init();