Skip to content

Instantly share code, notes, and snippets.

@natedunn
Last active October 14, 2018 18:09
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save natedunn/d2e001f00b0ac6a6432d5effbc94faf1 to your computer and use it in GitHub Desktop.
Save natedunn/d2e001f00b0ac6a6432d5effbc94faf1 to your computer and use it in GitHub Desktop.
Wordpress global import function
<?php
function import($file_path, $args = array())
{
$did_wp_head_fire = did_action('wp_head');
$output = null;
$npm_path = TEMPLATEPATH . '/node_modules/' . $file_path;
// Check file
if (!file_exists($file_path) && !file_exists($npm_path)) {
trigger_error('File not found.', E_USER_WARNING);
return false;
} elseif (
!file_exists($file_path) &&
file_exists(TEMPLATEPATH . '/node_modules/' . $file_path)
) {
$file_path = $npm_path;
}
$file_type = pathinfo($file_path, PATHINFO_EXTENSION);
// .php Import
if ($file_type == 'php') {
extract($args);
ob_start();
include $file_path;
$output = ob_get_clean();
}
// .css
if ($file_type == "css") {
if (!$did_wp_head_fire) {
add_action('wp_enqueue_scripts', function () use ($file_path) {
$handle = bin2hex(random_bytes(5));
wp_register_style($handle, $file_path, array(), null, false);
wp_enqueue_style($handle);
});
}
}
if (!isset($args['print']) || !$args['print'] == false) {
print $output;
}
return $output;
}
// ==================
// Examples
// ==================
// import(TEMPLATEPATH . '/components/test.php', array(
// 'title' => $campaign->get_raw('cye_18_within', 'campaign_name')
// ));
// import('press-css/src/press.css');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment