开发者

Wordpress: error in callback function when applying filter to customize page title

开发者 https://www.devze.com 2023-03-10 06:00 出处:网络
I have some templates where I need to customize the page title according to user selection. I have added a filter hook to \'wp_title\' tag following Codex docs but when the filter is applied I\'m rece

I have some templates where I need to customize the page title according to user selection. I have added a filter hook to 'wp_title' tag following Codex docs but when the filter is applied I'm receiving a warning, I'd say an error, regarding parameters in the callback function declaration:

Warning: Missing argument 4 for buildPageTitle() in /Applications/XAMPP/xamppfiles/htdocs/.../blog/wp-content/themes/.../inc/my_functions.php on line 2

my_functions.php

1  <?php
2  function buildPageTitle($sep, $echo, $seplocation, $brand) {
3    return $brand.$sep;
4  }
5  ...

Template

<?php
/*
Template Name: By brand-countries
*/

$brandLabel = get_query_var('brand');
require_once('inc/dbConn.php');
require_once('inc/get_brand_data.php');
require_once('inc/my_functions.php');

add_filter('wp_title', 'buildPageTitle', 10, 4);
apply_filters('wp_title', $sep, false, $seplocation, $brand);
get_header();
?>

I can solve the prob开发者_JAVA百科lem declaring $brand var as global in the buildPageTitle() function but I prefer to pass it as a parameter as in other templates different vars will be needed


I think you have a wrong idea how WordPress filters work. There is a function wp_title() and a filter wp_title. You call the function, which does some work to create a title, and then passes its output to the filter, so other code can further customize the result.

The function and the filter do not necessarily use the same arguments. For the function wp_title() you can pass the separator, whether to echo the title or not, and the separator location. The filter can get the title as wp_title() has created it, the separator and the separator location. When setting up the filter hook (via add_filter()) you specify how many arguments you need: 1 (the default), 2 or 3. You can't get more than three arguments because wp_title() does not pass more than three arguments to the wp_title filter.

So you should not have to call apply_filters() yourself. You call wp_title() (probably in your header.php template file, and this function calls the filter itself.

If you want to access your brand variable you should either put it in a global variable or let your buildPageTitle() function call some other function that will return it. What strategy to use depends on your situation. Can you tell more about the different templates and the title formats you want to use there?

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号