WP-JSON - Multi-endpoint - Re-occuring Foreach Error - php

I'm currently trying to build out a multi-endpoint system for WP-JSON between 4 websites, and most of the time it's fine, however sometimes when my page performs the process, it will throw back an error for the Foreach cycle, saying 'Warning: Invalid argument supplied for foreach() in ...'
I've tried alternative methods of merging the arrays before retrieving the body using wp_remote_retrieve_body but there's no such luck. I've looked up various google solutions on multiple-endpoints using php but nothing i've found seems to do an effective job
<?php
function limit_text($text, $limit) {
if (str_word_count($text, 0) > $limit) {
$words = str_word_count($text, 2);
$pos = array_keys($words);
$text = substr($text, 0, $pos[$limit]) . '...';
}
return $text;
}
/* BASE DETAILS FOR SEARCH*/
$b_url = get_site_url(); // Base URL
$posts_merged;
$args = array(
'sslverify' => false
);
if($_GET['search'] or !empty($_GET['search'])){
$filter_query = '?search='.$_GET['search'];
}else{
$filter_query = '';
}
$post_url_collective = array(
$b_url.'/wp-json/wp/v2/posts'.$filter_query, // Main Site
$b_url.'/db/wp-json/wp/v2/posts'.$filter_query, // DB Site
$b_url.'/dc/wp-json/wp/v2/posts'.$filter_query, // DC Site
$b_url.'/fw/wp-json/wp/v2/posts'.$filter_query // FW Site
);
$post_response = wp_remote_get($post_url_collective[0], $args);
$post_response = wp_remote_retrieve_body($post_response);
$post_response = json_decode($post_response);
$post_response_two = wp_remote_get($post_url_collective[1], $args);
$post_response_two = wp_remote_retrieve_body($post_response_two);
$post_response_two = json_decode($post_response_two);
$post_response_three = wp_remote_get($post_url_collective[2], $args);
$post_response_three = wp_remote_retrieve_body($post_response_three);
$post_response_three = json_decode($post_response_three);
$post_response_four = wp_remote_get($post_url_collective[3], $args);
$post_response_four = wp_remote_retrieve_body($post_response_four);
$post_response_four = json_decode($post_response_four);
$posts_merged = array_merge( $post_response, $post_response_two, $post_response_three, $post_response_four );
?>
<div class="container multi-search-wrap">
<div class="row" style="margin-bottom: 0px">
<div class="col sm12 m12 l12">
<form class="multi-search-form" method="GET">
<div class="row" style="margin-bottom: 0px">
<div class="col sm8 m9 l10">
<input type="text" name="search" value="<?php echo ( isset( $_GET['search'] ) ? $_GET['search'] : '' ); ?>" placeholder="Search for..."/>
</div>
<div class="col sm4 m3 l2">
<input type="submit" value="Search" />
</div>
</div>
</form>
</div>
</div>
<div class="row" style="background: #eeeeee;padding: 10px;font-size: 12px;margin:0px 0px 20px 0px">
<div class="col sm12 m12 l12">
We've found <strong><?php echo count($posts_merged);?></strong> results for <?php echo $_GET['search'];?>...
</div>
</div>
<div class="row">
<?php
// Post Loop
foreach($posts_merged as $get_post) {
$image_url = $b_url.'/wp-json/wp/v2/media/'.$get_post->featured_media;
$image_response = wp_remote_get($image_url, $args);
$image_response = json_decode($image_response['body']);
//echo'<pre>';print_r($image_response);echo'</pre>';
echo '<div class="col sm12 m6 l6 multi-search-post">';
echo '<div class="row">';
echo '<div class="col sm12 m3 l4 multi-search-post">';
if(!empty($image_response->media_details->sizes->thumbnail->source_url)){
echo '<img class="img_'.$get_post->id.'" src="'.$image_response->media_details->sizes->thumbnail->source_url.'" width="auto"><br>';
}else{
echo '<img class="img_'.$get_post->id.'" src="'.get_template_directory_uri().'/images/post-placeholder.jpg" width="auto"><br>';
}
echo '</div>';
echo '<div class="col sm12 m9 l8 multi-search-post">';
echo '<a href="'.$get_post->link.'">';
echo '<h3>'.$get_post->title->rendered.'</h3>';
echo '</a>';
echo '<p>'.limit_text($get_post->excerpt->rendered, 30).'</p>';
echo '</div>';
echo '</div>';
echo '</div>';
}
?>
</div>
</div>
I would like to improve the load speed of the queries but the most important part is ridding this occassional Foreach error.
Any help would be greatly appreciated

