Archived topic
Prefix the post title h1
24 replies · Started by Tesco on July 28, 2022
I disabled all plugins and the problem remains...
However, this seem to work except for posts that doesn't have one of the both categories:
add_filter( 'generate_get_the_title_parameters', 'filter_custom_post_title_by_cat' );
function filter_custom_post_title_by_cat( $title ) {
if (has_category( 'Cat One' )){ $prefix = 'My category one prefix - ';}
else if (has_category( 'Cat Two' )){$prefix = 'My category two prefix - ';}
else {}
if ( is_single() && $prefix ) {
$params = array(
'before' => sprintf(
'<h1 class="entry-title"%1$s>%2$s ',
'microdata' === generate_get_schema_type() ? ' itemprop="headline"' : '',
$prefix
),
'after' => '</h1>',
);
}
return $params;
}
I have some questions though:
- Can this be improved?
- It's all OK?
- What am I missing for posts that are not on the categories?
What should happen to a post that has neither category ?
Hi,
When has none of the categories (other than those two), it should show the H1 title without prefix.
Your callback: function filter_custom_post_title_by_cat( $title ) { os passing the $title variable which isn't used, change that to the $param.
That way $param is loaded with the default value of the filter, and if nothing changes that gets returned back to the filter.
Can you exemplify?
Because this way, the functions doesn't show any title for the other cats.
Thanks!
The callback and the return need to include the same variable:
The callback: function filter_custom_post_title_by_cat( $params ) {
And we return: return $params;
So when the Callback is made, it loads the existing $params into the the $params variable.
So IF your callback doesn't modify the $params it will return the original unchanged one.
The code will look like this:
add_filter( 'generate_get_the_title_parameters', 'filter_custom_post_title_by_cat' );
function filter_custom_post_title_by_cat( $params ) {
if ( is_single() ){
if ( has_category( 'Health Tips' )){ $prefix = 'My category one prefix - ';}
if ( has_category( 'Sport' )){ $prefix = 'My category two prefix - ';}
}
if ( $prefix ) {
$params = array(
'before' => sprintf(
'<h1 class="entry-title"%1$s>%2$s ',
'microdata' === generate_get_schema_type() ? ' itemprop="headline"' : '',
$prefix
),
'after' => '</h1>',
);
}
return $params;
}
if ( has_category( ...
if ( has_category( ...
if ( has_category( no category...?
This: if ( has_category( no category...? is not required.
The $param variable exists in the GP generate_get_the_title_parameters filter hook. See here.
So in none of the conditions are met, the function will return the default $param.
Got it working with your code above.
Thanks!
Glad to hear that!