Wordpress功能更新或创建robots.txt

时间:2012-07-14 23:11:09

标签: wordpress function robots.txt

我正在为Wordpress创建一个插件,其功能是更新文件robots.txt或创建它(如果尚不存在)。

到目前为止,我有这个功能:

function roots_robots() {

  echo "Disallow: /cgi-bin\n";
  echo "Disallow: /wp-admin\n";
  echo "Disallow: /wp-includes\n";
  echo "Disallow: /wp-content/plugins\n";
  echo "Disallow: /plugins\n";
  echo "Disallow: /wp-content/cache\n";
  echo "Disallow: /wp-content/themes\n";
  echo "Disallow: /trackback\n";
  echo "Disallow: /feed\n";
  echo "Disallow: /comments\n";
  echo "Disallow: /category/*/*\n";
  echo "Disallow: */trackback\n";
  echo "Disallow: */feed\n";
  echo "Disallow: */comments\n";
  echo "Disallow: /*?*\n";
  echo "Disallow: /*?\n";
  echo "Allow: /wp-content/uploads\n";
  echo "Allow: /assets\n";
  echo "\n";
}

add_action('do_robots', 'roots_robots');

文件robots.txt没有更新,我忘了什么吗? 还有一种方法可以先检查是否存在,如果没有创建文件?

我从插件kb-robots中找到了一些东西,但我不是百分百确定如何将它添加到我的函数中..

function kb_robotstxt(){
    # this is to make it work for demos and testing. Without this, plugin would only act when robots.txt is in a valid place. With this, it will act whenever robots.txt is appended to blog URL
    # (even if blog is in a subdirectory)
    $request = str_replace( get_bloginfo('url'), '', 'http://'.$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'] );

    if ( (get_bloginfo('url').'/robots.txt' != 'http://'.$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI']) && ('/robots.txt' != $_SERVER['REQUEST_URI']) && ('robots.txt' != $_SERVER['REQUEST_URI']) )
        return;     // checking whether they're requesting robots.txt

    $robotstxt = get_option('kb_robotstxt');

    if ( !$robotstxt)
        return;

    header('Content-type: text/plain');
    print $robotstxt;
    die;
}

谢谢!

1 个答案:

答案 0 :(得分:1)

您应该将数据保存到文件中,而不是将其输出到浏览器。查看file_put_contents。您还必须确保Web服务器可以写入该文件。