Archived topic
Prefix the post title h1
24 replies · Started by Tesco on July 28, 2022
I´m trying to add a prefix to the post title h1, if the post it´s on specific categories.
Any way to do this on elements using a hook or something?
Hi there,
what is the prefix ? Do you have an example ?
Hi, yes!
if in_category ONE, it would be Prefix For Cat One if in_category TWO, it would be Prefix For Cat Two, etc..
If its just a prefix to the H1 on the single post then you can use a snippet like this:
add_filter( 'generate_get_the_title_parameters', function( $params ) {
$prefix = '';
$category = get_the_category();
$cat_name = $category[0]->cat_name;
switch ( $cat_name ) {
case 'Category One':
$prefix = 'Your category one prefix';
break;
case 'Category Tne':
$prefix = 'Your category two prefix';
break;
}
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;
} );
It works fine on category one, but in the category two, it only shows the category name (not is prefix).
And on category two, it shows the category name, after the H1 (not before...).
Hmmm.... it works for me, can you share your code ?
Just the same of yours. I only changed the category name and the prefix.
Perhaps this can help you finding the "bug":
Category One is a two word name (cat two)
Category Two is a one word name (thiscat)
Can you share it anyway ? As there is nothing in my code that would output either the category name or display anything after the title
Sure!
I'm not understanding this either.
Here you are:
add_filter( 'generate_get_the_title_parameters', function( $params ) {
$prefix = '';
$category = get_the_category();
$cat_name = $category[0]->cat_name;
switch ( $cat_name ) {
case 'Cat One':
$prefix = 'Your category one prefix';
break;
case 'CatTwo':
$prefix = 'Your category two prefix - ';
break;
}
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;
} );
Do you have any other custom functions on the site ?
Not regarding this
Can i see a post on the site where the category name is being displayed instead of the prefix?
It's on localhost
You will need to debug by disabling other plugins and other custom functions. As i can't see what could be causing that within the code i provided, and i cannot replicate the issue locally.
I will try that. Keep you posted.