首页 文章

在Wordpress中的functions.php之前访问post数据

提问于
浏览
0

我正在更新我的自定义Wordpress主题,但由于这是一个相当耗时的过程,我想一次启动一个部分 . 换句话说,网站的不同部分将有几个版本的主题 . 为了保持整洁,我希望将它们保存在单独的文件夹中,包含所有资源,例如js,images,css .

我设法使用条件标签重写模板层次结构,但卡在了functions.php上

我试图使用自定义字段(post meta)在几个functions.php文件之间切换,但遗憾的是$ post不可用,所以我无法使用get_post_meta() .

我只能找到自定义数据库查询,$ wpdb等解决方案的痕迹,但无法弄清楚 .

在加载functions.php之前,是否有任何相当简单的解决方案可以连接到post数据(wp_query)?或以某种方式不同地修改函数的加载位置?

为了说明我正在撰写的内容,我粘贴了我的主要index.php

<?
get_header();

/*
 * Get theme version according to the custom field 'section'
 */
 
if( function_exists ( 'theme_version' ) ){
	$theme = theme_version( @get_the_ID() );
} else {
	$theme = 'v2';
}

include_once( 'theme/'. $theme .'/TEMPLATE_BUILDER.php' );


get_footer();

?>

谢谢!

1 回答

  • 1

    希望找到一个正确的答案(经过几个小时的研究,试验和错误)

    我将下面的代码放在main(wp-native)functions.php中,试图保持代码和文件结构整洁,作为一个魅力 .

    add_action('after_setup_theme', function(){
    
        // parse_url tidies-up the uri
        $section = get_post_meta( url_to_postid( parse_url( $_SERVER['REQUEST_URI'], PHP_URL_PATH ) ),'section', true);
        if ( !empty( $section )){
    
            // assign sections to the theme versions below
            $theme_version = array(
    
                'v3' => array(
                    'Sixth Form',
                    [ ... ]
                ),
    
                'v3.1' => array(
                    'Contact',
                    [ ... ]
                )
    
            );
            foreach($theme_version as $key => $value) { if(in_array( $section, $value )) $theme = $key; }   
        }
        if( empty($theme) ) $theme = 'v2';   // default theme version
    
        require_once(  'theme/' . $theme . '/functions.php' );
    
        $GLOBALS['theme-ver'] = $theme; // set the global to use in index.php (and somewhere else perhaps)
    
    });
    

    代码还没有完成 - 需要一些条件子句作为functions.php有时在循环中被多次调用(特别是使用自定义wp_query)

    也许有人会发现以上有用的 . 顺便说一下,WP本身并不支持某种“主题版本控制”,这是非常令人惊讶的 - 我可以看到不必立即升级整个网站的强大好处,例如e . G . RESP .

相关问题