I am currently working on a WordPress website, where the chosen shopping platform is WooCommerce.
I want to create a series of Template files, to be called within the content-product-single.php
file, which contains Maths calculations. For some reason, the Maths calculations only seems to work when placed in the functions.php
rather than my assigned Template files. It was suggested that the way in which I was using the get_template_part
tags could be incorrect. Here is the original code I was using:
<?php
if (is_product_category('category-name')) {
get_template_part( 'templates/template-a' );
}
elseif (is_single('product-slug')) {
get_template_part( 'templates/template-b' );
}
elseif (is_single('product-slug')) {
get_template_part( 'templates/template-c' );
}
?>
If anyone notices any errors in my above code, then please do let me know as that could be the issue but for the time being, I think that my Maths coding may only work within a functions
file.
For organisation purposes, is there a way I can create multiple functions.php
files or would this be bad practice? I have tried functions-template-file-name.php
and placed this in the root of the theme but still the Maths does not work.
You can include secondary files like this in your functions.php
(files inside the subdirectory inc
):
include_once dirname(__FILE__) . '/inc/shortcodes.php';
include_once dirname(__FILE__) . '/inc/frontend.php';
On functions.php
(and included files) you should only add hooks (filters and actions) and their respective function callbacks.
On the template files (and their get_template_part
s) you leave the HTML and eventually some call to a function of your theme, like
<div class="results">
<?php my_get_results(); ?>
</div>
Where my_get_results()
(in functions.php) would be something like:
function my_get_results(){
$results = get_something();
foreach($results as $r) {
echo '<span>' . $r . '</span>';
}
}
The function.php file is automatically loaded by Wordpress, but from there you can include any number of php files (in your case, your functionality or calculation code files) in it.
You may add files something like this:
require_once( __DIR__ . '/template/template-a.php');
PHP scripts run relative to the current path, not to the path of their own file. Using DIR forces the template to happen relative to their own path.