Related

Dynamically building bootstrap row, 3 per row

I am not sure the best way to go about this, on a site i'm building (using bootstrap) i want to have 3 cards per row using the grid system like:
HTML:
<div class="container">
<div class="row">
<div class="col-sm">
One of three columns
</div>
<div class="col-sm">
One of three columns
</div>
<div class="col-sm">
One of three columns
</div>
</div>
</div>
Which is no problem normally, but i'm building it (or trying to) dynamically:
PHP:
<main>
<br /><br /><br />
<?php
$pages = array_slice(scandir($_SERVER['DOCUMENT_ROOT']), 2);
$mixed = shuffle($pages);
$count = 0;
echo '<div class="container"><div class="row">';
foreach($pages as $page)
{
$count++;
if (strpos($page, '.php') !== false && $page != 'index.php') {
$html = file_get_contents($page);
$code = explode("|", extractXvideos($html));
?>
<div class="col-md-4">
<div class="card" style="width: 18rem;">
<img src="<?= $code[3]; ?>" class="card-img-top" alt="<?= $code[0]; ?>">
<div class="card-body">
<p class="card-text"><?= substr($code[0], 0, 25); ?> ...</p>
</div>
</div>
</div>
<?php
if ($count == 18) {
// The reason only 15 is showing is because we ignore ".", ".." & "index.php".
break;
}
}
}
echo '</div></div>';
?>
</main>
For this project i'm scanning .php pages on the server, then trying to lay them out 3 per row, so after every row of 3 i need to start a new row echo '<div class="container"><div class="row">'; from what i can see, i do not know the best way to go about this, any help would be appreciated.
main
<?php
$pages = array_slice(scandir($_SERVER['DOCUMENT_ROOT']), 2);
$mixed = shuffle($pages);
$count = 0;
$output = '';
foreach($pages as $page) {
$count++;
if (strpos($page, '.php') !== false && $page != 'index.php') {
$html = file_get_contents($page);
$code = explode("|", extractXvideos($html));
$output .= '<div class="container">';
$output .= '<div class="row">';
$output .= '<div class="col">Column</div>';
$output .= '<div class="col">Column</div>';
$output .= '<div class="col">Column</div>';
$output .= '</div>
$output .= '</div>';
}
}
echo $output;
?>
main
try this template and apply your conditions.

Unfdefine variable: workshop

Error
Notice: Undefined variable: workshop in C:\wamp\www\MBL\index.php on
line 273
Line 273
$workshop .= '<div class="workshopAddon col-xs-4 text-center no-padding" style="display:none;">';
Cut out of coding
</script>
<!-- Server Workshop Collection -->
<div class="col-xs-12" style="overflow:hidden;position:absolute!important;bottom:25px;">
<?php
include 'simple_html_dom.php';
$url = 'http://steamcommunity.com/sharedfiles/filedetails/?&format=json&id=124102726';
$html = file_get_html($url);
foreach($html->find('.collectionItem') as $element) {
$workshop .= '<div class="workshopAddon col-xs-4 text-center no-padding" style="display:none;">';
foreach($element->find('.workshopItemPreviewHolder') as $previewImg) {
$img = '<div class="col-xs-3 no-padding text-center circular">'.$previewImg->innertext.'</div>';
}
foreach($element->find('.workshopItemTitle') as $displayName) {
$title = '<p class="workshopItemTitle">'.$displayName->innertext.'</p>';
}
foreach($element->find('.workshopItemAuthor') as $displayName) {
$author = '<p class="workshopItemAuthor">'.$displayName->innertext.'</p>';
}
$workshop .= $img.'
<div class="col-xs-9 no-padding">
'.$title.$author.'
</div>
</div>';
}
echo $workshop;
?>
<script>
Define $workshop before you append string parts to it.
</script>
<!-- Server Workshop Collection -->
<div class="col-xs-12" style="overflow:hidden;position:absolute!important;bottom:25px;">
<?php
include 'simple_html_dom.php';
$url = 'http://steamcommunity.com/sharedfiles/filedetails/?&format=json&id=124102726';
$html = file_get_html($url);
$workshop = ''; // <!-------------------------------------------------- ADDED
foreach($html->find('.collectionItem') as $element) {
$workshop .= '<div class="workshopAddon col-xs-4 text-center no-padding" style="display:none;">';
foreach($element->find('.workshopItemPreviewHolder') as $previewImg) {
$img = '<div class="col-xs-3 no-padding text-center circular">'.$previewImg->innertext.'</div>';
}
foreach($element->find('.workshopItemTitle') as $displayName) {
$title = '<p class="workshopItemTitle">'.$displayName->innertext.'</p>';
}
foreach($element->find('.workshopItemAuthor') as $displayName) {
$author = '<p class="workshopItemAuthor">'.$displayName->innertext.'</p>';
}
$workshop .= $img.'
<div class="col-xs-9 no-padding">
'.$title.$author.'
</div>
</div>';
}
echo $workshop;
?>
<script>

