Rewriting in wordpress url

时间:2015-11-09 作者:stlawrance

是的,我们喜欢让url更短、更干净。

假设我们有这样的css url

xxx.com/wp-content/theme_name/css/my_custom_css.css
但是我很乐意这样展示

xxx.com/css/my_custom_css.css
所以我认为重写是最好的选择。

我创建了一个插件,对新文件进行了重写。php并在重写中包含了文件和插入的代码。php像这样

<?php 
function my_rewrite_rules( $wp_rewrite ) {
    $non_wp_rules = array(
        \'css/(.*)\'  => \'wp-content/themes/twentyfourteen/assets/css/$1\',
        \'js/(.*)\'  => \'wp-content/themes/twentyfourteen/assets/js/$1\',
    );

    $wp_rewrite->non_wp_rules = $non_wp_rules + $wp_rewrite->non_wp_rules;
}

function my_flush_rewrite_rules() {
    global $wp_rewrite;

    $wp_rewrite->flush_rules();
}

add_action( \'init\', \'my_flush_rewrite_rules\');
add_action(\'generate_rewrite_rules\', \'my_rewrite_rules\');
?>
我安装了流行的重写分析器。但我看不到任何效果。

不知道问题出在哪里。

但当我使用$wp_rewrite->wp_rules 而不是$wp_rewrite->non_wp_rules 这表明,但显然这不是我们想要的??

问题在哪里:(这实际上造成了太多问题:(

谢谢:)

2 个回复
最合适的回答,由SO网友:phatskat 整理而成

<罢工>来自this other answer on the WP SE

add_action(\'generate_rewrite_rules\', \'roots_add_rewrites\');

function roots_add_rewrites($content) {
    $theme_name = next(explode(\'/themes/\', get_stylesheet_directory()));
    global $wp_rewrite;
    $roots_new_non_wp_rules = array(
        \'css/(.*)\'      => \'wp-content/themes/\'. $theme_name . \'/css/$1\',
        \'js/(.*)\'       => \'wp-content/themes/\'. $theme_name . \'/js/$1\',
        \'img/(.*)\'      => \'wp-content/themes/\'. $theme_name . \'/img/$1\',
    );
    $wp_rewrite->non_wp_rules += $roots_new_non_wp_rules;
}
TheDeadMedic提供了一个更好的功能版本:

function wpse_208051_add_rewrites( $wp_rewrite ) {
    $path = str_replace( home_url( \'/\' ), \'\', get_template_directory_uri() );

    $wp_rewrite->non_wp_rules += array(
        \'css/(.*)\' => $path . \'/css/$1\',
        \'js/(.*)\'  => $path . \'/js/$1\',
        \'img/(.*)\' => $path . \'/img/$1\',
    );
}

add_action( \'generate_rewrite_rules\', \'wpse_208051_add_rewrites\' );

SO网友:TheDeadMedic

根据@phatskat的回答,这是我的建议。其他解决方案的最大问题是路径名的假设,这在WordPress开发中是一个很大的禁忌(尤其是那些打算分发给公众的)。

function wpse_208051_add_rewrites( $wp_rewrite ) {
    $path = str_replace( home_url( \'/\' ), \'\', get_template_directory_uri() );

    $wp_rewrite->non_wp_rules += array(
        \'css/(.*)\' => $path . \'/css/$1\',
        \'js/(.*)\'  => $path . \'/js/$1\',
        \'img/(.*)\' => $path . \'/img/$1\',
    );
}

add_action( \'generate_rewrite_rules\', \'wpse_208051_add_rewrites\' );

相关推荐