Shaun Taylor
Shaun Taylor

Reputation: 972

Custom Page Titles and Descriptions on WooCommerce Category Pages

I have used Advanced Custom Fields to add a custom page title field on all of my pages, posts, categories and products.

In order to remove the default <title> tag and ensure this field pulls through correctly, I have used the following function inside my functions.php file:

/* Remove Default <title> tag */

remove_action( 'wp_head', '_wp_render_title_tag', 1 );


// Add new <title> and description tags 

function child_theme_head_script() { ?>
  <title><?php the_field('seo_page_title'); ?></title>
  <meta name="description" content="<?php the_field('seo_page_description'); ?>"/>
  <!-- Your HTML goes here -->
<?php }
add_action( 'wp_head', 'child_theme_head_script' );

This works fine across the site apart from on my category pages here: http://staging.morningsidepharm.com/products/branded-medicines

On the category pages, it seems to take the title from the first product that appears on the page... For the page above, the page title is showing as: Bimizza (Desogestrel Ethinylestradiol) Tablets Branded Medicine | Morningside Pharmaceuticals

Rather than just: Branded Medicine | Morningside Pharmaceuticals

I thought wp_head in the function would target the head of all Wordpress pages, then remove the title tag and add the custom tag... It seems to be doing this correctly actually, but it's just adding the data from the first product rather from the category. The category looks like this is it's any help:

enter image description here

The SEO files of which, correspond to the: <?php the_field('seo_page_title'); ?> and <?php the_field('seo_page_description'); ?>

Can anyone point me in the right direction? I'm not sure where I'm going wrong...

** UPDATE ** ** UPDATE **

I have since tried this, but it doesn't seem to have an effect...

/* Remove Default <title> tag */

remove_action( 'wp_head', '_wp_render_title_tag', 1 );


// Add new <title> and description tags 

$term = get_queried_object();
$title = get_field('seo_page_title', $term);
$desc = get_field('seo_page_description', $term);

function child_theme_head_script() { ?>
  <title><?php echo $title; ?></title>
  <meta name="description" content="<?php echo $desc; ?>"/>
  <!-- Your HTML goes here -->
<?php }
add_action( 'wp_head', 'child_theme_head_script' );

Upvotes: 0

Views: 1506

Answers (1)

Peter HvD
Peter HvD

Reputation: 1661

the_field() can only be used in a Loop, which is why it's doing this as it's pulling the data from the current Loop item. If you want to target the taxonomy's field, you need to pass a reference to that taxonomy to the function.

I'd suggest something like this:

$term = get_queried_object();
the_field('seo_page_title', $term);

Here's the relevant page in ACF's documentation: https://www.advancedcustomfields.com/resources/adding-fields-taxonomy-term/

Upvotes: 2

Related Questions