Let's say I want to use the $wpdb class to retrieve image locations from the database so I can then create a gallery of images. I have this code, but when I press 'next', the link doesn't seem to go anywhere. Am I missing something?
<?php
global $wpdb;
$wpdb->show_errors();
$offset = 0;
if( isset($_GET['page']) && !empty($_GET['page']) ){
$offset = ($_GET['page']-1) * 10; // (page 2 - 1)*10 = offset of 10
}
$pics = $wpdb->get_col("SELECT pic_thumb_url FROM wp3_bp_album
WHERE owner_type = 'user' ORDER BY title DESC
LIMIT 10 OFFSET $offset"
);
//LIMIT shows 10 results per page
//OFFSET will 'skip' this number off results. On page 1 the offset is 0 on page 2 it is 10 (if 10 results per page)
foreach($pics as $pic) :
echo '' . '';
endforeach;
/*
pagination
*/
?>
previous
next
Can I implement pagination with this?
You can't use the built-in pagination, but to use pagination use an OFFSET and a LIMIT in your query. So, make your own pagination:
<?php
$offset = 0;
if(isset($_GET['page']) && !empty($_GET['page']) {
$offset = ($_GET['page']-1) * 10; // (page 2 - 1)*10 = offset of 10
}
$wpdb->get_col("SELECT pic_thumb_url FROM wp3_bp_album
WHERE owner_type = 'user' ORDER BY title DESC
LIMIT 10 OFFSET $offset"
);
//LIMIT shows 10 results per page
//OFFSET will 'skip' this number off results. On page 1 the offset is 0 on page 2 it is 10 (if 10 results per page)
/*
pagination
*/
?>
previous
next
Not flawless, it doesn't check if you are on the first or last page but at least the first check you have to build yourself.
Related
I have a mongo collection which stores orders for a shopping site. Therefore, it starts from 0 and goes up 1 by 1. I want to search for documents, 10 each time, but starting from the max order number all the way down to 0.
In order to do this, I had the idea of getting the max order number and then simply query for the order number from max-10 to max.
Is there a better way to do this? And also, how do I get the maximum order number?
You can use aggregation query to achieve this
var limit = 10;
var offset = page_no > 1 ? (page_no-1) * limit : 0;
Orders.aggregate([
{
$sort:{
'order_no':-1
}
},{
$skip:offset
},{
$limit:limit
}
])
Here order_no is the Number type in your schema as you mentioned & offset will be set based on the page_no you increase from 1-N
Is there a way to limit the amount of records returned via SuiteScript? I use the following method, but the search still gets all results. I am breaking out of the iteration of the results if I've hit the max I'd like to return. I can't find anything in the documentation.
In the UI it looks like one can limit the returned results, even though I haven't had much luck with it. (Maybe because I'm joining...)
var accountSearch = search.create({
type: search.Type.CUSTOMER,
columns: searchColumns,
filters: searchFilters
});
var searchResultsPagedData = accountSearch.runPaged({
'pageSize': 1000
});
var max = 9;
for (var pageIndex = 0; pageIndex < searchResultsPagedData.pageRanges.length; pageIndex++) {
var pageRange = searchResultsPagedData.pageRanges[pageIndex];
if (pageRange.index >= max)
break;
var searchPage = searchResultsPagedData.fetch({ index: pageRange.index });
// Iterate over the list of results on the current page
searchPage.data.forEach(function (result) {
}
}
Use getRange instead of each to iterate over your results. getRange lets you specify a start and end index to grab a specific slice of the results.
Why not just set the page size to the max number of results you want and only iterate over the first page (page 0)? Or if you're looking for more than 1000 results you could limit the number of pages by setting pageIndex < max; instead of pageIndex < searchResultsPagedData.pageRanges.length;
Another approach: from the comments it seems one of the issues you're having is running into the execution limit, so you could load the N/runtime module and use Script.getRemainingUsage() before each fetch to ensure you have enough governance units left - and break or return if you don't.
I have a query to get photos according to values in a pivot table, that stores the relation of "pics" and "tags":
#photos
$q = PicTag::select(DB::raw('distinct(pics.id)'),
'pics.url',
'pics.titel',
'pics.hits',
'pics.created_at',
'users.username',
'users.displayname')
->leftJoin('pics', 'pics.id', '=', 'pic_tag.pic_id')
->leftJoin('users','users.id','=','pics.user_id')
->whereIn('pic_tag.tag_id', $tagids);
if($cat)
$q->where('typ',$cat);
if($year)
$q->where('jahrprod',$year);
$pics = $q->orderBy('pics.id','desc')
->paginate(30);
The problem is, when for a certain photo multiple (same) tags are stored like "Tag", "tag" and "tAG". Then the same photo would be shown 3 times in my gallery. That is why I use the distinct in the query.
Then the gallery is ok, but $pics->total() does not show "87 photos" but for example "90 photos", because the distinct is not used in the pagination. In laravel 4, I used groupBy('pics.id'), but this did not seem to be the fastest query and with laravel 5 it gives me a total() count result of 1.
How could I get the right total() value?
I know it's an old subject but it could help some other people.
I faced the same problem and the only good solution (low memory cost) I found was to do the request in two times:
$ids = DB::table('foo')
->selectRaw('foo.id')
->distinct()
->pluck('foo.id');
$results = $query = DB::table('foo')
->selectRaw('foo.id')
->whereIn('foo.id', $ids)
->paginate();
I tried this with 100k results, and had no problem at all.
Laravel has issue in paginate of complex queries. so you should handle them manually . In laravel 5 I did it in 2 steps :
Step 1: repository method :
public function getByPage($page = 1, $limit = 10 , $provinceId , $cityId , $expertiseId)
{
$array = ['users.deleted' => false];
$array["users.approved"] = true;
$array["users.is_confirmed"] = true;
if($provinceId)
$array["users.province_FK"] = $provinceId;
if($cityId)
$array["users.city_FK"] = $cityId;
if($expertiseId)
$array["ONJNCT_USERS_EXPERTISE.expertise_FK"] = $expertiseId;
$results = new \stdClass();
$results->page = $page;
$results->limit = $limit;
$results->totalItems = 0;
$results->items = array();
$users= DB::table('users')
->distinct()
->select('users.*','ONDEGREES.name as drgree_name')
->join('ONJNCT_USERS_EXPERTISE', 'users.id', '=', 'ONJNCT_USERS_EXPERTISE.user_FK')
->join('ONDEGREES', 'users.degree_FK', '=', 'ONDEGREES.id')
->where($array)
->skip($limit * ($page - 1))->take($limit)->get();
//$users = $usersQuery>skip($limit * ($page - 1))->take($limit)->get();
$usersCount= DB::table('users')
->select('users.*','ONDEGREES.name as drgree_name')
->join('ONJNCT_USERS_EXPERTISE', 'users.id', '=', 'ONJNCT_USERS_EXPERTISE.user_FK')
->join('ONDEGREES', 'users.degree_FK', '=', 'ONDEGREES.id')
->where($array)
->count(DB::raw('DISTINCT users.id'));
$results->totalItems = $usersCount;
$results->items = $users;
return $results;
}
Step 2:
In my Search Controller :
function search($provinceId , $cityId , $expertiseId){
$page = Input::get('page', 1);
$data = $this->userService->getByPage($page, 1 , $provinceId ,$cityId , $expertiseId);
$users = new LengthAwarePaginator($data->items, $data->totalItems, 1 , Paginator::resolveCurrentPage(),['path' => Paginator::resolveCurrentPath()]);
return View::make('guest.search.searchResult')->with('users' ,$users);
}
It worked for me well!
Im working on a site and build a custom post type. Within this custom post type I added a meta field where you can select a number from 1 trough 16. These numbers are corresponding with specific positions on my homepage. But now my issue appears. How can I query these post within these specific positions without repeating myself.
So for example...
here a post with meta value 1
here a post with meta value 2
here a post with meta value 3
ect..
Hope someone can help me a little
There are a few ways to tackle this depending on how complex your layout logic is. If you basically just need to loop through the 16 posts in order, you can use the orderby parameter in your query to sort the posts:
$args = array(
'post-type' => 'YOUR_POST_TYPE',
'orderby' => 'meta_value_num',
'meta_key' => 'YOUR_METAFIELD_SLUG'
);
$customposts = new WP_Query($args);
while( $customposts->have_posts() ): $customposts->the_post();
// loop goes here
If you need something more complex, you might be able to avoid repeating queries by querying once and then using conditionals to check the meta value. For example, with the query from the above example...
// Position 1 on your page
<div class="position-1">
<?php
while( $customposts->have_posts() ): $customposts->the_post();
$meta_value = get_post_meta(get_the_ID(), 'YOUR_METAFIELD_SLUG', true);
// Only print something here if the meta value is what we want
if( $meta_value == 1 ) :
the_title();
the_content();
endif;
// Reset the loop
$customposts->rewind_posts(); ?>
</div>
// Position 2 on your page
<div class="position-2">
<?php
while( $customposts->have_posts() ): $customposts->the_post();
$meta_value = get_post_meta(get_the_ID(), 'YOUR_METAFIELD_SLUG', true);
if( $meta_value == 2 ) :
the_title();
the_content();
endif;
// Reset the loop again
$customposts->rewind_posts(); ?>
....and so on.
You may find these helpful:
http://codex.wordpress.org/Function_Reference/get_post_meta
http://codex.wordpress.org/Class_Reference/WP_Query
I am using the Google Site Search XML API and want to do pagination. I know that the count in is considered inaccurate, but how does Google implement their paging on the demo site at http://www.google.com/sitesearch/? It seems to at least be accurately knowing if there are more than 35 results to break into the 8 pages.
This is an old question but I've just implemented this myself so thought I should share.
Not sure what language you are using, but here's how I did it in PHP ($xml is, of course, the full XML result retrieved using curl or file_get_contents or whatever):
$results_per_page = 8;
$pages = ceil($xml->RES->M/$results_per_page);
if ($pages > 1) {
for ($i = 0; $i < $pages; $i++) {
$class = '';
if ( ($i) * $results_per_page == $_GET['s']) {
$class = 'current-page';
}
echo '<strong>' . $i + 1 . '</strong>
}
}
Note that $results_per_page should match the value of num in the XML url that's fetched