0

I need to display a meta tag in header for singular custom post type "communications" like this:

<meta name="citation_title" content="single post title is here" />

I tried to use this code :

<?php if ( is_singular( 'communications' ) ) {
        echo '<meta name="citation_title" content="' . the_title( '', '' ).'" />' . '';
} ?>

but the result was a title before the meta:

single post title is here<meta name="citation_title" content="" />

any help please?

1 Answer 1

3

Use the_title_attribute() to print the attribute. A post title might contain HTML, so you need the escaped content that this function returns.
Also suppress immediate print-out, because that will set the output in front of the echo statement.

if ( is_singular( 'communications' ) ) {
    $title = the_title_attribute( [ 'echo' => FALSE ] );
    echo '<meta name="citation_title" content="' . $title . '" />' . PHP_EOL;
}

Another question is why your theme knows so much about the post type. Custom post types should always be registered in a plugin. So that code should go to the plugin too. This is how the result could look like:

add_action( 'wp_head', 'add_citation_title' );

function add_citation_title() {

    if ( ! is_singular( 'communications' ) )
        return;

    $title = the_title_attribute( [ 'echo' => FALSE ] );
    echo '<meta name="citation_title" content="' . $title . '" />' . PHP_EOL;
}
3
  • you are great thanks a lot but I have another question please: when i use several codes, like your first one, to display several meta tags the result is displayed in one single row. how can i put each meta tag in one row please?
    – nisr
    Commented May 30, 2015 at 12:20
  • @nisr Add . PHP_EOL. See my edit.
    – fuxia
    Commented May 30, 2015 at 12:22
  • It worked !! You are the best, thank you very much
    – nisr
    Commented May 30, 2015 at 12:35

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.