In PHP, there are several ways to include external files into your code, but the most commonly used ones are include, include_once, require, and require_once. These statements allow you to incorporate code from other files and reuse it in your PHP program.
Here are the differences between them:
include: This statement includes the specified file in your code. If the file is not found, a warning message is displayed, but the script continues to execute. If the file is included more than once, the code is executed each time.include_once: This statement is similar toinclude, but it checks if the file has already been included. If the file has been included before, it does not include it again, preventing duplicate code. This statement also generates a warning message if the file is not found.require: This statement is similar toinclude, but if the file is not found, it generates a fatal error and stops the script execution.require_once: This statement is similar torequire, but it checks if the file has already been included. If the file has been included before, it does not include it again.
In summary, include and require are used to include external files into your PHP code, while include_once and require_once are used to prevent duplicate code inclusion. The difference between include and require is that include generates a warning message if the file is not found, while require generates a fatal error.
Referencing or Including Other Files In WordPress Child Theme
When you need to include files that reside within your child theme’s directory structure, you will need to use get_stylesheet_directory() . Since the style.css is in the root of your child theme’s subdirectory, get_stylesheet_directory() points to your child theme’s directory (not the parent theme’s directory). To reference the parent theme directory, you would use get_template_directory() instead.
Below is an example illustrating how to use get_stylesheet_directory() when referencing a file stored within the child theme directory:
<?php require_once get_stylesheet_directory() . '/my_included_file.php'; ?>
Meanwhile, this example uses get_stylesheet_directory_uri() to display an image that is stored within the /images folder in the child theme directory.
<img src="<?php echo get_stylesheet_directory_uri(); ?>/images/my_picture.png" alt="" />
Unlike get_stylesheet_directory(), which returns a file path, get_stylesheet_directory_uri() returns a URL, which is useful for front-end assets.