MilenKo

date
Show pages published by a time interval (day, week, month etc.) without a date field

11 posts in this topic

Hello all.

I am trying to find a way to have a query with all pages that were published on a specific date (today for example). I read a few posts where people had a specific date field and were limitting the results by that, however is there a way to filter results without a specific date field? As far as I am able to publish the timestamp using $page->created logically I should be able to filter by the result of it? What is the best way to accomplish a filter for a day, week, month etc.?

Share this post


Link to post
Share on other sites
27 minutes ago, MilenKo said:

I read a few posts where people had a specific date field and were limitting the results by that, however is there a way to filter results without a specific date field?

It's the same, just replace $page->custom_date_field with $page->created or $page->published

1 person likes this

Share this post


Link to post
Share on other sites

@Robin S Thanks for the advise. I thought so, but I am getting an error on my code:

<ul class="cs-recipes"> 

<?php
$start = strtotime( date('Y-m-d') . " 00:00:00");
$end = strtotime( date('Y-m-d') . " 23:59:59");

if($pages->get('/recipes/')->children) {
$items = $pages->find("template=recipes-inner, $page->published>$start, $page->published<$end, sort=date, limit=9"); 
foreach($items as $rotd) { ?>

	<li class="cs-recipe">
		<div class="cs-recipe-image">
			<div class="cs-recipe-details-button">
				<a href="recipe_single_layout_1.html">Details</a>
			</div>
			<img src="<?=$rotd->recipe_image->url?>" alt="<?=$rotd->recipe_image->description?>">
		</div>
		<div class="cs-recipe-meta">
			<span><i class="fa fa-hourglass-half"></i> <?=$rotd->recipe_cooktime?></span>
			<span><i class="fa fa-cutlery"></i> <?=$rotd->recipe_servings?></span>
		</div>
		<h3>	
			<a href="<?=$rotd->httpUrl?>"><?=$rotd->title?></a>
		</h3>
	</li>  
<? } ?>
	
</ul>

Any ideas where did I messed it up this time? :)

Share this post


Link to post
Share on other sites

From the documentation for selectors

<?php
// single condition
// pages published today, sorted new->old
$recentItems = $pages->find("template=product, my_date_field>=today, sort=-my_date_field");

// multiple conditions with AND operator
// pages published this year until today
$thisYear = date('Y-01-01'); // 2017-01-01 or 2011-01-01 etc
$recentItems = $pages->find("template=product, published>=$thisYear, published<=today");

 

Share this post


Link to post
Share on other sites

You shouldn't put $page-> in there, just use the name of the field. And your sort field must be an existing field.

$items = $pages->find("template=recipes-inner, published>=$start, published<=$end, sort=-published, limit=9"); 

Also you don't have to manually build the boundaries of today, you can just use today

$items = $pages->find("template=recipes-inner, published>=today, sort=-published, limit=9"); 

In fact, you can use any valid PHP date that you can use with DateTime constructor. http://php.net/manual/en/class.datetime.php

published>=today
published>=1365436783
published>=2013-04-08
published>=4/8/2013
published>=8.4.2013
published>="April 8, 2013"
4 people like this

Share this post


Link to post
Share on other sites

OK, that seemed to work and shows some results.

Now if I want to show dates 2 or 3 days ago, would it be correct to have $start = strtotime( date(('Y-m-d')-2) . " 00:00:00"); or there is a better/correct way of doing it? 

Also let's say I need to show the pages for last 7 days?

Share this post


Link to post
Share on other sites

You can use DateTime class. http://php.net/manual/en/class.datetime.php

$today = new \DateTime();
$aFewDaysAgo = $today->modify('-2 days');
$lastYear = $today->modify('-1 year');

$latestPages = $pages->find("published>=$aFewDaysAgo");
$pagesSinceLastYear = $pages->find("published>=$lastYear");

 

3 people like this

Share this post


Link to post
Share on other sites

Ok, so it looks like DateTime class would do the trick if I ever want to present some pages in a specific timeframe.

Thanks again @abdus & @Robin S

Share this post


Link to post
Share on other sites

@abdus I tested your code using DateTime class, but am getting a server error 500:

        $today = new DateTime();
        $aFewDaysAgo = $today->modify('-2 days');
        if($pages->get('/recipes/')->children) { 
        $latest = $pages->find("template=recipes-inner, published>=$aFewDaysAgo, sort=-published, limit=9");

and the error in exceptions.txt is: Object of class DateTime could not be converted to string.

Share this post


Link to post
Share on other sites
4 hours ago, MilenKo said:

$today = new DateTime();

Without a backslash class names resolve to current namespace (ProcessWire), and since DateTime class is in global namespace, you should put \ before DateTime.

$today = new \DateTime();

Also, I've realized that I am getting the same error, but $pages->find() is still returning a result (because when DateTime object is converted to string it turns into an empty string '', and the selector becomes "published>'' ", which returns all pages). You can fix the error using:

$today = new \DateTime();

// use UNIX timestamps
$aFewDaysAgo = $today->modify('-2 days')->getTimestamp();
$lastYear = $today->modify('-1 year')->getTimestamp();

// or convert to ISO format
// $aFewDaysAgo = $today->modify('-2 days')->format('c');
// $lastYear = $today->modify('-1 year')->format('c');

$latestPages = $pages->find("published>=$aFewDaysAgo");
$pagesSinceLastYear = $pages->find("published>=$lastYear");
 

 

5 people like this

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!


Register a new account

Sign in

Already have an account? Sign in here.


Sign In Now

  • Recently Browsing   0 members

    No registered users viewing this page.

  • Similar Content

    • By Robin S
      I'd hate to know how much accumulated time I have spent and how much eye-strain I have experienced over the last couple of years, hunting through the 675 icons in the "all icons" view for the one I want. Today I finally got around to doing something about it.
      IconsFilter
      Allows the "all icons" view in InputfieldIcon to be filtered by name.
      Usage
      Install the IconsFilter module.
      When viewing "all icons" in InputfieldIcon (Advanced tab of field/template settings) you can filter the icons by name using the filter input at top right.
       

       
      https://github.com/Toutouwai/IconsFilter
       
      @tpr, something that could be merged into AdminOnSteroids?
    • By cosmicsafari
      Hi all,
      I am working on a module which creates templates, fields & pages upon install.
      I have ran into an issue where I have a numerous fields which I would like to override their labels depending on the template they are used in.
      Is it possible to do this dynamically via API at the point where I am creating the field group and template using the API.
      The following is the code which I am using at the moment.
      foreach($templatesArray as $name => $cTemplate) { if(array_key_exists('fieldGroup',$cTemplate)) { $fg = new Fieldgroup(); $fg->name = $name . '-fg'; foreach ($cTemplate['fieldGroup'] as $field) { //possibly at this point? $fg->add($this->fields->get($field)); } $fg->save(); } $t = new Template(); $t->name = $name; $t->fieldgroup = $fg; $t->noChildren = 1; $t->setIcon($cTemplate['icon']); $t->save(); } Is this even possible?
    • By Cody Connor
      I am currently working on a website in process wire.  I created an image field and added svg as a valid file extension and could upload a png image and a jpg image but when I try to upload a svg image it is stuck loading at 100%.  I figured out that the image field does not take the extension svg even if I add it as an extension. and I was wondering if their is any way to upload a svg image to an image field in processwire?
      I am working with processwire version 3.0.61

    • By Martin Muzatko
      Hello!
      I'm trying to use the data I create in Processwire as much as possible.
      So for a form, I try to use the fields description, name and also its built-in validation rules I defined in ProcessWire on the front-end. (minlength, ranges, patterns, etc)
      I already looked into this tutorial, but it is using external resources to validate the form.
      Since ProcessWire does all the heavy lifting, when processing data, I don't have to sanitize anything - ___processInput should do the job just fine.
      However, it is not actually working correctly. 
      $fields = $templates->get('user')->fields; $submission = $input->post; foreach ($submission as $key => $value) { $field = $fields->{$key}; if ($field instanceof Field) { $field = $field->getInputfield($user); $field->___processInput(new WireInputData([$key => $value])); var_dump($field->getErrors(true)); // retrieve validation error } } This works for some constraints, but the values are not correctly validated.
      Example: 

      All the fields are required and zip is an integer field.
      Yet, I get no validation error for zip, although it was entered as a string, and not an integer. Funny enough: if I provide a number outside the range, I get "Specified value 2 removed because it is out of bounds (min=1000, max=99999)".
      firstname will not return any error for being a required field.
      From what I have looked through the source code, there is no check for "required". Some fields only validate on setAttribute. Am I missing anything or am I doomed to build my own validation process?
      Thank you in advance!
      Best,
      Martin
    • By neonwired
      I'm trying to call an ajax function for an inputfield using Soma's method below by intercepting the call in the module init function but for some reason $this->input is always NULL.
       
      public function init() { parent::init(); $dir = dirname(__FILE__); require_once("$dir/Location.php"); require_once("$dir/LocationArray.php"); $this->wire('config')->js('InputfieldLocations', array( 'url' => "/admin/locationmodule/ajax" )); if ($this->config->ajax && $this->input->ajaxfunction == 'getcities') { header('Content-Type: application/json'); echo $this->get_cities(); exit; } }