2013-07-10 63 views
0

我目前在wordpress中使用条件元标记代码。 一切工作正常,除了在某些页面上。WordPress的条件元标记说明

代码的header.php:在functions.php的

<meta name="description" content="<?php echo metadesc($post->ID); ?>" /> 
<?php }else{ ?> 
<meta name="description" content="<?php bloginfo('description'); ?>" /> 
<?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) > 135) { 
return htmlspecialchars(substr($description,0,135) . "..."); 
}else{ 
return htmlspecialchars($description); 
} 
} 

这是它显示了当我去源,并期待在对元标记描述以下页面:

家:(在Wordpress常规设置中定义的主页描述(支票)

传记:页面(检查)的第135个字符

联系人:

<meta name="description" content="[contact-form-7 id=&quot;25&quot; title=&quot;Contact&quot;]" /> 

正如你所看到的,我只有我的联系页面上的联系表,它看起来像我需要添加一个过滤到脚本,以便它忽略脚本标记和短代码,并且它会替代地放置主页描述。

我该如何解决这个问题?

回答

0

如果你使用strip_shortcode功能试试这个

function metadesc($pid) { 
$p = get_post($pid); 
$description = strip_tags($p->post_content); 
$description = str_replace ("\n","",$description); 
$description = str_replace ("\r","",$description); 
$description =strip_shortcodes($description ); 
if(empty($description)){ 

return please get home page content 
} 
else{ 
if (strlen($description) > 135) { 
return htmlspecialchars(substr($description,0,135) . "..."); 
}else{ 
return htmlspecialchars($description); 
} 

} 

} 

strip_shortcodes

+0

我把你的脚本替换成了我的,但后来出现语法错误 – Eric

+0

你把家里的内容放在**返回中请得到主页的内容**和你得到了什么语法错误 –

+0

是的,没有语法错误了,但没有变化,仍然: Eric

0

你跳进出PHP的过于频繁,导致编码错误和缓慢的执行。重写你的第一个代码:

<?php 
echo '<meta name="description" content="' . 
    ((some condition)? metadesc($post->ID): bloginfo('description')) . '" />'; 
?> 

现在,如果你对内容的原始数据是[contact-form-7 id=&quot;25&quot; title=&quot;Contact&quot;]什么是你试图把它变成?您希望如何看待它重新格式化?这是来自metadesc()函数?我不认为描述标签中的HTML实体将被扩展为它们的字符,但将按原样使用。因此,您可能需要输出[contact-form-7 id=\"25\" title=\"Contact\"]。无论如何,这是一个很糟糕的描述 - 真的想要那里吗?

另外请注意您是否使用UTF-8或单字节编码,如Latin-1,这在使用substr()时变得很重要(您不想在多字节UTF -8个字符)。此外,如果您要添加省略号(...),则需要132个字符,而不是135个。

0

我做了类似的事情,有条件地采用摘录并将其用作描述,如果查看器是在一个单一的帖子页&有一个摘录。这里是代码:

<?php 
if (is_single() && $post->post_excerpt != “”) { 
$post = $wp_query->post; 
$descrip = strip_tags($post->post_excerpt); 
echo ‘<meta name=”description” content=”‘.$descrip.’”>’; 
} 
?> 

我也写了一个blog post详细说明了整个事情。