Home › Forums › General Issues › Meta title and description via ACF
I have a fully working code to collect the data of 2 meta fields (title and description) on all pages in case the auto generated meta is not suitable. It works on every page exact 2:
– The WordPress blog overview (archive)
– The WooCommerce shop page (also archive page)
The 2 ACF fields within the pages look like to be totally ignored.
Any reason for that? And how to overwrite this behavior?
I understand that both pages are like kinda system pages where I can’t directly edit the content but I do want to edit the generated meta data.
Here’s the working code (except for the 2 archive pages):
// Add social media friendly meta tags
function yl_add_meta_tags_to_wp_head() {
setup_postdata( $post );
$custom_meta_title = get_field('yl_meta_title' );
$custom_meta_description = get_field( 'yl_meta_description' );
if ($custom_meta_title) {
$meta_title = $custom_meta_title;
} else {
$meta_title = get_the_title();
}
if ($custom_meta_description) {
$meta_description = $custom_meta_description;
} else {
$meta_description = substr(wp_strip_all_tags(get_the_excerpt()),0,150) . '...';
}
if ( class_exists( 'woocommerce' ) && is_product() ) {
$meta_type = 'product';
} elseif ( is_single() ) {
$meta_type = 'article';
} else {
$meta_type = 'website';
}
echo '
<meta name="meta_name" content="' . $meta_title . '" />
<meta name="description" content="' . $meta_description . '" />
';
}
add_action( 'wp_head', 'yl_add_meta_tags_to_wp_head', 1, 1 );
On an archive page get_field(), get_the_excerpt() and get_the_title() will all fail to return any value. These all depends on the global post and on archive pages there isn’t one.
In order to do this you need to have a value stored somewhere, like on an options page or something. Then you need to detect that you are showing an archive page and then get the values you want to set from wherever they are stored.
Thanks for explaining John,
I thought it had to be something like that…
I am going for a different approach then.
You must be logged in to reply to this topic.
Welcome to the Advanced Custom Fields community forum.
Browse through ideas, snippets of code, questions and answers between fellow ACF users
Helping others is a great way to earn karma, gain badges and help ACF development!
We use cookies to offer you a better browsing experience, analyze site traffic and personalize content. Read about how we use cookies and how you can control them in our Privacy Policy. If you continue to use this site, you consent to our use of cookies.