【问题标题】:Broken CSS when changing from blog.mysite.com to www.mysite.com/blog从 blog.mysite.com 更改为 www.mysite.com/blog 时 CSS 损坏
【发布时间】:2016-11-16 18:57:26
【问题描述】:

我们为我们的网站创建了一个新网址。旧 URL 是 blog.mysite.com。新 URL 是 www.mysite.com/blog。我遇到的问题是,虽然 CSS 在 blog.mysite.com 上运行良好,但在 www.mysite.com/blog 上却无法运行。新 url 正在 www.mysite.com/wp-content... 上查找文件,而文件实际上位于 www.mysite.com/blog/wp-content... 在新 URL (blog.mysite .com/wp-content ... 在旧版本上)。两者都指向相同的服务器和相同的文件。这是一个例子:

<link href="/wp-content/themes/edition/prefix_css.css" rel="stylesheet">
<link href="/wp-content/themes/edition/header.css" rel="stylesheet">

【问题讨论】:

  • 对吗?那么将 href 更新为正确的 URL?

标签: php wordpress .htaccess


【解决方案1】:

就像@JonStirling 说你应该更新你的 href 属性。它在 blog.mysite.com 上工作的原因是它是一个子域,而不是新的 url。 最好的方法是使用bloginfo() 动态添加域,这样你的代码就会变成类似的东西:

<link href="<?php bloginfo('stylesheet_directory')?>/prefix_css.css" rel="stylesheet">
<link href="<?php bloginfo('stylesheet_directory')?>/header.css" rel="stylesheet">

这样每次都会正确加载文件的路径,不管它是否在子域上。

【讨论】:

    【解决方案2】:

    如果您使用的是 Wordpress,建议您使用 WP 提供的排队系统。如果你正确使用它,你可以用它做很多“技巧”——这对于硬编码的样式表链接和脚本来说(几乎)是不可能的。

    使用wp_head() 函数——它可以为你调用很多东西:例如enqueued stylesheets(或scripts)。

    所以我认为您应该将代码更改为以下内容

    // Put this code in your functions.php
    function enqueue_stylesheets() {
    
        // enqueueing prefix_css.css for all media, with a version number of 1.0.0
        wp_enqueue_style(
            'prefix_css',
            get_stylesheet_directory_uri() . '/prefix_css.css',
            array(),
            '1.0.0',
            'all'
        );
    
        // enqueueing header.css for all media, with a version number of 1.0.0; AFTER prefix_css.css
        wp_enqueue_style(
            'header',
            get_stylesheet_directory_uri() . '/header.css',
            array( 'prefix_css' ),
            '1.0.0',
            'all'
        );
    
    }
    add_action( 'wp_enqueue_scripts', 'enqueue_stylesheets' );
    

    从头部移除硬编码的样式表链接,然后改变你的头部:

    <html>
        <head>
        <!-- everything that's in the header -->
        <?php
            wp_head();
        ?>
        </head>
    <!-- continuing with the <body> -->
    

    这将输出您的样式表并尊重网站的 URL 结构。

    当然,您可以使用bloginfo('stylesheet_directory'),但最佳做法是改用get_stylesheet_directory_uri()

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-08-23
      • 2014-03-29
      • 1970-01-01
      • 1970-01-01
      • 2012-03-07
      • 2018-12-27
      • 1970-01-01
      • 2021-04-20
      相关资源
      最近更新 更多