Adding Pagination to a 3rd party module (OT-MiniNewsModule) - php

i'm currently trying to modify a module that works almost perfectly for my requirements, but lacks pagination. I can't seem to grasp how i should add the pagination to it; most JPagination examples assume i have access to the query but in this module (which uses JFactory, JmoduleHelper & JModel) i don't see the query in order to add the limits and such.
mod_otmininews.php
//No direct access!
defined('_JEXEC') or die;
// Include the syndicate functions only once
require_once dirname(__FILE__).DS.'helper.php';
$doc = &JFactory::getDocument();
$doc->addStyleSheet(JURI::base().'/modules/mod_otmininews/css/layout.css');
$list = modOtMiniNewsHelper::getList($params);
$moduleclass_sfx = htmlspecialchars($params->get('moduleclass_sfx'));
require JModuleHelper::getLayoutPath('mod_otmininews', $params->get('layout', 'default'));
helper.php
//No direct access!
defined('_JEXEC') or die;
require_once JPATH_SITE.'/components/com_content/helpers/route.php';
jimport('joomla.application.component.model');
JModel::addIncludePath(JPATH_SITE.'/components/com_content/models');
abstract class modOtMiniNewsHelper
{
public static function getList(&$params)
{
// Get the dbo
$db = JFactory::getDbo();
// Get an instance of the generic articles model
$model = JModel::getInstance('Articles', 'ContentModel', array('ignore_request' => true));
// Set application parameters in model
$app = JFactory::getApplication();
$appParams = $app->getParams();
$model->setState('params', $appParams);
// Set the filters based on the module params
$model->setState('list.start', 0);
$model->setState('list.limit', (int) $params->get('count', 3));
$model->setState('filter.published', 1);
// Access filter
$access = !JComponentHelper::getParams('com_content')->get('show_noauth');
$authorised = JAccess::getAuthorisedViewLevels(JFactory::getUser()->get('id'));
$model->setState('filter.access', $access);
// Category filter
$model->setState('filter.category_id', $params->get('catid', array()));
// User filter
$userId = JFactory::getUser()->get('id');
switch ($params->get('user_id'))
{
case 'by_me':
$model->setState('filter.author_id', (int) $userId);
break;
case 'not_me':
$model->setState('filter.author_id', $userId);
$model->setState('filter.author_id.include', false);
break;
case '0':
break;
default:
$model->setState('filter.author_id', (int) $params->get('user_id'));
break;
}
// Filter by language
$model->setState('filter.language',$app->getLanguageFilter());
// Featured switch
switch ($params->get('show_featured'))
{
case '1':
$model->setState('filter.featured', 'only');
break;
case '0':
$model->setState('filter.featured', 'hide');
break;
default:
$model->setState('filter.featured', 'show');
break;
}
// Set ordering
$order_map = array(
'm_dsc' => 'a.modified DESC, a.created',
'mc_dsc' => 'CASE WHEN (a.modified = '.$db->quote($db->getNullDate()).') THEN a.created ELSE a.modified END',
'c_dsc' => 'a.created',
'p_dsc' => 'a.publish_up',
'h_dsc' => 'a.hits',
);
$ordering = JArrayHelper::getValue($order_map, $params->get('ordering'), 'a.publish_up');
$dir = 'DESC';
$model->setState('list.ordering', $ordering);
$model->setState('list.direction', $dir);
$items = $model->getItems();
foreach ($items as &$item) {
$item->slug = $item->id.':'.$item->alias;
$item->catslug = $item->catid.':'.$item->category_alias;
if ($access || in_array($item->access, $authorised))
{
// We know that user has the privilege to view the article
$item->link = JRoute::_(ContentHelperRoute::getArticleRoute($item->slug, $item->catslug));
}
else {
$item->link = JRoute::_('index.php?option=com_user&view=login');
}
//$item->title = htmlspecialchars( $item->title );
$item->content= strip_tags(preg_replace('/<img([^>]+)>/i',"",$item->introtext));
$item->content = substr($item->content, 0, $params->get('introtext_limit'));
preg_match_all('/img.+src="([^"]+)"/i', $item->introtext, $matches);
if(empty($matches[1][0])){
$item->images="";
}else{
$item->images= $matches [1] [0];
}
//Show thumbnails
if($params->get('showthumbnails')==1){
if($item->images == ""){
$item->thumbnail = '<img src="'.$params->get('directory_thumbdefault').'" width="'.$params->get('thumbwidth').'" height="'.$params->get('thumbheight').'" alt="'.$item->title.'" />';
}else{
$item->thumbnail = '<img src="' .$item->images.'" width="'.$params->get('thumbwidth').'" height="'.$params->get('thumbheight').'" alt="'.$item->title.'" />' ; //show images
}
}
$item->created_date = $item->created;
}
return $items;
}
}
All this code creates an array used by
default.php
defined('_JEXEC') or die;
?>
<div class="ot_news">
<div class="ot_news_i">
<?php
$count = 0;
foreach ($list as $item) : ?>
<?php $count++; ?>
<div class="ot_items <?php echo ($params->get('count') == $count)?'last-item':''; ?>">
<!-- Show thumbnails -->
<?php if($params->get('showthumbnails') == 1){?>
<div class="ot_thumbs" style="width:<?php echo $params->get('thumbwidth')?>px; height:<?php echo $params->get('thumbheight')?>px;">
<?php if($params->get('enablelinkthumb') == 1) {?>
<?php echo $item->thumbnail ;?>
<?php } else { ?>
<?php echo $item->thumbnail?>
<?php }?>
</div>
<?php } else { ?>
<?php echo ''; ?>
<?php } ?>
<!-- End -->
<!-- Show Titles -->
<div class="ot_articles">
<?php if($params->get('showtitle') == 1) { ?>
<div class="ot_title">
<?php if($params->get('enablelinktitle') == 1) { ?>
<?php echo $item->title; ?>
<?php }else{?>
<span class="title"><?php echo $item->title; ?></span>
<?php }?>
</div>
<?php } ?>
<!-- Show Created Date -->
<?php
if ($params->get('show_date') == 1) {
echo '<p class="createddate"><span class="ot_date">';
$date = $item->created_date;
echo JHTML::_('date', $date, $params->get( 'date_format' ));
echo '</span></p>';
}
?>
<!-- Show Content -->
<div class="ot_content"><?php echo $item->content; ?></div>
<!-- Show Readmore -->
<?php if($params->get('readmore') == 1) {?>
<div class="ot_readmore"><?php echo JText::_('READMORE') ?></div>
<?php }else {?>
<?php echo ''; ?>
<?php } ?>
</div>
</div>
<div class="spaces"></div>
<?php endforeach; ?>
</div>
</div>
<div class="ot-mini-news"><?php echo JText::_('ABOUT_OT_MINI_NEWS'); ?></div>
that just uses a for each to show the items with their photos links and descriptions.
So as you can see i have seriously no clue where to add the Pagination code, and i suspect they even use some part of it for the display (i saw a getlist function in the helper.php file.
Any help would be much appreciated.

http://docs.joomla.org/Using_JPagination_in_your_component This is a highly useful document for this - even though this is for a module and the wiki page is using it for a component.
$db =& JFactory::getDBO();
$lim = $mainframe->getUserStateFromRequest("$option.limit", 'limit', 14, 'int'); //I guess getUserStateFromRequest is for session or different reasons
$lim0 = JRequest::getVar('limitstart', 0, '', 'int');
$db->setQuery('SELECT SQL_CALC_FOUND_ROWS x, y, z FROM jos_content WHERE x',$lim0, $lim);
$rL=&$db->loadAssocList();
if (empty($rL)) {$jAp->enqueueMessage($db->getErrorMsg(),'error'); return;}
else {
////Here the beauty starts
$db->setQuery('SELECT FOUND_ROWS();'); //no reloading the query! Just asking for total without limit
jimport('joomla.html.pagination');
$pageNav = new JPagination( $db->loadResult(), $lim0, $lim );
foreach($rL as $r) {
//your display code here
}
echo $pageNav->getListFooter( ); //Displays a nice footer
You can see in their code that whilst they do use the db result, that the pagination doesn't 'depend' on the query. Only the results which come from it. So for the $db->loadResult() for example you can just use a php count forumla to see how many rows there are in the array being produced by the module. In your case counting the number of $items.
The foreach command is still as you have it as well. With just the foreach($rL as $r) just corresponding to the existing foreach($items as $item). So the fact you don't have the database query as you see - shouldn't actually be an issue!
So the code you want will be something like:
global $option; //If Joomla 1.5
global $mainframe; //If Joomla 2.5
$option = JRequest::getCmd('option') //If Joomla 2.5
$mainframe = JFactory::getApplication(); //If Joomla 2.5
$lim = $mainframe->getUserStateFromRequest("$option.limit", 'limit', 14, 'int'); //I guess getUserStateFromRequest is for session or different reasons
$lim0 = JRequest::getVar('limitstart', 0, '', 'int');
if (empty($items)) {
$app->enqueueMessage($db->getErrorMsg(),'error');
return;
} else {
jimport('joomla.html.pagination');
$pageNav = new JPagination( count($list), $lim0, $lim );
foreach($list as $item) {
//wrap in your code here that you had in the foreach already
}
echo $pageNav->getListFooter( ); //Displays a nice footer
Make sure you remove one of the top two lines depending on whether you're using Joomla 1.5 or 2.5 but that should work.

Related

How can i create a new section with only 5 elements in PHP?

i have a PHP code that creates a team page with team member boxes on my website. The code for every team meber is fetched from the database, and it works fine, but time has passed and we are many now. So many, that I need to display only 5 team members per section. Like 5 team members in one line, the next 5 in the other line, .. - I tried a few things to do that, but I got stuck. Sometimes members were missing, sometimes he created many lines with the same members, and so on. That's why I'm asking here. I already searched a bit but couldn't find anything that helps me.
Currently, my code creates a new <section> for ALL team members. But that's not what I need. It should create a section for 5 members, the next section for the next 5 members, and so on. How can I do that?
(btw I'm a complete beginner in PHP and want to learn something from it so you can improve my code if you want.)
function team_helfer() {
$db = new mysqli("ip", $username, $password, $database);
$result = mysqli_query($db, "SELECT code FROM team_data WHERE rank = 'HELFER'");
$team_list = "";
$count = 0;
while ($row = mysqli_fetch_assoc($result)) {
foreach ($row as $field => $value) {
$team_list .= "$value";
++$count;
}
}
if ($count == 2) {
$code = '<section class="elementor-section elementor-inner-section elementor-element elementor-section-boxed elementor-section-height-default elementor-section-height-default" data-element_type="section">
<div class="elementor-container elementor-column-gap-default" style="left: 17%;">
'.$team_list.'
</div>
</section>';
} elseif ($count == 1) {
$code = '<section class="elementor-section elementor-inner-section elementor-element elementor-section-boxed elementor-section-height-default elementor-section-height-default" data-element_type="section">
<div class="elementor-container elementor-column-gap-default" style="left: 33%;">
'.$team_list.'
</div>
</section>';
} else {
$code = '<section class="elementor-section elementor-inner-section elementor-element elementor-section-boxed elementor-section-height-default elementor-section-height-default" data-element_type="section">
<div class="elementor-container elementor-column-gap-default">
'.$team_list.'
</div>
</section>';
}
mysqli_free_result($result);
$db->close();
return $code;
}
add_shortcode( 'team_helfer', 'team_helfer' );
Code from HTMHell's answer:```php
function team_helfer() {
$db = new mysqli("ip", $username, $password, $database);
$result = mysqli_query($db, "SELECT code FROM team_data WHERE rank = 'HELFER'");
$rows = mysqli_fetch_all($result, MYSQLI_ASSOC);
$sections = array_chunk($rows, 5);
foreach ($sections as $section) {
$teamList = implode(",", array_map(function($row) {
return $row['code'];
}));
$code = '<section class="elementor-section elementor-inner-section elementor-element elementor-section-boxed elementor-section-height-default elementor-section-height-default" data-element_type="section">
<div class="elementor-container elementor-column-gap-default">'.$teamList.'</div></section>';
}
mysqli_free_result($result);
$db->close();
return $code;```
Sadly that doesn't help, all elements are vanished now, i can't see them.
I think you are looking for array_chunk.
$rows = mysqli_fetch_all($result, MYSQLI_ASSOC);
$sections = array_chunk($rows, 5);
foreach ($sections as $section) {
$teamList = implode(",", array_map(function($row) {
return $row['code'];
}, $section));
echo "<section>$teamList</section>";
}
Here's a live example:
https://3v4l.org/mXRtV

Automatic Blog - Multiple PHP function declaration?

I want to generate HTML using PHP based on files in a specific Folder, everything works for the first File but if I add a second File, I just see:
Fatal error: Cannot redeclare getTitle() (previously declared in [path]:3) in [path].php on line 4
I understood the Problem but I don't know how to solve it. This is the PHP-Code of the main File:
foreach (glob("content/blog/*.php") as $file) {
require_once $file;
$index = str_replace("content/blog/", "", str_replace(".php", "", str_replace("img/", "", $file)));
?>
<div class="content">
<h3><?php getTitle() ?><span><?php getPublishedDate() ?></span></h3>
<p><?php getContent() ?></p>
</div>
<?php
$file = null;
}
?>
And this is the PHP-Code in every Blog-File:
<?php
function getTitle() {
echo "Lorem Ipsum 2!";
}
function getPublishedDate() {
echo "When Time has finally come";
}
function getContent() {
echo "<p>Text</p>";
}
?>
I searched for opposites of include, include_once, require or require_once. I also tried Setting the variable back to null before foreach is called again.
Thanks for any help in advance.
Define a class to store the information about one blog post.
// name this file class.blogEntry.php
class blogEntry {
var $title;
var $publishedDate;
var $content;
public function getTitle() {
return $this->title;
}
public function setTitle($title) {
$this->title = $title;
}
public function getPublishedDate() {
return $this->publishedDate;
}
public function setPublishedDate($date) {
$this->publishedDate = $date;
}
public function getContent() {
return $this->content;
}
public function setContent($content) {
$this->content = $content;
}
}
For each blog post create a simple php file to set it's different properties
$entry->setTitle("Lorem Ipsum 2!");
$entry->setPublishedDate("When Time has finally come");
$entry->setContent("<p>Text</p>");
Modify your output to use the class and the class based blog entries
require_once 'class.blogEntry.php';
foreach (glob("content/blog/*.php") as $file) {
$entry = new blogEntry();
require_once $file;
$index = str_replace("content/blog/", "", str_replace(".php", "", str_replace("img/", "", $file)));
?>
<div class="content">
<h3><?php $entry->getTitle() ?><span><?php $entry->getPublishedDate() ?></span></h3>
<p><?php $entry->getContent() ?></p>
</div>
<?php
$file = null;
}
?>
The problem is you have several files, defining the same function getTitle and you are requiring them.
Requiring or including a *.php file is like merging all the code into one single file, which explains the error, because you are requiring n files and in each of them you are defining the same functions.
You can do something like this instead of functions you can use associative array.
<?php
// blog_file_1.php
$prop = array(
'title' => "This is file 1!",
'published_date' => "When Time has finally come",
'content' => "<p>Text</p>"
);
<?php
// blog_file_2.php
$prop = array(
'title' => "This is file 2!",
'published_date' => "When Time has finally come",
'content' => "<p>Text</p>"
);
<?php
// blog.php
foreach (glob("content/blog/*.php") as $file) {
require_once $file;
$index = str_replace("content/blog/", "", str_replace(".php", "", str_replace("img/", "", $file)));
?>
<div class="content">
<h3><?php echo $prop['title'] ?><span><?php echo $prop['published_date'] ?></span></h3>
<p><?php echo $prop['content'] ?></p>
</div>
<?php
$file = null;
}
?>
I'm not sure if this will help you but maybe it will help others that might find this question as it hits what I was looking for. I was looking to exactly this a few days ago and didn't find much for a simple PHP script to generate a blog. I put this together after searching Stack for different functions (Generate gallery with links from a folder, PHP Pagination, Passing Variable from Another PHP File, Sort Files) and put this together.
Code for the main blog page
\\Blog.php
<?php
$directory = "blog/folder/";
$blogfiles = glob($directory . "*.php");
usort($blogfiles, function($file_1, $file_2)
{
$file_1 = filectime($file_1);
$file_2 = filectime($file_2);
if($file_1 == $file_2)
{
return 0;
}
return $file_2 < $file_1 ? 1 : -1;
});
$post_count = 5;
$total_pages = ceil(count($blogfiles)/$post_count);
$page = $_REQUEST['page']; ///make it dyanamic :: page num
$offset = ($page-1)*$post_count;
$files_filter = array_slice($blogfiles, $offset,$post_count);
foreach ($files_filter as $blogfile) {
ob_start();
include "$blogfile";
ob_end_clean();
echo '<div class="blog-post"><a href="'.$blogfile.'"><img src="'.$BLOG_IMG.'"><h1
class="blog-title">' . $BLOG_TITLE . '</h1></a><br><p class="blog-summary">' .
$SUMMARY . '</p></div><hr>', "\n";
}
if($total_pages > 1){
if($page > 1){
echo '<div class="blog-pagination prev-page"><a href="blog.php?page='.($page-
1).'">Prev Page</a></div>';
}
if($page != $total_pages){
echo '<div class="blog-pagination next-page"><a href="blog.php?page='.
($page+1).'">Next Page</a><div class="blog-pagination">';
}
}
?>
Here is a blog post template
\\post1.php
<?php
$DOC_TITLE = "Document Title for browser tab";
$BLOG_TITLE = "Blog Post Title";
$SUMMARY = "Page summary";
$BLOG_IMG = "/Path/to/blog/image.jpg";
require $_SERVER['DOCUMENT_ROOT'] . '/header.php'; //Pre-made HTML header in the root folder - or just replace with HTML header
?>
\\content
<?php
require $_SERVER['DOCUMENT_ROOT'] . '/footer.php'; //Pre-made HTML footer in the root folder - or just replace with HTML footer
?>

PHP / Codeigniter Nestable List

Simple issue for someone to solve I hope, (I have re written this), I have a table with pages each page record has a parent_id I need to output all of the pages nested correctly under their parent page. I have managed to get the output to show two levels but I am now stuck at this point.
The eventual aim is to use JQuery Nestable to allow my user to re-order the pages and set new parents.
EDIT
Controller:
public function navigation() {
if($this->session->userdata('logged_in')) {
$session_data = $this->session->userdata('logged_in');
$data['auid'] = $session_data['user_user_id'];
$data['userName'] = $session_data['user_fullname'];
$data['gravatar'] = gravatar($session_data['user_email'], 30, FALSE);
$pages = $this->admin_m->getAllTopPages();
foreach ($pages as $p) {
$pid = $p->page_id;
$children = $this->admin_m->getAllChildPages($pid);
if($children) {
$p->children = $children;
}
}
$data['pages'] = $pages;
$data['current'] = 'navigation';
$this->load->view('admin/partials/header_v', $data);
$this->load->view('admin/partials/top-bar_v');
$this->load->view('admin/partials/side-bar_v');
$this->load->view('admin/navigation_v');
$this->load->view('admin/partials/footer_v');
} else {
redirect('admin/login', 'refresh');
}
}
Model:
public function getAllTopPages() {
$query = $this->db->get_where('yell_page', array('page_parent_id'=>'-1'));
return $query->result();
}
public function getAllChildPages($pid) {
$this->db->select('page_id, page_name, page_parent_id');
$this->db->from('yell_page');
$this->db->where('page_parent_id =', $pid);
$this->db->where('page_parent_id !=', '-1');
$query = $this->db->get();
return $query->result();
}
View:
<div class="panel-body">
<div class="dd" id="nestable_list_2">
<ol class="dd-list">
<?php
foreach($pages as $p) {
echo '<li class="dd-item" data-id="'.$p->page_id.'">';
echo '<div class="dd-handle">'.$p->page_name.'</div>';
echo '<ol class="dd-list">';
if(isset($p->children)) {
foreach($p->children as $obj) {
echo '<li class="dd-item" data-id="'.$obj->page_id.'"><div class="dd-handle">'.$obj->page_name.'</div></li>';
}
}
echo '</ol>';
echo '</li>';
}
?>
</ol>
</div>
</div>
I am getting somewhat closer but now the issue is that I only get data on two levels this could potentially be many more.

WordPress sidebar navigation based off of top-level parent page

I'm trying to create a complex sidebar navigation system that remains the same depending on what top-level page you're viewing. For example, say I have this navigation:
Home
About
Our Company
Location
Hours
Our PeopleJim
Dave
Sarah
Kelly
PortfolioLogos
Websites
Contact
Now, if the user was anywhere within the About section, I'd want the sidebar to display:
About
Our Company
Location
Hours
Our PeopleJim
Dave
Sarah
Kelly
That goes for if they're in the main About page, in the Our Company page, or in the Location page. I need the whole navigation visible regardless of depth.
If the user was in a page with no sub-items, such as Contact, the sidebar needs to show:
Home
About
Portfolio
Contact
What's more, the ordering needs to be based on a WordPress Menu (one main menu, each sidebar can't be it's own; that's too complicated for the user). I don't know if that complicates things or not.
In the past, I've managed to get something to display children and sibling pages, but it doesn't display parent pages, and doesn't display in the order that the user defines.
<ul>
<?
global $wp_query;
if( empty($wp_query->post->post_parent) ) {
$parent = $wp_query->post->ID;
}
else {
$parent = $wp_query->post->post_parent;
}
wp_list_pages ("&title_li=&child_of=$parent");
?>
</ul>
If this can be modified to work the way I want it, that'd be great. I'm going to try and figure this out on my own, and will post updates as I make progress.
UPDATE 1: I've made a bit of progress determining what the absolute parent is. I think I'm on the right track.
<?
if ($post->post_parent) {
$ancestors = get_post_ancestors($post->ID);
$root = count($ancestors)-1;
$parent = $ancestors[$root];
} else {
$parent = $post->ID;
}
echo "Current Page: " . $post->ID . "<br />";
echo "Top Level Parent: " . $parent;
?>
UPDATE 2: I can now determine the correct page ID to query for a menu, so I think I'm getting close.
<?
$children = get_pages("child_of=".$post->ID);
if ($post->post_parent) {
$ancestors = get_post_ancestors($post->ID);
$root = count($ancestors)-1;
$parent = $ancestors[$root];
} elseif (count($children) != 0) {
$parent = $post->ID;
} else {
$parent = 0;
}
echo "Current Page: " . $post->ID . "<br />";
echo "Top Level Parent: " . $parent;
?>
UPDATE 3: I'm nearly there! The only problem is this uses the page's order from the editor, not from the menu. Is it possible to edit this to work with a menu instead?
<aside>
<?
$children = get_pages("child_of=".$post->ID);
if ($post->post_parent) {
$ancestors = get_post_ancestors($post->ID);
$root = count($ancestors)-1;
$parent = $ancestors[$root];
$sidebarDepth = 0;
$postParentID = get_post($parent);
$title = $postParentID->post_title;
} elseif (count($children) != 0) {
$parent = $post->ID;
$sidebarDepth = 0;
$postParentID = get_post($parent);
$title = $postParentID->post_title;
} else {
$parent = 0;
$sidebarDepth = 1;
$frontPageID = get_option("page_on_front");
$exclude = $frontPageID;
$postParentID = get_post($frontPageID);
$title = $postParentID->post_title;
}
?>
<header>
<h6><? echo $title ?> »</h6>
</header>
<section>
<nav>
<?
echo "<ul>";
wp_list_pages("child_of=" . $parent . "&depth=" . $sidebarDepth . "&exclude=" . $exclude . "&title_li=&");
echo "</ul>";
?>
</nav>
</section>
</aside>
Figured it out! I modified the code from this answer to add a start_in option to wp_nav_menu, and modified my code from there. Now this works exactly as I wanted it.
In functions.php:
// add start_in argument to navigation
add_filter("wp_nav_menu_objects",'my_wp_nav_menu_objects_start_in',10,2);
function my_wp_nav_menu_objects_start_in( $sorted_menu_items, $args ) {
if (isset($args->start_in) && $args->start_in != 0) {
$menu_item_parents = array();
foreach ($sorted_menu_items as $key => $item) {
if ($item->object_id == (int)$args->start_in) $menu_item_parents[] = $item->ID;
if (in_array($item->menu_item_parent, $menu_item_parents)) {
$menu_item_parents[] = $item->ID;
} else {
unset($sorted_menu_items[$key]);
}
}
return $sorted_menu_items;
} else {
return $sorted_menu_items;
}
}
In page.php (or whatever template you want):
<aside>
<?
if ($post->post_parent) {
$ancestors = get_post_ancestors($post->ID);
$root = count($ancestors)-1;
$parent = $ancestors[$root];
} elseif (count(get_pages("child_of=".$post->ID)) != 0) {
$parent = $post->ID;
} else {
$parent = get_option("page_on_front");
$sidebarDepth = 1;
$exclude = $parent;
}
if ($post->post_parent || count(get_pages("child_of=".$post->ID)) != 0) {
$sidebarDepth = 0;
$start_in = $parent;
$depth = 0;
} else {
$depth = 1;
$start_in = 0;
}
$parentID = get_post($parent);
$parentTitle = $parentID->post_title;
$parentURL = get_permalink($parentID);
?>
<header>
<h6><? echo $parentTitle ?> »</h6>
</header>
<section>
<nav>
<?
wp_nav_menu(
array(
"container" => false,
"depth" => $depth,
"items_wrap" => '<ul>%3$s</ul>',
"start_in" => $start_in,
"theme_location" => "first"
)
);
?>
</nav>
</section>
</aside>

last.fm api - random / shuffle foreach loop

I am currently working with the lat.fm api to develop an app.
I have a function which runs to pull in the weekly track listing from a last.fm group.
The aim is to pull in the album artwork and to make a "gridview" template.
The below code does this:
public function getWeeklyTrackChartGrid($methodVars) {
// Check for required variables
if ( !empty($methodVars['group']) ) {
$vars = array(
'method' => 'group.getweeklytrackchart',
'api_key' => $this->auth->apiKey
);
$vars = array_merge($vars, $methodVars);
if ( $call = $this->apiGetCall($vars) ) {
$i = 0;
//shuffle($call->weeklytrackchart->track);
$loopN = $call->weeklytrackchart->track;
foreach ($loopN as $track ) {
require 'config.php';
//if(++$i > $userLimit*2) break;
$albumArtS = $tracks['album']['image']['small'] = (string) $track->image[0];
$albumArtM = $tracks['album']['image']['small'] = (string) $track->image[1];
$albumArtL = $tracks['album']['image']['small'] = (string) $track->image[2];
$playCounts = $tracks[$i]['playcount'] = (string) $track->playcount;
?>
<?php if ($playCounts > 1) { ?>
<?php if ($albumArtL) { ?>
<img src="<?php echo $albumArtL; ?>" />
<?php } ?>
<?php } else { ?>
<?php if ($albumArtM) { ?>
<img src="<?php echo $albumArtM; ?>" />
<?php } ?>
<?php } ?>
<?php if ($albumArtwork == "yes") { ?>
<?php if ($albumArt) { ?>
<?php } }?>
<?php $i++;
}
return $tracks;
}
else {
return FALSE;
}
}
else {
// Give a 91 error if incorrect variables are used
$this->handleError(91, 'You must include a group variable in the call for this method');
return FALSE;
}
}
I would like to use the php function shuffle on the foreach loop to randomise the tracks, rather than pull them in, in the order last.fm gives them you.
As you can see i havent commented the shuffle function out above, as when i add this i get the following warning:
Warning: shuffle() expects parameter 1 to be array, object given in
Any ideas on what could be the problem?
Cheers,
Dan
$loopN = (array) $call->weeklytrackchart->track;
shuffle($loopN);

Categories