Pages

Monday, April 28, 2014

Wordpress pass variable when calling template - [resolved]

If you want to pass any variable when include template than please follow below method:

1. I want to send page ID to sidebar than I have create one array for this and pass it using below method:

<?php
$params = array(
'ID' => $parentId
);
getTemplatePart('sidebar', 'subpages', $params);
?>

2. If you want to get this array than please see at below code:

<?php
$parentId = $ID;

// here, you can set your login
?>

3. Please write below function in your functions.php for calling the template:

<?php
function getTemplatePart($slug = null, $name = null, array $params = array()) {
    global $posts, $post, $wp_did_header, $wp_query, $wp_rewrite, $wpdb, $wp_version, $wp, $id, $comment, $user_ID;

    do_action("get_template_part_{$slug}", $slug, $name);
    $templates = array();
    if (isset($name))
        $templates[] = "{$slug}-{$name}.php";

    $templates[] = "{$slug}.php";

    $_template_file = locate_template($templates, false, false);

    if (is_array($wp_query->query_vars)) {
        extract($wp_query->query_vars, EXTR_SKIP);
    }
    extract($params, EXTR_SKIP);

    require($_template_file);
}
?>

No comments: