0

I want to show the excerpt from a post only if it exists. If it does not I want to show an excerpt of the content text of the post. Here is what I came up with:

<?php

  $my_excerpt = $item->post_excerpt;

  if ($my_excerpt) {            
    echo Str::limit($my_excerpt, 120);
  }
   else
  { 
    $content = ($item->post_content);
    $contentexcerpt = substr($content, 0, 150);
    echo $contentexcerpt, '...'; 
  }
?>

This worked perfectly until I tried to use it on an archive page inside a foreach loop. Now it shows both the custom excerpt and an excerpt taken from the content text.

Here is the code for the whole archive page archivepage

Any suggestions would be welcome.

  • Are you sure that you are not seeing the part "<p><?php echo Str::words($queried_post->post_content, 19); ?></p>" at line 46 in your archive page? Do you have a link to your page, so we could inspect it? – brance May 13 '15 at 10:43
  • Please add your complete code inside your question – Pieter Goosen May 13 '15 at 10:47
0

Apart from the horribly format issues you also have a typo:

<?php
            $my_excerpt = $item->post_excerpt;

                        if ($my_excerpt){                      
                        echo Str::limit($my_excerpt, 120);}

                        else
                        $content = ($item->post_content);{
                        $contentexcerpt = substr($content, 0, 150);
                        echo $contentexcerpt, '...';
                        }
         ?>

These lines:

else
                            $content = ($item->post_content);{

should be:

else {
                            $content = ($item->post_content);

The parser registered a single line of code corresponding to the else statement, mainly this: $content = ($item->post_content);

After that, the code between the curly brackets:

{
                        $contentexcerpt = substr($content, 0, 150);
                        echo $contentexcerpt, '...';
                        }

is treated like any other block of code and that is why if the if ($my_excerpt) conditioned is passed it will still output the custom excerpt.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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