Place category_description in the meta description

2019-08-22 12:51发布

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

1条回答
再贱就再见
2楼-- · 2019-08-22 13:16

You already have the work mostly done:

<?php
    if( is_single() || is_page() ) $description = strip_tags($post->post_content);
    elseif( is_category() ) $description = category_description();
    else $description = get_bloginfo( 'description' );
    $description = substr($description,0,150);
?>

<meta name="description" content="<?= $description ?>" />

As you see, I would forget about all the cleaning you are doing in metadesc(), just get rid of the html with strip_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 &amp;.

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:

function metadesc() {
    global $post;

    if( is_single() || is_page() ) $description = strip_tags($post->post_content);
    elseif( is_category() ) $description = category_description();
    else $description = get_bloginfo( 'description' );

    $description = substr($description,0,150);

    return $description;
}
查看更多
登录 后发表回答