Dynamically create variables in foreach loop and use on another page - php

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>";
}
?>

Related

How to make a template variable global?

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/

How to get list of current wordpress categories and inject each in script

I'm trying to create php code that will get the list of categories that are assigned to a wordpress post (of the current page) and then loop through the array list and each category that IS has been assigned to the post and add it to the script.
this is the script i need to inject the category name in:
<script> window.abkw = '<category name>';</script>
so i wrote this but it does not seem to work...
<?php
$ads = the_category();
for ($i = 0; $i < count($ads); ++$i) {
$d = $ads[$i];
<script> window.abkw = $d[$i];</script>
}
?>here
I'm new to php so please excuse my ignorance... and thank you so much.!
use get_categories() (https://developer.wordpress.org/reference/functions/get_categories/)
$categories = get_categories(array('hide_empty' => 0'));
foreach($categories as $category) {
echo '<script> window.abkw = '.$category->cat_name.';</script> ';
}
What if you use jquery data()...
https://api.jquery.com/data/#data-html5
--edited--
I expand the way
template-example.php
...
<?php
$categories = get_categories(array('hide_empty' => 0'));
foreach($categories as $category): ?>
<div class="js-category" style="visibility:hidden;" data-category = "<?php echo $category->cat_name ?>"></div> //invisible div
<?php endforeach; ?>
...
file.js
var categories = $(".js-category").data("category");
...

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

How can I send url where I use sessions?

I use sessions in the products site. My problem is how can I send the single products datasheet site's url.
In the product datasheet site, I fill up the sessions when I click on a product's image in the index site:
<?php session_start(); include "connection.php";
$sql = mysql_query("SELECT * FROM products WHERE img = '".$_COOKIE['image_src']."'");
while ($f = mysql_fetch_array($sql))
{
$_SESSION['fid'] = $f['id']; //product id
$_SESSION['fimg'] = $f['image']; //product image
$_SESSION['fname'] = $f['name']; //product name
$_SESSION['fdecription'] = $f['decription']; //product description
$_SESSION['fcategory'] = $f['category']; //product category
}
?>
Than the same site I write out the sessions (the product infos):
e.g:
<?php session_start(); print ($_SESSION[fname]);
echo "<img src='".$_SESSION['fimg']."' height='350' width='250'>";?>
But this way always the last clicked products infos will be in the sessions.
And I can't open more than one product's datasheet at the same time.
You just need to create another "level" to your session array:
<?php
session_start();
include "connection.php";
$sql = mysql_query("SELECT * FROM products WHERE img = '".$_COOKIE['image_src']."'");
# Create a counter variable
$counter = 0;
while ($f = mysql_fetch_array($sql))
{
$_SESSION[$counter]['fid'] = $f['id']; //product id
$_SESSION[$counter]['fimg'] = $f['image']; //product image
$_SESSION[$counter]['fname'] = $f['name']; //product name
$_SESSION[$counter]['fdecription'] = $f['decription']; //product description
$_SESSION[$counter]['fcategory'] = $f['category']; //product category
# Increment the counter
$counter++;
}
?>
Then on the page which you want to view the images, just loop that array:
<?php
for( $i=0; $i<count($_SESSION); $i++ )
{
...
echo '<img src="'.$_SESSION[$i]["fimg"].'">';
...
}
?>
Multi-dimensional Arrays
PHP Docs - Arrays
I solve the problem:
Firstly I have to call the page this way: index.php?image_src=XY
Then I need to use $_GET insted of $_COOKIE.
Finally with this way the sessions are unnecessary.
<?php include "connection.php";
$sql = mysql_query("SELECT * FROM products WHERE img = '".$_GET['image_src']."'");
while ($f = mysql_fetch_array($sql))
{
$fid = $f['id']; //product id
$fimg = $f['image']; //product image
$fname = $f['name']; //product name
$fdecription = $f['decription']; //product description
$fcategory = $f['category']; //product category
}
?>
And I can write out the datas:
<?php echo "<img src='".$fimg."' height='350' width='250'>";
echo "$fdecription";
?>

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