【问题标题】:Wordpress get_theme_mod in custom.css.php file not workingcustom.css.php 文件中的 Wordpress get_theme_mod 不起作用
【发布时间】:2025-11-23 19:50:02
【问题描述】:

在 Wordpress 主题开发中,我将作为样式表的 colors.php 文件加入队列。

wp_register_style( 'custom_colors', $uri . '/assets/css/colors.php', [], $ver );

wp_enqueue_style( 'custom_colors' );

我创建了一个 wordpress 定制器部分和设置来管理颜色。我在定制器中添加了我的设置,如下所示:

$wp_customize->add_setting( 'primary_color', [
    'default'       =>  '#1ABC9C'
]);

$wp_customize->add_control(
    new WP_Customize_Color_Control( 
        $wp_customize, 
        'primary_color_input', 
        array(
            'label'      => __( 'Primary Accent Color', 'myslug' ),
            'section'    => 'color_section',
            'settings'   => 'primary_color',
        )
    ) 
);

当我直接在 header.php 文件中调用 get_theme_mod 作为测试以回显它的工作值时:

$color = get_theme_mod('primary_color', '#1ABC9C'); //hex color is default
echo $color;

但是当我在 colors.php 文件中调用同一行时,我得到一个错误:

Uncaught Error: Call to undefined function get_theme_mods() in /app/public/wp-content/themes/mytheme/assets/css/colors.php:28

我想使用 get_them_mod 值来更新我的 colors.php 文件中的所有链接颜色,而不是在头部动态打印样式。

谁能帮我理解这里出了什么问题?

这在我的 colors.php 文件中:

header("content-type: text/css; charset: UTF-8");

$color = get_theme_mod('primary_color', '#1ABC9C'); 

a { color: <?php echo $color; ?>; }

【问题讨论】:

  • 您可能需要首先在您的 css/php 文件中包含 wp-includes/theme.php.
  • 点赞&lt;?php require_once("../howevermanytimes../../wp-load.php"); if ( ! function_exists( 'get_theme_mod' ) ) { require_once( ABSPATH . '/wp-includes/theme.php.' ); }
  • 嘿,Stender,效果很好!太感谢了!你能把它作为答案吗?如果可能的话,你能向我解释一下这些文件做了什么吗?

标签: php wordpress wordpress-theming stylesheet


【解决方案1】:

函数get_theme_mods(以及所有其他与样式相关的函数)位于wp-includes/theme.php

当您创建自定义文件,但仍需要 wordpress 功能时,您应该告诉 wordpress 先加载。这是由require_once("../howevermanytimes../../wp-load.php") 完成的

之后,您可以测试您需要的函数或该文件中的任何函数是否存在。在这个例子中,它是通过调用

if ( ! function_exists( 'get_theme_mod' ) ) { 
    require_once( ABSPATH . '/wp-includes/theme.php.' ); 
}

这可以确保函数已加载。

所有其他函数文件都可以这样做,

所以另一个例子可能是:

if ( ! function_exists( 'get_post_meta' ) ) {
    require_once( ABSPATH . '/wp-admin/includes/post.php' );
}

这将使您可以访问post_exists() 等功能。

【讨论】:

  • 优秀而翔实的信息!感谢您在这个问题上提供的帮助,非常感谢。