Concrete5 - Custom block not editable, or recognized with the editing tool?

I'm making a site with conrete5. It's the first one I might add. I have made myself a couple of custom blocks. Named News, Teammates and References.
Now News and Teammates are not editable anymore. I will paste the News -blocks sourcecode.
----------- FORM.php ---------------------
<?php defined('C5_EXECUTE') or die(_("Access Denied.")); ?>
<?php
$al = Loader::helper('concrete/asset_library');
echo $al->file('optional', 'fID', t('Valitse kuva'), $bf, $args);
?>
<div class="form-group">
<?php echo $form->label('otsikko', t('Otsikko'));?>
<?php echo $form->text('otsikko', $otsikko);?>
</div>
<div class="form-group">
<?php echo $form->label('teksti', t('Teksti'));?>
<?php echo $form->text('teksti', $teksti); ?>
</div>
<div class="form-group">
<?php echo $form->label('korkeus', t('Korkeus'));?>
<?php echo $form->select('korkeus', array("108px"=>t("Pieni"),"299px"=>t("Iso")), $korkeus); ?>
</div>
<div class="form-group">
<?php echo $form->label('koko', t('Leveys'));?>
<?php echo $form->select('koko', array("col-md-3"=>t("Pieni"),"col-md-6"=>t("Iso")), $koko); ?>
</div>
<div class="form-group">
<?php echo $form->label('link', t('Linkki'));?>
<?php echo $form->text('link', $link); ?>
</div>
<div class="form-group">
<?php $psh = Loader::helper('form/page_selector');
echo $psh->selectPage('targetCID', $targetCID); ?>
</div>
----------- view.php ---------------------
<?php
defined('C5_EXECUTE') or die(_("Access Denied."));
$c = Page::getCurrentPage();
if($size=="col-md-3"){
$class='col-md-3';
$tag = $class;
}else{
$class="col-md-6";
$tag= $class;
}
if ($c->isEditMode()){
$class="editmode";
$editingStyle="padding: 15px; background: #ccc; color: #444; border: 1px solid #999;";
}
else {
$editingStyle = "";
}
$random = rand();
if($korkeus == "299px"){
$padding = '4px';
}else {
$padding = '5px';
}
$p = Page::getByID($targetCID);
$a = new GlobalArea('Header Navigation');
$blocks = $a->getAreaBlocksArray($c);
foreach ($blocks as $block){
if ($block->getBlockTypeHandle()=="autonav"){
$block->setCustomTemplate('cdrop.php'); // it's templates/cdrop.php -check the select option values when you set custom template manually at edit mode. I think you will need just "my_template"
$bv = new BlockView($block);
$bv->render('view');
}
}
?>
<?php $p = Page::getByID($targetCID); ?>
<a href="index.php">
<div class="pull-left <?= $koko;?>" style="padding:<?= $padding ?>;<?php echo $editingStyle;?>">
<div class="col-lg-12 alapalkki box" style="z-index:2;position:relative;">
<div class="image-big" style="background-color:transparent;text-align:center;position:relative;z-index:1;">
<!-- FiGuRe this shit out......... !-->
<?php
if($fID != 0){
$file = File::getByID($fID);
$filePath = $file->getVersion()->getRelativePath();
}
?>
<?php echo '<img src="' . $filePath . '" style="max-height:' . $korkeus . ';width:100%;"/>'; ?>
</div>
<div class="col-lg-12 " style="position:relative;z-index:255;padding:2px 0 0 15px;">
<div class="htitle">
<h4 style="color:white;"><b><?php echo $otsikko; ?></b></h4>
<p style="color:white;"><?php echo $teksti; ?></p>
</div>
</div>
</div>
</div>
</a>
Why is this not being an editable block? Why doesn't the concrete5 even recognize its existence when it is on the page? It just says at the area that it's empty.
$p = Page::getByID($targetCID);
$a = new GlobalArea('Header Navigation');
$blocks = $a->getAreaBlocksArray($c);
foreach ($blocks as $block){
if ($block->getBlockTypeHandle()=="autonav"){
$block->setCustomTemplate('cdrop.php'); // it's templates/cdrop.php -check the select option values when you set custom template manually at edit mode. I think you will need just "my_template"
$bv = new BlockView($block);
$bv->render('view');
}
}
?>
There's the problem. No idea what so ever what that is doing there..... Removed it. Worked like a charm.
-Kevin

