I have several sites with several custom PHP widget loops I've created. I would like to reuse these widgets in other areas and site, but with different custom post types.

The only unique thing in each of the widget PHP files are the post type pulling (in the snippet below, it is post):

$home_carousel_query = new WP_Query('post_type=post&posts_per_page=-1&order=ASC); while($home_carousel_query -> have_posts()) : $home_carousel_query -> the_post();

I've recently started using Sass and I feel the variable method there has to be used in other languages.

Is there a way in PHP that I can have 1 file with all my variables (i.e. $carouselCPT='post'; $widgetAlpha='CPT1';, etc.) that will pull to other PHP files?

Originally my functions.php was HUGE with all of my loops and CPTs, so I portioned the PHP out into more manageable files and include each manually:

include( get_stylesheet_directory() . '/functions/widgetCarousel.php' );

I'm imagining a solution working something like:

~in variables.php
$carouselCPT = 'post';

~in widgetCarousel.php
...WP_Query('post_type=' . $carouselCPT . '....

The goal is to load all of these widget files into a GIT repository so that if one file needs a change, it will be updated in all sites with that file, instead of having to make the same change 10+ times.

I am new to PHP - I am not sure of where the variables need to be created, how they need to be written, and then what needs to happen in each file where I am declaring the Custom Post Type....

Help! Thank you!

up vote 2 down vote accepted

you can define a constant in wp.config.php or at the beginning of functions.php of your theme

if (!defined('CAROUSEL_CPT')) {
  define("CAROUSEL_CPT", "post");
}

WP_Query('post_type='.CAROUSEL_CPT);//....

Your Answer

 
discard

By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Not the answer you're looking for? Browse other questions tagged or ask your own question.