1

我对此很陌生(了解 WP Guts),我想更好地了解 Hooks 和 Filters,但我无法从 Codex 中得到它。

我做了一个简单的测试,

这个想法是重写 get_title() 方法,以便从标题中删除“受保护:”语句,如果页面受到保护,有一个 protected_title_format 过滤器,我想使用它......

post-template.php中的那一行指定:

$protected_title_format = apply_filters('protected_title_format', __('Protected: %s'));

对于我可以从 CODEX 获得的内容,我需要删除该过滤器并添加我自己的过滤器,例如

remove_action('protected_title_format');
apply_filters('protected_title_format', __('MY OWN PAGE Protected: %s'));

使用,当然像

// Removing action
function remove_title_action() {
    remove_action('protected_title_format','get_the_title',3);
}
add_action('init','remove_title_action');

// Adding custom function
add_action('protected_title_format','fancy_title', 3, 4);

function fancy_title($id = 0) {
    $post = &get_post($id);
    $title = $post->post_title;

    echo "I'm the king of the world!... >" . $title . "< & >" . $post . "<";

    if ( !is_admin() ) {
    if ( !empty($post->post_password) ) {
        $protected_title_format = apply_filters('protected_title_format', __('MY OWN PAGE Protected: %s'));
        $title = sprintf($protected_title_format, $title);
    }
    }
    return apply_filters( 'the_title', $title, $post->ID );
}

我可以得到输出的回声,但我没有得到 $id(为此,没有 $title 或 $post),这个方法是 get_title() 的副本,除了受保护的部分字符串之外,它会删除所有内容。

任何人都可以向我解释这是如何工作的吗?谢谢


PS我想学习,这是这个问题的想法,不是有人告诉我“嘿,去post-template.php并改变它”,因为那样我会问“我更新WP时怎么样...... ?” !

4

1 回答 1

3

实际上,您可以比您尝试的更简单地执行此操作。不过,您走在正确的轨道上。

基本上,您要做的是创建自己的函数,该函数将删除 WordPress 标题的“受保护:”部分。最简单的方法是简单地创建一个函数,使用 preg_replace() 搜索“Protected:”文本并将其剥离。你可以很容易地让它用你自己的文本自动替换字符串。

这是一个执行此操作的示例函数。我们将 $title 作为参数并返回它的修改版本。

function remove_protected_text($title) {
  $match = '/Protected: /';
  $replacement = '';

  $title = preg_replace($match, $replacement, $title);
  return $title;
}

我们要做的下一件事实际上是将我们的函数添加到过滤器挂钩中。在这种情况下,我们感兴趣的过滤器挂钩是“the_title”。因此,我们在刚刚编写的函数下方添加以下行:

add_filter( 'the_title', 'remove_protected_text', 10);

这会将我们的函数添加remove_protected_text()到“the_title”过滤器中。在这种情况下,我使用第三个参数为我们的过滤器赋予 10 的优先级。这完全是可选的,但我认为这个过滤器的优先级很低。

所以我们的代码应该看起来像这样:

function remove_protected_text($title) {
    $match = '/Protected: /';
    $replacement = '';

    $title = preg_replace($match, $replacement, $title);
    return $title;
}
add_filter( 'the_title', 'remove_protected_text', 10);

将该代码添加到您主题中的 functions.php 文件中将允许它工作。您可以为 WordPress 的大部分输出文本的部分编写这样的过滤器。

更新

这是该函数的修订版本,它应该获取“受保护:”的翻译字符串并将其删除:

function remove_protected_text($title) {
    $protected = __('Protected: %s');
    $protected = preg_replace('/ %s/', '', $protected);

    $match = "/${protected}/";
    $replacement = '';

    $title = preg_replace($match, $replacement, $title);

    return $title;
}
add_filter( 'the_title', 'remove_protected_text');

基本上,这里唯一的变化是我们使用 __() 函数来翻译受保护的字符串,然后去除多余的位。这有点骇人听闻,我确信有更好的方法可以做到这一点,但它在我的测试中确实有效。

我在西班牙语版本的 WordPress 上对此进行了测试,它确实有效,因此请告诉我它是否适用于您的项目。

于 2009-08-27T17:21:04.520 回答