首页 > 解决方案 > 创建可在各种元素/类中的可重用 ACF 字段

问题描述

我在它自己的文件中有以下代码,它获取一个 ACF 字段并输出它。

<?=get_field('text') ?>

然后我使用 PHP include 将其包含在另一个模板文件中,这意味着我在整个站点中都有可重用的字段。这在过去运作良好,因为我可以创建一致的“文本”字段,例如:<h1>My Text field</h1>

但是,我想通过编写某种函数来进一步扩展这一点,该函数允许我调用 PHP 包含,同时还分配容器标签(h1、h2 等)以及可选类:

<h1>My Text field</h1>

<h2>My Text field</h2>

<p>My Text field</p>

<h1 class="myClass">My Text field</h1>

这可能吗?

标签: php

解决方案


你可以这样做:

<?php

class functions{
    public static function get_field($text = 'Default', $tag = 'p', $class = false){
        if($class){
           $class = ' class="' . $class . '"'; 
        }
        return '<' . $tag . $class . '>' . $text . '</' . $tag . '>';
    }
}

echo functions::get_field('My Text', 'h1', 'my-class');
?>

在 HTML 中

<h1 class="my-class">My Text</h1>

希望它能让您了解如何扩展此方法。


推荐阅读