【问题标题】:parsing CSS in PHP with global variables. Wordpress在 PHP 中使用全局变量解析 CSS。 WordPress
【发布时间】:2015-03-14 15:52:40
【问题描述】:

我有一个小问题,我不确定如何解决,因为我在 php 中解析 css 文件有点天真。我正在使用 wordpress,并且正在构建一个功能,我需要动态地将宽度应用于我的元素。

理论上,在程序意义上,我的方法应该有效。

我所做的是在头文件中:

global$imageSlider;//global as needed in other files
$imageSlider=new slider();//my class

$imageSlider->add_css();//just an enqueue really.
//wp_enqueue_styles('image_slider_styles',get_template_directory_uri()."/css/imageSlider.css");

现在看到我的imageSlider.css 继续我的全局声明,我想该文件将能够使用$imageSlider

使用 .htaccess 在 PHP 中解析 CSS 文件

<FilesMatch "\.(css)$">
    AddHandler application/x-httpd-php .css
</FilesMatch>

这适用于局部变量。在我声明$imageSlider 之前是否正在解析这个文件?

在 CSS 文件中

header("Content-type: text/css; charset: UTF-8");
$pref=$imageSlider->build_css_widths();
//$imageSlider::build_css_widths() returns an array
//The rest of my styles
#imageSlider #sliderHolder{width:<?echo$pref['total'];?>%;}

class slider() 位于我的函数文件中。

有没有其他方法或者我错过了什么? 但它什么也没返回。 :(

我得到的错误是call to member function on non object,这基本上意味着从未声明过$imageSlider

【问题讨论】:

    标签: php wordpress .htaccess


    【解决方案1】:

    问题是,您包含 PHP 的 CSS 文件是在 WordPress 外部加载的,因此对您在 WordPress 内部声明的全局变量一无所知。

    一种常见的技术是使用wp_head在页面头部简单地输出自定义属性

    function my_style() {
        ?><style type="text/css"><?php
        //Output CSS.
        ?></style><?php
    }
    add_action( 'wp_head', 'my_style' );
    

    另一种技术是使用 AJAX URL,并注册一个将响应动态 CSS 的操作。

    $style_url = add_query_arg( array( 'action' => 'my-style' ), admin_url( 'admin-ajax.php' ) );
    wp_enqueue_styles( 'my-style', $style_url );
    
    function my_style() {
        header( 'Content-type: text/css; charset: UTF-8' );
        //Output CSS.
    }
    add_action( 'wp_ajax_my-style', 'my_style' );
    add_action( 'wp_ajax_nopriv_my-style', 'my_style' );
    

    无论哪种情况,我都强烈建议将动态样式与静态 CSS 分开。通过 PHP 解析整个 CSS 文件会给服务器增加不必要的负载。此外,基于 .htaccess 的技巧将 CSS 解析为 PHP 仅适用于 Apache 服务器。

    【讨论】:

    • 我以为是因为这样的事情。谢谢你的回答:) 我现在可以找到替代方法 n_n
    • 别担心,我可以:)
    • @sourRaspberri 你的意思是使用self::func 作为回调?如果在类中添加动作,您可以使用add_action( 'wp_head', array( $imageSlider, 'add_css' ) );add_action( 'wp_head', array( $this, 'add_css' ) );,假设它不是静态方法。 编辑:啊,我明白了!
    • add_action('wp-head',self::css()); 实际上会立即调用该方法。此外,操作是wp_head,而不是wp-head。你可能想要add_action( 'wp_head', array( 'MyClass', 'css' ) );add_action( 'wp_head', array( __CLASS__, 'css' ) );
    • 对不起,我通常是WriteInCamel,在这个wordpress下划线的东西上苦苦挣扎......哈哈,好的,我会更新你建议的方法:)再次感谢
    猜你喜欢
    • 2017-10-14
    • 1970-01-01
    • 2017-01-09
    • 1970-01-01
    • 1970-01-01
    • 2017-04-08
    • 2021-07-20
    • 1970-01-01
    • 2022-09-28
    相关资源
    最近更新 更多