Header in my theme I created the following code for the meta description:
<?php if (is_single() || is_page()) { ?>
<meta name="description" content="<?php echo metadesc($post->ID); ?>" />
<?php }else{ ?>
<meta name="description" content="<?php bloginfo('description'); ?>" />
<?php } ?>
and included this code in my function.php:
function metadesc($pid) {
$p = get_post($pid);
$description = strip_tags($p->post_content);
$description = str_replace ("\n","",$description);
$description = str_replace ("\r","",$description);
if (strlen($description) > 150) {
return htmlspecialchars(substr($description,0,150) . "...");
}else{
return htmlspecialchars($description);
}
}
now I want to also incorporate category_description the theme header :
<?php if ( is_category() ) { echo category_description(); } ?>
can you help me how can I do? thanks
You already have the work mostly done:
As you see, I would forget about all the cleaning you are doing in
metadesc()
, just get rid of the html withstrip_tags()
, but I see no need to remove linebreaks or to translate to html entities, certainly I don't think search engines will mind at all about a line break or either a&
or a&
.Plus, there is no need to check the length of the description. Just try to truncate it, if its length is less than 150 chars,
substr()
will return the whole string untouched.EDIT: Responding to your comment, you can do it this way if you prefer to use the
metadesc()
function you were using: