• I want the opening lines of each post to be meta description of the post page (only post page so the script below isn’t what I’m looking for yet). Here’s my code that I placed in header.php:

    <meta name="description" content="<?php if ( is_home() ) { print("MY DESCRIPTION FOR HOMEPAGE");} else { echo the_excerpt(); } ?>" />

    The problem is that the_excerpt(); (also get_the_excerpt(), the_content()) shows nothing.
    the_title(); shows the title and other things like the_permalink(); work fine in this place.

    the_excerpt(); works fine on my homepage in loop showing all the posts but it doesn’t work in header.php in meta tag.

Viewing 6 replies - 1 through 6 (of 6 total)
  • The template tag, the_content(), and the_excerpt(), are meant to be used in The Loop.

    Thread Starter flow01

    (@flow01)

    Thanks for your quick response MichaelH!

    So, how do I use The Loop to get the excerpt of the current post? I’m sorry but I’m not a WP expert (nor PHP expert) and it would take me hours to read and understand those articles about The Loop and template tags.

    PS
    For some reason the_title() and other template tags (except the_excerpt()) does work in header.php without The Loop.

    Well $posts[0]->post_content and $posts[0]->post_excerpt will contain those values (at least those values for the ‘first’ post in a given query).

    Thread Starter flow01

    (@flow01)

    Okay, I’m using the loop and it works almost fine. The only problem is that it shows too many words (I need only 20-25) and it ends with “[…]”. I’d like it to end with “…”

    <?php if (is_single()) : if ( have_posts() ) : while ( have_posts() ) : the_post(); ?>
    <meta name="description" content="<?php the_excerpt(); ?>" />
    <?php endwhile; endif; elseif(is_home()) : ?>
    <meta name="description" content="MY DESCRIPTION FOR HOMEPAGE" />
    <?php endif; ?>
    Thread Starter flow01

    (@flow01)

    Ahh, and I don’t want to use:

    function new_excerpt_length($length) {
    	return 20;
    }
    add_filter('excerpt_length', 'new_excerpt_length');

    because it will make my excerpts on homepage shorter too

    use ‘get_the_excerpt()’ and shorten it yourself with php string operations:

    so, change from this:

    <meta name="description" content="<?php the_excerpt(); ?>" />

    to this:

    <meta name="description" content="<?php $words = explode(' ', get_the_excerpt());
    echo implode(' ', array_slice($words, 0, 20)).' ...'; ?>" />

Viewing 6 replies - 1 through 6 (of 6 total)

The topic ‘Quick php problem (excerpt in meta tag doesn’t work)’ is closed to new replies.