有多种呼叫方式get_field( \'short_title\' )
仅一次:
使用global
变量:
您可以声明
$acfvalue
变量
global
然后在函数中使用它。自从
global
作用域可能具有相同的变量名称,最好在其前面加前缀,以免产生冲突:
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\' );
使用static
变量:
使用
static
函数中的变量将优于
global
可变方式。由于它不会污染全局范围,因此在这种情况下无需在变量名称前加前缀:
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\' );
使用class
:
最好的方法是使用类,因为使用类还可以避免可能的函数名冲突:
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();