根据页面使用js动态更改meta/title标签

4

我有文档的结构:

<?
    include('head.php');
    include('header.php');
    include('index_content.php');
    include('footer.php');
    include('form.php');
    include('js.php');
?>

当我创建一个新页面时,我使用这个框架并仅更改页面内容。但是为了进行SEO优化,还需要更改标题和元标签。是否可以使用JavaScript根据页面动态更改这些内容?或者最好不要麻烦,像这样写:
<?
    include('head.php'); //beginning of the <head> tag
?>
    <title>Some title</title>
    <meta name="description" content="some description">
    <meta name="keywords" content="some keywords">
<?
    include('header.php'); - //end of </head> tag
    include('index_content.php');
    include('footer.php');
    include('form.php');
    include('js.php');
?>

你不能这样做吗?<meta name="description" content="<?php echo $DESCRIPTION;?>"> - Hemal
你在页面内容中使用了数据库还是静态页面? - Samir Karmacharya
我在我的情况下使用了 https://prerender.io/ - Vinod Louis
@SamirKarmacharya 静态页面 - MrVieV
1个回答

0

您可以像下面展示的那样,直接将php变量获取到meta标签中。

<?
    include('head.php'); //beginning of the <head> tag
?>
    <title>Some title</title>
    <meta name="description" content="<?php echo $DESCRIPTION;?>">>
    <meta name="keywords" content="<?php echo $KEYWORDS;?>">>
<?
    include('header.php'); - //end of </head> tag
    include('index_content.php');
    include('footer.php');
    include('form.php');
    include('js.php');
?>

更新

如果您使用jquery,这可能有效

$("meta[name='description']").attr("content","<?php echo $DESCRIPTION;?>");

你认为机器人会等待 PHP 变量解析吗? - Vinod Louis
这只是一段脚本代码,当在浏览器中呈现时,它将显示纯文本,很容易被爬取。不需要使用机器人来获取php。 - Hemal
1
这很完美,DOM 上的页面保存了已解析的值,但是机器人将会抓取变量 "<?php echo $DESCRIPTION;?>" 作为内容,这是我在工作中遇到的情况。 - Vinod Louis
@VinodLouis,这可能有效。我只是用jQuery设置元内容。我是对的吗? - Hemal
1
这个不会起作用,因为机器人在页面加载时就会触发,它甚至不会等待你的js加载。你可以通过服务器端渲染或预渲染中间件来实现这一点。 - Vinod Louis
使用phantom.js来实现这个目的链接,因为在更改内容之后,机器人无法阅读它。 - uiTeam324

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接