How to display fetched results into 2 different group of divs from one inner-join-where query?

I'm having troubles displaying results into different divs.
I have this html code:
<div class="grid_10 alpha omega">
<div class="grid_5 alpha paddingtop10">
<div class="grid_5" id="titlescontent"><p class="titlebar">Subcat 1</p></div>
<div class="clear"></div>
<div class="grid_5" id="content"><p>Subsubcategories 1</p></div>
<div class="clear"></div>
</div>
<div class="grid_5 omega paddingtop10">
<div class="grid_5" id="titlescontent"><p class="titlebar">Subcat 2</p></div>
<div class="clear"></div>
<div class="grid_5" id="content"><p>Subsubcategories 2</p></div>
<div class="clear"></div>
</div>
<div class="grid_5 alpha paddingtop10">
<div class="grid_5" id="titlescontent"><p class="titlebar">Subcat 3</p></div>
<div class="clear"></div>
<div class="grid_5" id="content"><p>Subsubcategories 3</p></div>
<div class="clear"></div>
</div>
<div class="grid_5 omega paddingtop10">
<div class="grid_5" id="titlescontent"><p class="titlebar">Subcat 4</p></div>
<div class="clear"></div>
<div class="grid_5" id="content"><p>Subsubcategories 4</p></div>
<div class="clear"></div>
</div>
etc ...
</div>
<div class="clear"></div>
I'm using the 960grid system and alpha class is clearing 5px padding to the left while omega is clearing 5px padding to the right. The other classes are just for colors except of paddingtop10.
This is my php code structure I was trying to implement into my html:
if ($stmt = mysqli_prepare($connect, "SELECT subcategories.subcat_name, subsubcategories.subsubcat_name, subcategories.subcat_ID FROM subcategories INNER JOIN subsubcategories ON subcategories.subcat_ID=subsubcategories.subcat_ID WHERE subcategories.cat_ID = ? OR subcategories.extra_cat_ID = ? ORDER BY subcategories.subcat_name, subsubcategories.subsubcat_name ASC")){
mysqli_stmt_bind_param($stmt, "ii", $cat_ID, $cat_ID);
mysqli_stmt_execute($stmt);
mysqli_stmt_bind_result($stmt, $subcat_name, $subsubcat_name, $subcat_ID);
$lastcat = 0;
while (mysqli_stmt_fetch($stmt)){
if($lastcat != $subcat_ID){
$lastcat = $subcat_ID;
echo "<br>";
echo $subcat_name;
echo "<br>";
echo "<br>";
}
echo $subsubcat_name;
echo "<br>";
}
}
I want to generate the alpha and omega divs through php but I'm not sure how to do this.
I tried this code but it doesn't give me the right result like I want shown in my html example code:
if ($stmt = mysqli_prepare($connect, "SELECT subcategories.subcat_name, subsubcategories.subsubcat_name, subcategories.subcat_ID FROM subcategories INNER JOIN subsubcategories ON subcategories.subcat_ID=subsubcategories.subcat_ID WHERE subcategories.cat_ID = ? OR subcategories.extra_cat_ID = ? ORDER BY subcategories.subcat_name, subsubcategories.subsubcat_name ASC")){
mysqli_stmt_bind_param($stmt, "ii", $cat_ID, $cat_ID);
mysqli_stmt_execute($stmt);
mysqli_stmt_bind_result($stmt, $subcat_name, $subsubcat_name, $subcat_ID);
$lastsubcat = 0;
while (mysqli_stmt_fetch($stmt)){
echo '<div class="grid_5 alpha paddingtop10">';
echo '<div class="grid_5" id="titlescontent"><p class="titlebar">';
if($lastsubcat != $subcat_ID){
$lastsubcat = $subcat_ID;
echo $subcat_name;
}
echo '</p></div>';
echo '<div class="clear"></div>';
echo '<div class="grid_5" id="content"><p>';
echo $subsubcat_name;
echo '</p></div>';
echo '<div class="clear"></div>';
echo '</div>';
echo '<div class="grid_5 omega paddingtop10">';
echo '<div class="grid_5" id="titlescontent"><p class="titlebar">';
if($lastsubcat != $subcat_ID){
$lastsubcat = $subcat_ID;
echo $subcat_name;
}
echo '</p></div>';
echo '<div class="clear"></div>';
echo '<div class="grid_5" id="content"><p>';
echo $subsubcat_name;
echo '</p></div>';
echo '<div class="clear"></div>';
echo '</div>';
}
}
Any idea how I need to make this work?
Thank you for any help!
The only thing I can think of is to use a counter to track when you're in the first or last iteration. This would work even if the loop has only one item.
$values = mysqli_stmt_fetch($stmt);
$i = 0;
$len = count($values);
while ($values) {
$i++;
...
if ($i == 1) {
// add alpha class
}
...
if ($i == $len) {
// add omega class
}
}
Does that spark any ideas for you?

