How to make a template variable global? - php

Inside a template part file there's a variable I'd like to be able to use in my page templates. Page templates are in the theme directory, and the template part file are in a sub-directory called template parts.
My template part file is called 'roster-get-annual-data.php', and the variable is the title of a custom post type. How can I make this title variable available in my page template?
Inside my template file (roster-get-annual-data.php) - within a wp_query:
if ($rosterQuery->have_posts()) {
while ($rosterQuery->have_posts()) {
$rosterQuery->the_post();
$post_title = $post->post_title;
set_query_var('post_title', $post_title);
?>
<h1><?php echo $post_title; ?></h1>
<div class="teams-wrapper">
<?php
$teams = get_field('single_rosters');
foreach ($teams as $post) {
// Setup this post for WP functions (variable must be named $post).
setup_postdata($post);
// set the individual roster's ID
$rosterId = $post->ID;
// get the Class Title
if (!empty(get_field('class', $rosterId)) && !empty(get_field('grad_year', $rosterId))) {
$classTitle = ucwords(get_field('class', $rosterId)) . ' - Class of ' . get_field('grad_year', $rosterId);
} else {
$classTitle = get_the_title();
}
?>
<h2><?php echo $classTitle; ?></h2>
<?php
// create empty $players array
$players = array();
// loop through the players acf repeater
if (have_rows('players', $rosterId)) {
?>
<?php
while (have_rows('players', $rosterId)) {
the_row();
// place players into an array
$players[] = get_sub_field('name');
}
?>
<?php
}
// display the PLAYERS NAMES
?>
<p class="players"><?php echo implode(', ', $players); ?></p>
<?php
}
// Reset the global post object so that the rest of the page works correctly.
wp_reset_postdata();
?>
</div>;
?>
And then in my page template:
$post_title = get_query_var('post_title');
get_template_part('template-parts/roster-get-annual', 'data');
I thought this would give me just the $post_title variable, but instead it outputs the entire template without the $post_title variable.

It´s not 100% clear to me what you want to achieve. But if you want pass args to a template you can do it with the 3rd parameter:
get_template_part('template-part', 'name', array('customkey' => 'value') );
see doc:
https://developer.wordpress.org/reference/functions/get_template_part/

Related

Restart foreach loop in PHP

I have an array with products as objects in it. Each object contains a key = category_title
I have a foreach loop that generates products in Bootstrap rows with configurable columns, in my case $col=3.
What I need is to have a new row if a new category_title comes up.
I created an array to push all the category_titles in it and create a variable if it is a new category. But now I am stuck.
The foreach looks like this:
<?php foreach($productspercat as $product): ?>
<!-- Make sure product is enabled and visible #front end -->
<?php // if($product->enabled && $product->visibility):?>
<?php
$catnew = false;
$categorytitle = $product->category_title;
if(!in_array($categorytitle, $totalcategories, true)):?>
<?php array_push($totalcategories,$categorytitle );
$catnew=true;
?>
<?php endif;?>
<div class="j2store-products-row <?php echo 'row-'.$row; ?> row">
<?php endif;?>
<div class="col-sm-<?php echo round((12 / $col));?>">
<h2><?php echo $categorytitle; ;
var_dump($catnew);
?></h2>
test
</div>
<?php $counter++;
$firstrun = true; ?>
<?php if (($rowcount == $col) or ($counter == $total)) : ?>
</div>
<?php endif; ?>
<?php // endif; ?>
<?php endforeach;?>
So basically if a new category comes up, it should close the row and start a fresh row with a new column count.
appreciate any help!
If you don't want to page refresh then you can do that by using jQuery or Angular JS.
By jQuery you can add data by jquery prepend() function if you wanna add data in starting or append() function to add ending section.
<?php
// Arranged products by category title
$arrangedProducts = array()
foreach($productspercat as $product) {
if (!array_key_exists($product->category_title, $arrangedProducts)) {
$arrangedProducts[$product->category_title] = array();
}
$arrangedProducts[$product->category_title][] = $product;
}
// each category is a key and its value is an array with all its products
foreach ($arrangedProducts as $categoryTitle => $products) {
// you create a new row
// ....
foreach ($products as $product) {
// you display product information
}
// you end the row
}
?>

Passing values to wordpress shortcode

<?php while (have_rows('home_playlist', 'option')): the_row();
$track = get_sub_field('home_track'); ?>
echo $track;
Here echo generate some selective IDs 2,4,7,10,12 (mp3 songs title) from wp panel. And I need to show the title on the player. How do i pass the value of $track into the 'ids'....
<?php
$tracks=array();
while (have_rows('home_playlist', 'option')): the_row();
$tracks[] = get_sub_field('home_track'); ?>
$list= implode(',',$tracks);
echo $list;
mp3j_put( '[popout ids="'.$list.'" autoplay="y"]' ); ?>

Dynamically create variables in foreach loop and use on another page

I'm using a dynamic template for a custom made CMS. I want to get variablesfrom one php-page and, for each created site that uses that page, I want to use the variables in a foreach to, for example display each title.
I have made a simple example below to explain this:
home.com/gallery/1
home.com/gallery/2
home.com/gallery/3
What I get:
Gallery 1
Gallery 1
Gallery 1
What I want:
Gallery 1
Gallery 2
Gallery 3
(Assuming that each page was named Gallery 1, 2, 3)
gallery.php
<form action="">
<input type="text" name="page_title">
</form>
<?php
$galleries = array();
$id = intval($_POST["id"]);
? foreach ($galleries as $id => $gallery) {
$title = $_POST["page_title"];
}
$_SESSION['galleries'] = $galleries;
$_SESSION['title'] = $title;
?>
<h1><?php echo $title; ?></h1>
page.php:
$galleries = $_SESSION['galleries'];
$title = $_SESSION['title'];
foreach ($galleries as $id => $gallery) {
echo $title;
echo "<br>";
}
?>
Note: because I want to use the variables on multiple pages I can't assign the form's action to a specific php-page.
Ok, I just found the sollution:
page.php:
$galleries = $_SESSION['galleries'];
$title = $_SESSION['title'];
foreach ($galleries as $id => $gallery) {
echo $gallery["title"]; //echo this line instead of $title
echo "<br>";
}
?>

Pass arguments from php function issue

I am working on a wordpress plugin. In plugin, a user first add a slider and then add images of relevant slider.
First i make this with shortcode. User enter the short name of the slider in the shortcode and images slides of relevant slider like this [foo_slider slider=slider_one] or [foo_slider slider=slider_two].
Now i "also" want the snippet, that user can add snippet else shortcode in the code like this echo wp_foo_slider(slider_two). But i dont get that.
Please guide me, how can i do this.
Here is my Code That works for shortcode:
<?php
function wp_foo_sliders($atts) {
global $wpdb;
$tbl_sliders = $wpdb->prefix . "foo_sliders";
ob_start();
extract(shortcode_atts(array(
'slider' => '',
), $atts));
$get_sliders = $wpdb->get_results("Select * From $tbl_sliders Where slider_shortname = '$slider'");
?>
<div class="foo_main_slider">
<?php
foreach ($get_sliders as $get_slider) {
$slider_id = $get_slider->slider_id;
?>
<div class="foo_slider_img">
<?php
$get_slider_image = $wpdb->get_results("Select * From ".$wpdb->prefix."foo_images Where
slider_id = $slider_id Order By image_order ASC");
foreach ($get_slider_image as $foo_img) {
?>
<img src="<?php echo $foo_img->image_path . $foo_img->image_name; ?>" alt="">
<?php
}
}
return ob_get_clean();
}
add_shortcode("foo_slider", "wp_foo_sliders");
?>
I also try this by my own <?php echo wp_foo_sliders("slider_two") ?> or <?php echo wp_foo_sliders(slider_two) ?>, in code and when i refresh the browser only <div class="foo_main_slider"> </div> appears and no images show.
Edit: I want that user can use short code <?php echo do_shortcode('[foo_slider slider=slider_one]'); ?> or user can use snippet <?php echo wp_foo_sliders("slider_two") ?>, only shortcode is working, snippet not work.
What i make mistake please help me.
When you call the shortcode function directly, you are passing a string to it. When you use the shortcode way WordPress will convert the arguments into an associative array.
Try refactoring your code
if( is_array( $atts ) ) {
//Called using shortcode so $atts is an array
extract(shortcode_atts(array(
'slider' => '',
), $atts));
} else {
//Function called directly so $atts is a string
$slider = $atts;
}
So i get my solution by my own.
I make a new function for this:
<?php
function foo_sliders($foo_short_name) {
global $wpdb;
$tbl_sliders = $wpdb->prefix . "foo_sliders";
$get_sliders = $wpdb->get_results("Select * From $tbl_sliders Where slider_shortname = '$slider'");
?>
<div class="foo_main_slider">
<?php
foreach ($get_sliders as $get_slider) {
$slider_id = $get_slider->slider_id;
?>
<div class="foo_slider_img">
<?php
$get_slider_image = $wpdb->get_results("Select * From ".$wpdb->prefix."foo_images Where
slider_id = $slider_id Order By image_order ASC");
foreach ($get_slider_image as $foo_img) {
?>
<img src="<?php echo $foo_img->image_path . $foo_img->image_name; ?>" alt="">
<?php
}
}
ob_start();
return $foo_short_name;
return ob_get_clean();
}
?>
And in theme code:
<?php foo_sliders(short_name) ?>
and its work great

wordpress site navigation

I'm using following code to display my 3 level menu:
if(!$post->post_parent){
// will display the subpages of this top level page
$children = wp_list_pages("title_li=&child_of=".$post->ID."&echo=0");
}else{
// diplays only the subpages of parent level
//$children = wp_list_pages("title_li=&child_of=".$post->post_parent."&echo=0");
if($post->ancestors) {
// now you can get the the top ID of this page
// wp is putting the ids DESC, thats why the top level ID is the last one
$ancestors = end($post->ancestors);
$children = wp_list_pages("title_li=&child_of=".$ancestors."&echo=0");
// you will always get the whole subpages list
}
}
if ($children) { ?>
<ul id="submenu">
<?php echo $children; ?>
</ul>
<?php } ?>
It lists pages in side bar, second level then 3rd level too. I would like to include very top level too so i would like to my structure to look as follow:
*A
-a
--a
-b
--b
-c
--c
Where as above code is not listing main page i.e. *A, i hope that make sense and someone will be able to help
Thanks,
I found this code snippet at the wordpress codex site, and I think it's exactly what you're looking for, I've pasted it in for convenience:
<?php
//if the post has a parent
if($post->post_parent){
//collect ancestor pages
$relations = get_post_ancestors($post->ID);
//get child pages
$result = $wpdb->get_results( "SELECT ID FROM wp_posts WHERE post_parent = $post->ID AND post_type='page'" );
if ($result){
foreach($result as $pageID){
array_push($relations, $pageID->ID);
}
}
//add current post to pages
array_push($relations, $post->ID); // <---- THIS IS INCLUDING THE PARENT
//get comma delimited list of children and parents and self
$relations_string = implode(",",$relations);
//use include to list only the collected pages.
$sidelinks = wp_list_pages("title_li=&echo=0&include=".$relations_string);
}else{
// display only main level and children
$sidelinks = wp_list_pages("title_li=&echo=0&depth=2&child_of=".$post->ID);
}
if ($sidelinks) { ?>
<h2><?php the_title() ;?></h2>
<ul>
//links in <li> tags
<?php echo $sidelinks; ?>
</ul>
<?php } ?>
It also has some built-in logic to not display everything if this is a highest-level page. Hope this helps!
<div id="breadcrumbs">
Home
<?php
$parent_id = $post->post_parent;
$breadcrumbs = array();
while ($parent_id) {
$page = get_page($parent_id);
$breadcrumbs[] = ''.get_the_title($page->ID).'';
$parent_id = $page->post_parent;
}
$breadcrumbs = array_reverse($breadcrumbs);
foreach ($breadcrumbs as $crumb) echo ' / '.$crumb;
?>
</div>
<h1><?php the_title(); ?></h1>
credit : Ivovic
from : http://wordpress.org/support/topic/display-page-parent-on-page-with-title?replies=13

Categories