Place category_description in the meta description (wordpress)

我只是一个虾纸丫 提交于 2019-12-12 01:58:08

问题


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:


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;
}


来源:https://stackoverflow.com/questions/5727909/place-category-description-in-the-meta-description-wordpress

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!