I do not know if this is possible, but what I am trying to do is create a value for a key within an object that is an array, and then loop through that array in a for loop. My object is coded like this:
<?php $shoots[01] = array(
"name" => "Rustic Farm Shoot",
"id" => "rustic",
"img" => array("img/slider.jpg", "img/testb2.jpg")
); ?>
My code on my page looks like this:
<div id="main-content">
<div class="slideshow">
<?php foreach($shoots as $shootID => $shoot) {
if($_GET["id"] == $shootID) {
for (i = 0; i < $shoot['img'[]].length ; i++) { ?>
<img src="<?php echo $shoot['img'[i]]; ?>" alt="<?php echo $shoot['name']; ?>">
<?php }}}; ?>
</div>
</div>
I have called for the url change earlier on the page, and that is working correctly. I am positive my problem is in this section. This is probably obvious, but I am new to working with PHP, so any help, even if it's something really dumb that I've done, is greatly appreciated.
Looks like you need a nested for-loop.
Here's the rough idea:
$shoots[01] = array(
"name" => "Rustic Farm Shoot",
"id" => "rustic",
"img" => array("img/slider.jpg", "img/testb2.jpg")
);
foreach($shoots as $shootID => $shoot) {
if($_GET["id"] == $shootID) {
foreach($shoot['img'] as $img) {
echo "<img src='$img' alt='$shoot[name]'>";
}
}
}
Related
I have some code that iterates over JSON in my project to display reviews in a slider. This code works, however I only want to display reviews where the array key 'comment' exists. I feel like the solution must be using array_key_exists, but I can't get the code correct (I'm still quite a novice with PHP). I've tried searching all over SO without much success. Here's an example of some of the JSON I'm working with; REVIEW ID 1 is review that I want to display, and REVIEW ID 2 is one I want to skip:
{
"reviewId": "{REVIEW ID 1}",
"reviewer": {
"profilePhotoUrl": "{PROFILE PHOTO URL}",
"displayName": "PERSON 1"
},
"starRating": "FIVE",
"comment": "This is a review",
"createTime": "2019-08-30T15:38:59.412Z",
"updateTime": "2019-08-30T15:38:59.412Z",
"reviewReply": {
"comment": "{REVIEW REPLY}",
"updateTime": "2019-08-30T16:05:58.184Z"
},
"name": "accounts/{ACCOUNT NUMBER}/locations/{LOCATION NUMBER}/reviews/"
},
{
"reviewId": "{REVIEW ID 2}",
"reviewer": {
"profilePhotoUrl": "{PROFILE PHOTO URL}",
"displayName": "PERSON 2"
},
"starRating": "FIVE",
"createTime": "2019-02-07T14:59:28.729Z",
"updateTime": "2019-02-07T14:59:28.729Z",
"name": "accounts/{ACCOUNT NUMBER}/locations/{LOCATION NUMBER}/reviews/"
},
And here's the code that runs the reviews:
$jsonreviews = plugin_dir_path( __DIR__ ) . './latest.json';
$reviews2var = file_get_contents($jsonreviews);
$reviews = json_decode($reviews2var, true);
$starpath = plugin_dir_url( __FILE__ ) . './img/fivestars.svg';
$truckpath = plugin_dir_url( __FILE__ ) . './img/chad_love_truck.png';
// Start buffer
ob_start();
?>
<div class="reviews-background">
<div class="swiper-container review-container">
<div class="swiper-wrapper review-wrapper">
<?php
$counter = 1;
foreach ($reviews['reviews'] as $review) :
if ($counter > 3) {
//do nothing
} else {
?>
<div class="swiper-slide review-slide">
<img src="<?php echo $starpath;?>" alt="5 Stars" class="five-stars" />
<?php $counter++;?>
<div class="truncate" data-excerpt>
<div data-excerpt-content>
<p class="slider-review-text">
<?php echo $review['comment'];?></p>
</div>
</div>
<p class="slider-review-auth">
<?php echo $review['reviewer']['displayName'];?>,
</p>
</div>
<?php } ?>
<?php endforeach;?>
How can I properly implement array_key_exists in the above, or should I be doing something else entirely? Thank you
You can check if comment is NOT set here:
if ($counter > 3 || !isset($review['comment'])) {
//do nothing
} else {
$counter++;
//HTML
}
However, I would probably flip the if logic and you won't need an else:
if ($counter <= 3 && isset($review['comment'])) {
$counter++;
//HTML
}
If you have large arrays, you probably want to break out of the loop if you have displayed more than 3 (or some number):
if ($counter > 3)
break;
} elseif (isset($review['comment'])) {
$counter++;
//HTML
}
You can substitute !array_key_exists and array_key_exists for the issets if you want.
I think this is the simple approach
if(isset($test[$key_check])){
echo $value = $test[$key_check];
}
Or check for array exist :
if (array_key_exists($key_check, $test)) {
return $test[$key_check];
}
I am using wordpress and would like to offer the user the capability to use a shortcode to pull a slider into the post / page.
i.e [slider id="2"]
I have done the following:
Created custom post type 'Sliders'
Used Advanced Custom Fields to create all the fields required within the post type.
Created the shortcode using:
function landwSliderShortcode($atts = [], $content = null, $tag = '')
{
$atts = array_change_key_case((array)$atts, CASE_LOWER);
$slider_atts = shortcode_atts([
'id' => '1',
], $atts, $tag);
return $slider_atts['id'];
}
function landwSliderShortcodes_init()
{
add_shortcode('slider', 'landwSliderShortcode');
}
add_action('init', 'landwSliderShortcodes_init');
I now need to call another function that is going to perform the WP_Query of the custom post type and build the HTML slider... It is this part I am struggling with. I have got this far:
function getSliderData($sliderId) {
$slidercount = 0;
$args = array(
'post_type' => 'slider',
'post_status' => 'publish',
'posts_per_page' => '1',
'p' => $sliderId,
);
$sliderLoop = new WP_Query( $args );
if ( $sliderLoop->have_posts() ) :
while ( $sliderLoop->have_posts() ) : $sliderLoop->the_post();
$image = get_sub_field('image');
$image_render = $image['sizes'][$image_asset_size];
$add_link = get_sub_field('add_link');
$link_type = get_sub_field('link_type');
$internal_link = get_sub_field('internal_link');
$external_link = get_sub_field('external_link');
$add_lightbox = get_sub_field('add_lightbox');
$lightboxasset = get_sub_field('lightbox_asset');
$lightboxassetcaption = get_sub_field('lightbox_caption');
$caption = get_sub_field('caption');
$sub_caption = get_sub_field('sub_caption');
?>
<div class="slider-wrap">
<?php if ($add_link) {
if ($link_type == "External") {
echo '<a class="carousel-slide-link" href="'.$external_link.'" target="_blank"></a>';
} else {
echo '<a class="carousel-slide-link" href="'.$internal_link.'"></a>';
}
}
?>
<?php if ($add_lightbox) { ?>
<a class="carousel-slide-link" data-fancybox data-src="#SliderModal<?php echo $slidercount ?>" target="_blank" href="javascript:;"></a>
<?php } ?>
<img src="<?php echo $image_render; ?>">
<!-- 6 Mar 17 added conditional to show the caption -->
<?php if (strlen($sub_caption) > 0 || strlen($caption) > 0) : ?>
<div class="post-wrap-meta">
<span><?php echo $sub_caption; ?></span>
<p class="slider-caption-text"><?php echo $caption; ?></p>
</div>
<?php endif ?>
</div>
<!-- output the modal -->
<div style="display: none;" class="standard__modal" id="SliderModal<?php echo $slidercount; ?>">
<?php echo $lightboxasset ?>
<p class="slider-caption-text">
<?php echo $lightboxassetcaption ?>
</p>
</div>
<?php
$slidercount ++;
endwhile;
?>
<?php
endwhile;
wp_reset_postdata();
endif;
}
I hope to be able to pass the sliderId var to this function and return a fully functioning slider (there is a small Javascript function I need to add to this HTML as well).
Many thanks in advance to anyone whole can help with this.
Instead of using WP_Query, ->have_posts(), while, wp_reset_postdata, use a simple get_posts($args) and do a for loop over the results.
- - see When should you use WP_Query vs query_posts() vs get_posts()?
And instead of echo, build a HTML string that will be returned to the shortcode. WordPress shortcodes should never echo anything, they expect a string to be returned. PHP heredoc is perfect for that, example:
function getSliderData($sliderId) {
$some_var = 'Value of the var';
$html = <<<HTML
<div>$some_var</div>
<h3>$post->title</h3>
HTML;
return $html;
}
Important: the closing HTML; must not have white spaces before or after.
Ideally, you'll build the $html bit by bit, making sure it's returning the perfect markup. You can use $html .= to compose the string in more than one operation.
I have an array of items (cheese) in a checkbox format like so
array(
'type' => 'checkbox',
"holder" => "div",
"class" => "",
"heading" => __("Choose your cheese topping", 'rbm_menu_item'),
'param_name' => 'cheesbox',
'value' => array( 'Cheddar'=>'Chedder', 'Gouda'=>' Gouda', 'Bleu'=>' Bleu'),
"description" => __("<br /><hr class='gduo'>", 'rbm_menu_item')
),
The values of the array are displayed on a page (in a hidden div) using the heredoc declaration with an if to check if the checkbox has been used - if the return is empty the div does not show - if one of the checkboxes is "checked" then it does.
///Cheese selections
if (!empty($cheesbox)) {
$output .= <<< OUTPUT
<br />
<div class="sides">Comes with: <p>{$cheesebox}</p></div>
<br />
OUTPUT4;
}
What I need to do is pull any one of the values in the array and if its in the $cheesebox the do something.
Ive tried using an ifelse like this
if ( ('$cheesebox') == "Cheddar" ){
echo "Your topping is Cheddar";
}
elseif ( ('$cheesebox') == "Gouda" ){
{
echo "Your topping is Gouda";
}
elseif ( ('$cheesebox') == "Bleu" ){
{
echo "Your topping is Bleu";
}
however this does not work - I'm sure I have it wrong somehere along the line or does the heredoc function only allow for one?
if so is there a way to accomplish this?
Single quotes in PHP mean a literal string with no parsing of variables. Try this:
if ($cheesebox == "Cheddar") {
echo "Your topping is Cheddar";
} else if ($cheesebox == "Gouda") {
echo "Your topping is Gouda";
} else if ($cheesebox == "Bleu") {
echo "Your topping is Bleu";
}
Better yet:
if (in_array($cheesebox, ['Cheddar', 'Gouda', 'Bleu'])) {
echo "Your topping is {$cheesebox}";
}
EDIT: In response to your further requirements in the comments:
In your PHP:
$cheeses = ['Cheddar', 'Gouda', 'Bleu'];
$cheeseBoxes = '';
foreach ($cheeses as $cheese) {
$cheeseClass = $cheesebox == $cheese ? '' : 'cheese-hidden';
$cheeseBoxes .= <<<CHEESE
<div class="cheese {$cheeseClass}">
<p>Cheese: {$cheese}</p>
<img src="/images/cheeses/{$cheese}.png" alt="A picture of some {$cheese}" />
</div>
CHEESE;
}
// Then, wherever you need it, or just use $cheeseBoxes in your chosen heredoc:
echo $cheeseBoxes;
In your CSS, to hide the inactive ones:
.cheese.cheese-hidden {
display: none;
}
i have a problem similar to this question
How to identify active menu link in CakePHP
i have a page in my default.ctp file in which i want to add 'active' class on links. how can i identify the current url of the page and then apply the class on link.. i have followed the answer also there which is
$url = $this->Html->url('INPUT_THE_URL') ;
$active = $this->request->here == $url? true: false;
i dont know how can i do this in my code .. sorry for asking as i am newbie in cakephp .. here is my code
**default.ctp file**
<li>
<?php echo $this->Html->link('Dashboard', array('controller'=>'users','action' => 'controlpanel'), array('title' => 'Dashboard','class' => 'shortcut-dashboard'));?></li>
<li> <?php echo $this->Html->link('Contacts', array('controller'=>'contacts','action' => 'index'), array('title' => 'Contacts','class' => 'shortcut-contacts'));?></li>
i want to add a class with li like this
<li class = 'active''>
This is a simple logic as follows
<li class="<?php echo (!empty($this->params['action']) && ($this->params['action']=='controlpanel') )?'active' :'inactive' ?>">
<?php echo $this->Html->link('Dashboard', array('controller'=>'users','action' => 'controlpanel'), array('title' => 'Dashboard','class' => 'shortcut-dashboard'));?>
</li>
<li class="<?php echo (!empty($this->params['action']) && ($this->params['action']=='index') )?'active' :'inactive' ?>">
<?php echo $this->Html->link('Contacts', array('controller'=>'contacts','action' => 'index'), array('title' => 'Contacts','class' => 'shortcut-contacts'));?></li>
If you have a different controller and you have declared a method with same name, and the above code is not working, then you can do the following:
<li class="<?php echo (($this->params['controller']==='hotels')&& ($this->params['action']=='view') )?'active' :'' ?>" >
<?php echo $this->Html->link('Hotels', array('controller' => 'hotels', 'action' => 'view')); ?>
</li>
<li class="<?php echo (($this->params['controller']==='packages')&& ($this->params['action']=='view') )?'active' :'' ?>" >
<?php echo $this->Html->link('Packages', array('controller' => 'packages', 'action' => 'view')); ?>
</li>
Here view method is declared in different controller. i hope it will be helpful for you.
Not to revive a dead post, but this is what I do (which I believe is a bit cleaner and faster and a bit more manageable)
I create an element that has an array of pages, then I check against each item in the array to see if it is the current page. If it is I add the active class.
I can then call this element from anywhere.
// Changed the line below to a multi-dimensional array to cater for different controllers and actions
//$mypages = array('Home','About','Pricing','FAQs','Contact');
$mypages = array(
array('controller'=>'controller1','action'=>'action1','name'=>'name1'),
array('controller'=>'controller2','action'=>'action2','name'=>'name2
')
);
foreach ($mypages as $page ){
// Changed to account for controller and action
//$currentPage = isset($this->params['pass'][0]) ?$this->params['pass'][0] : "";
$controller = isset($this->request->params['controller'])?$this->request->params['controller']: "";
$action= isset($this->request->params['action'])?$this->request->params['action']: "";
if (strtolower($page['controller']) == $controller && strtolower($page['action']) == $action) {
echo "<li class='active'>" . $this->Html->link($page,array("controller"=>"pages", "action"=>strtolower($page))) . "</li>" ;
}
else {
echo "<li>" . $this->Html->link($page,array("controller"=>"pages", "action"=>strtolower($page))) . "</li>";
}
}
I'm trying to implement SlickGrid on the edit page of a CakePHP project, and when the page loads I get this error in the javascript console:
slick.grid.js:2173TypeError:'Slick.Editors.Text is not a constructor' (evaluating 'new (editor || getEditor(activeRow, activeCell))')
The data renders correctly in the grid on my page, but when I click on a cell to edit it, it just turns white and I can't type anything. If I click on another cell, that cell will turn white and the first one will stay white.
Here is my php/jQuery code:
<?php echo $this->Html->script("/js/slickgrid/lib/jquery-1.7.min.js"); ?>
<?php echo $this->Html->script("/js/slickgrid/lib/jquery.event.drag-2.0.min.js"); ?>
<?php echo $this->Html->script("/js/slickgrid/lib/jquery-ui-1.8.16.custom.min.js"); ?>
<?php echo $this->Html->script("/js/slickgrid/slick.core.js"); ?>
<?php echo $this->Html->script("/js/slickgrid/slick.grid.js"); ?>
<?php echo $this->Html->script("/js/slickgrid/slick.editors.js"); ?>
<?php echo $this->Html->script("/js/slickgrid/slick.formatters.js"); ?>
<?php echo $this->Html->script("/js/slickgrid/slick.dataview.js"); ?>
<?php echo $this->Html->script("/js/slickgrid/plugins/slick.cellselectionmodel.js"); ?>
<?php echo $this->Html->script("/js/slickgrid/plugins/slick.cellrangedecorator.js"); ?>
<?php echo $this->Html->script("/js/slickgrid/plugins/slick.cellrangeselector.js"); ?>
<?php echo $this->Html->script("/js/slickgrid/plugins/slick.rowselectionmodel.js"); ?>
<?php // Setup rows and cols array for grid
$columns = array();
foreach($route['Stop'] as $stop) {
$columns[] = array( "name" => $stop['name'],
"field" => $stop['id'],
"id" => $stop['id'],
"editor" => "Slick.Editors.Text");
}
$tripId = 1;
$thisTrip['id'] = $tripId;
foreach($route['RouteTrip'] as $routeTrip) {
if($routeTrip['trip_id'] != $tripId) {
$rows[] = $thisTrip;
$tripId = $routeTrip['trip_id'];
$thisTrip['id'] = $tripId;
}
else {
$thisTrip[$routeTrip['stop_id']] = $routeTrip['time'];
}
}
?>
<?php
echo $this->Html->scriptBlock('
var rows = '.json_encode($rows).';
var columns = '.json_encode($columns).';
var options = { rowHeight:21,
defaultColumnWidth:100,
editable:true,
enableAddRow:true,
enableCellNavigation:true,
asyncEditorLoading:false,
autoHeight:true,
autoEdit:true
};
slickgrid = new Slick.Grid($("#scheduleTable"), rows, columns, options);
slickgrid.setSelectionModel(new Slick.CellSelectionModel());
slickgrid.updateRowCount();
slickgrid.render();
');
?>
The $rows and $columns are correctly formatted, and each column has an "editor" attribute with "Slick.Editors.Text" as its value.
Help?
I have also got this error initially when i started working with slickgrid.
The error is because you have specified the editor as string and not as a class.
So, remove the double quotes in "editor" => "Slick.Editors.Text" and give as "editor" => Slick.Editors.Text
This solved the error for me. Hope this solution will solve yours too.
Include the slick.editors.js file.
Also, make sure that the editor is being specified as a class, not as a string (I'm not familiar with PHP, so it's not obvious to me from the source code, but I suspect that's the case).