Foreach loop not always displaying

I'm retrieving data out of a database using PHP's PDO extension. I never had a problem with this and it always shows up in all browsers. BUT when I tested the website on a friends laptop, the foreach loop works but the content is not displayed. The content is present in the source code.
this is how I set up the code that should be displayed:
<?php
foreach($advertentiesManager->recenteAdvertenties() as $advertentie) {
$verkoperData = $usersManager->userData($advertentie->verkoper);
?>
<div class="col-md-4" style="margin:10px 0;">
<div class="advertentie">
<div class="overlay"></div>
<div class="img" style="background:url('images/categorie/<?php echo $advertentie->categorie; ?>.jpg') no-repeat center center;background-size:cover;"></div>
<div class="picture" style="background:url('<?php echo str_replace("../", "", $verkoperData->foto); ?>') no-repeat center center;background-size:cover;"></div>
<div class="prijs"><p class="h2">€ <?php echo $advertentie->verkoopprijs; ?></p></div>
<div style="padding: 10px;padding-left:80px;margin-top:-40px;">
<a href="<?php echo $advertentie->type.'/'.strtolower(str_replace(" ", "-", $advertentie->titel)).'-'.$advertentie->id; ?>">
<?php echo $advertentie->titel; ?>
</a>
<br>
<p style="color:#777;font-size:.9em;">
<?php
$beschrijving = strip_tags($advertentie->omschrijving);
$max_length = 100;
if (strlen($beschrijving) > $max_length) {
$offset = ($max_length - 3) - strlen($beschrijving);
$beschrijving = substr($beschrijving, 0, strrpos($beschrijving, ' ', $offset)) . '... Meer';
} else {
$beschrijving = $advertentie->omschrijving;
}
echo $beschrijving;
?>
</p>
</div>
</div>
</div>
<?php
}
?>
You can view a live example at http://www.coupontrade.nl/ the content should be displayed under "Recente advertenties" and above the twitter part.

Categories