WordPress:如何在您的自定义帖子类型内容中添加带有自定义字段的文本
在 WordPress 中, add_filter()
是一个函数,用于将自定义函数或现有的 WordPress 函数挂接到特定的过滤器操作。 过滤器是两种类型的 Hooks 之一,另一种是 Actions。 它们为函数提供了一种修改其他函数数据的方法,是 WordPress 插件功能的基石。
这是的基本语法 add_filter()
:
add_filter( string $tag, callable $function_to_add, int $priority = 10, int $accepted_args = 1 )
作为内容管理系统(CMS), WordPress 的设计与任何其他平台一样……无论是页面、帖子,还是自定义帖子,您都有标题和内容。 但并非所有内容都仅限于这两个选项。 一个例子是 缩写 我开发的图书馆 Martech Zone. 首字母缩略词具有三个要素……首字母缩略词本身、 定义 这表明首字母缩写词代表什么,以及对它的解释。
我能够使用以下方法轻松地为定义添加自定义字段 元盒,但该自定义字段并未在整个站点中发布。 一种方法是为存档和单个首字母缩略词页面构建一个自定义模板,我可以在其中提取自定义字段。 然而,这需要相当多的工作,而且必须在我需要该信息的任何地方完成——在存档、单个帖子、摘录和自定义帖子类型的提要中。
另一种方法是使用您的主题并在内容本身中添加该信息。 在这种情况下,我只想在前面加上一个简短的句子: {title} 是 {definition} 的缩写。 因为我也使用代码的首字母缩略词库,所以如果代码是数字,我也想修改前置文本: {title} 是 {definition} 的代码。 以下是示例:
0p 是零党的缩写 和 404 是 Not Found 的代码.
为此,我可以对概念、摘录、提要和 RSS 使用 add_filter 来添加适当的文本。 此外,我检查首字母缩略词是否为数字……在这种情况下它可能是代码。 (我意识到我可以进一步增强它,但现在还可以)。 在 的functions.php 我的档案
子主题,我只需添加以下函数,然后调用适当的过滤器以在整个站点中应用它:// Prepend text to the content of 'acronym' posts
add_filter('the_content', 'prepend_text_to_acronym');
add_filter('the_excerpt', 'prepend_text_to_acronym');
add_filter('the_content_feed', 'prepend_text_to_acronym');
add_filter('the_excerpt_rss', 'prepend_text_to_acronym');
function prepend_text_to_acronym($content) {
global $post;
// Check if it's an 'acronym' post
if($post->post_type == 'acronym') {
// Get the post title and the 'acronym_definition' field
$title = get_the_title($post->ID);
$definition = get_post_meta($post->ID, 'acronym_definition', true);
if (is_numeric($title)) {
$new_content = "<p>$title is the code for $definition.</p>";
} else {
$new_content = "<p>$title is the acronym for $definition.</p>";
}
// Prepend the new content to the original content
$content = $new_content . $content;
}
return $content;
}
现在,当你看到我的 缩写 存档,您会看到每个条目的摘录中都带有该句子。 它是单个帖子页面上的独立段落。