If you want to fetch the data from a custom field named wpse_desc
:
then here’s one way to do that with your code snippet:
function wpse_custom_meta_description()
{
// Nothing to do
if ( ! is_single() )
return;
// Fetch our custom field value
$desc = get_post_meta( get_queried_object_id(), 'wpse_desc', true );
// Output
if( ! empty( $desc ) )
printf(
'<meta name="description" content="%s" />',
esc_attr( trim( $desc ) )
);
}
add_action( 'wp_head', 'wpse_custom_meta_description' , 2 );
It’s important to escape the value of the content attribute, because you don’t want e.g. authors of your site to be able to write something like:
><script>alert('Hello World!');</script><
We might also want to strip the tags out with wp_strip_all_tags()
and limit the word count with wp_trim_words()
, that also uses wp_strip_all_tags()
, but we should keep in mind that it would still allow very long words. If you need a maximum length, then you might need to look further into that, I’m sure there are various approaches out there.
Here we prefix the custom field name with the wpse_
prefix, to avoid possible name collisions.
Hope you can adjust it to your needs, like using post excerpt or post content fallbacks.