Let's connect

Creating a Plugin for WordPress Part 3. Creating a Single Post Template and Displaying Carbon Fields

In this article, we will add the output of our car and all the fields we created in the last article.

Connecting scripts

Let’s start by creating the assets folder at the root of our project and copying there all the files that came to us with the layout

Now you need to add a hook to connect scripts and styles to the Main.php file in the init function

add_action( 'wp_enqueue_scripts', [ $this, 'add_scripts' ] );

Create this function

public function add_scripts(): void {
   wp_enqueue_script( 'ecl_build', ECL_URL . '/assets/js/build.js', [ 'jquery' ], ECL_VERSION, true );
   wp_enqueue_script( 'html5shiv', '//', [], '3.7.0', false );
   wp_enqueue_script( 'respond', '//', [], '1.4.2', false );

   wp_script_add_data( 'html5shiv', 'conditional', 'lt IE 9' );
   wp_script_add_data( 'respond', 'conditional', 'lt IE 9' );

   wp_enqueue_style( 'ecl_main', ECL_URL . '/assets/css/main.css', '', ECL_VERSION );

   $global_style = ':root{ --color-one:#f26b36; --color-two:#be542a;}';
   wp_add_inline_style( 'ecl_main', $global_style );

wp_enqueue_script – Enqueues a script
wp_script_add_data – Adds conditions when including a script
wp_enqueue_style – Enqueue styles
wp_add_inline_style – Displays inline styles in the header

Create an output template override filter

Go to the file AddCPT.php and add a filter to the init function

add_filter( 'template_include', [ $this, 'add_single_car_page' ] );

Create a function and add conditions to override the template

 * Add single car template.
 * @param string $template
 * @return string
public function add_single_car_page( string $template ): string {

   if ( is_singular( 'cars' ) && ! locate_template( [ 'single-cars.php' ] ) ) {
      return ECL_PATH . '/template/single-cars.php';

   return $template;

The condition we are checking is a car page and there is a single-cars.php template in the theme being used.
If there is no template, then it will be displayed from the template folder from the root folder of our plugin.

is_singular – Checks if the post page is being viewed
locate_template – Finds the best server path to the specified template file. The search takes into account the child theme.

Connecting layout

We create a template folder at the root of our plugin and in it the single-cars.php file
We copy our layout there, we can find it at the link:

Full file code at the link

carbon_get_the_post_meta(“The name of the field we want to get”) – Used in the standard loop
If we want to get this field in a non-loop then we need to use
carbon_get_post_meta(“The ID of the post the field is bound to”, “The name of the field we want to get”)

numfmt_create — Creates a number formatter

Post a Comment