What is Template Tags and Template Parts in PhP?

Template Tags

A template tag is a PHP function used to generate and display information dynamically. WordPress Themes contain different templates and theme developers use template tags to fetch and display dynamic data. WordPress has many built-in template tags that can be used in WordPress themes. WordPress plugins and themes can also define their own template tags and use them in different templates.

A template tag is broken up into three components:
  • A PHP code tag
  • A WordPress function
  • Optional parameters

Eg:- get_header() tells WordPress to get the header.php file and include it in the current theme file. Similarly, get_footer() tells WordPress to get the footer.php file.

By encapsulating all of the code for a particular chunk of content, template tags make it very easy to include various pieces of a template in a theme file and also to maintain the theme.

Some template tags let you pass parameters. Parameters are extra pieces of information that determine what is retrieved from the database.

Eg:
To print the version of WordPress that the blog is running on, you would pass a parameter of “version”:

bloginfo( 'version' );

Template Tags and Template Parts in PhP

Template Parts

Template parts provides a simple mechanism for child themes to overload reusable sections of code in the theme.Template files access them with a function called get_template_part().

The primary reason to create a template part in WordPress is to avoid repeating code: if multiple files use several identical lines of code, this code can be pulled into a template part, allowing it to be stored (and modified) in a single place.

get_template_part( string $slug, string $name = null, array $args = array() )

The above loads a template part into a template.

Its parameters include:-

$slug--(string) (Required) --The slug name for the generic template.
$name--(string) (Optional) --The name of the specialised template.
Default value: null

$args--(array) (Optional)-- Additional arguments passed to the template.
Default value: array()

It will return void on success and False if the template does not exist.

A call to get_template_part with both the slug and name parameters tries to load a template file with a slug-name.php filename. If a template file with a slug-name.php filename doesn’t exist, WordPress tries to load a template file with a slug.php filename.

Eg:-

<?php get_template_part( 'firstargument', 'secondargument' ); ?>

1 تعليقات

أحدث أقدم