Passing arguments to template files in WordPress example

Example 1: how to pass id through get template part

<?php
get_header();

// etc.

// In the main template file
$users = new \WP_User_Query( [ ... ] );

foreach ( $users as $user )
{
    set_query_var( 'user_id', absint( $user->ID ) );
    get_template_part( 'template-parts/user', 'contact_methods' );
}

Example 2: get template part pass variable

//NEW CLEAN way (WP 5.5.0 >=) of passing variables to template parts 

$data = array('foo'=>'bar');

//add your variables as a third parameter
get_template_part( 'template-parts/file', 'name', $data );

//In the template part itself: (IMPORTANT NOTE: the name of the variable has to be args)
echo $args['foo'];

Tags:

Php Example