Blog
2 posts by 2 authors in: Forums > CMS Builder
Last Post: September 25, 2014 (RSS)
Hi Guys,
Is there a simple way of doing this? I'm ending up with millions of lines of code.
I have a section "blog" with the following fields;
Title (text field)
Category (multi-select list)
Date (date field)
Content (wysiwyg)
I want to publish a blog page, that groups records by month, or by category. It displays links to all months and all categories, and displays the currently selected group or defaults to current month if nothing selected. ie.
<div id="navigation">
<nav id="months">
<!-- group articles by month" -->
<a>Month</a>
<a>Month</a>
<a>Month</a>
</nav>
<nav id="category">
<!-- group articles by month" -->
<a>Category</a>
<a>Category</a>
<a>Category</a>
</nav>
</div>
<!-- Display the selected month or category -->
<h1>Selected Group</h1><!-- list articles within current group" -->
<div>
<h2>Article 1</h2>
<p>This is the blog content</p>
</div>
<div>
<h2>Article 2</h2>
<p>This is the blog content</p>
</div>
<div>
<h2>Article 3</h2>
<p>This is the blog content</p>
</div>
I'm currently using the code below to group dates - but think there would be a better option?
<?php
// get list of unique months and years with articles
$query = "SELECT DATE_FORMAT(date, '%M %Y') as dateAndYear, YEAR(date) as year, MONTH(date) as month FROM cms_blog GROUP BY dateAndYear ORDER BY date DESC";
$result = mysql_query($query) or die("MySQL Error: ". htmlspecialchars(mysql_error()) . "\n");
while ($record = mysql_fetch_assoc($result)):
?>
Tim (toledoh.com.au)
Hey Tim,
I'd use the array_groupBy function to filter the list instead:
$firstRec = true;
$searchMonth = false;
// load records from 'blog'
list($blogs, $blogsMeta) = getRecords(array(
'tableName' => 'blog',
'loadUploads' => true,
'allowSearch' => false,
'orderBy' => '`date` DESC'
));
//Add the month the record was created to records.
if($searchMonth){
foreach($blogs as $key => $blog){
$blogs[$key]['month'] = $blogMonth = date('m', $blog['date:unixtime']);
$blogs[$key]['month_name'] = $blogMonth = date('F', $blog['date:unixtime']);
}
}
$groupBy = ($searchMonth)? 'month' : 'category' ;
//Group the blogs together
$blogs = array_groupBy($blogs, $groupBy, true);
?>
<?php foreach($blogs as $group): ?>
<?php foreach($group as $blog): ?>
<?php if($firstRec): ?>
<h1><?php echo ($searchMonth)? $blog['month_name'] : $blog['category:label']; ?></h1>
<?php $firstRec = false; ?>
<?php endif; ?>
<h3><?php echo $blog['title']; ?></h3>
<?php endforeach; ?>
<?php $firstRec = true; ?>
<?php endforeach; ?>
If you change the $sarchMonth variable to true or false at the top of the page, you shouldfind that it switches between grouping the articles by category or month.
The foreach loop will add variables for which month the article was published if the filter by month system is used.
This is just example code, so you might have to make a few changes to get it working.
Cheers,
Greg
PHP Programmer - interactivetools.com