I need help for this piece of code:
<?php
global $wpdb;
$id = get_the_ID();
$querystring = "SELECT * FROM wp_candle WHERE id = $id";
$results = $wpdb->get_results( $querystring ,OBJECT);
foreach($results as $result)
{
echo
'<div class="kerzenbox clearfix">
<article class="post boxrechts" id="">
<h2> "'.$result->contactName.'" </h2>
<p> "'.$result->worte.'" </p>
<img src="myImagePath" width="50" height="70"/>
</article>
</div>';
}
?>
I need the post per page option implemented but I don't know how. Without post per page for this specific query the page looks really weird.
<?php
global $wpdb;
$rows_per_page = 8;
$current = (intval(get_query_var('paged'))) ? intval(get_query_var('paged')) : 1;
$rows = $wpdb->get_results("SELECT * FROM wp_candle WHERE id = $id ");
global $wp_rewrite;
$pagination_args = array(
'base' => #add_query_arg('paged','%#%'),
'format' => '',
'total' => ceil(sizeof($rows)/$rows_per_page),
'current' => $current,
'show_all' => false,
'type' => 'plain',
);
if( $wp_rewrite->using_permalinks() )
{
$pagination_args['base'] = user_trailingslashit( trailingslashit( remove_query_arg('s',get_pagenum_link(1) ) ) . 'page/%#%/', 'paged');
}
if( !empty($wp_query->query_vars['s']) )
{
$pagination_args['add_args'] = array('s'=>get_query_var('s'));
}
echo paginate_links($pagination_args);
?>
Related
how to get the current category name of the page inside functions.php?
this is for adding a load more functionality based on a category per page.
this is what my current code looks like
add_filter('query_vars', 'registering_custom_query_var');
function registering_custom_query_var($query_vars)
{
$query_vars[] = 'id'; // Change it to your desired name
return $query_vars;
}
function more_post_ajax() {
global $wp_query;
$ppp = (isset($_POST["ppp"])) ? $_POST["ppp"] : 1;
$page = (isset($_POST['pageNumber'])) ? $_POST['pageNumber'] : 0;
$category = get_category(get_query_var('cat'));
header("Content-Type: text/html");
$args = array(
'post_type' => 'post',
'posts_per_page' => $ppp,
'category_name' => $category->name,
'paged' => $page,
);
$loop = new WP_Query($args);
$out = '';
if ($loop->have_posts()) : while ($loop->have_posts()) : $loop->the_post();
$out .= '<div class="article_card"><div class="article_card__thumbnail">' . get_the_post_thumbnail() . '</div><div class="article_card__content"><h3>' . get_the_title() . '</h3><p class="body-small">' . wp_trim_words( get_the_excerpt(), 60 ) . '</p><a a href="' . get_the_permalink() . '"> Learn more →</a></div></div>';
endwhile;
endif;
wp_reset_postdata();
die($out);
}
add_action('wp_ajax_nopriv_more_post_ajax', 'more_post_ajax');
add_action('wp_ajax_more_post_ajax', 'more_post_ajax');
Are you looking for something like this?
<?php
$post = get_post();
if ( $post ) {
$categories = get_the_category( $post->ID );
var_dump( $categories );
}
I'm working on a custom post type archive and I want to add an A-Z filtering menu.
I managed to pretty much get it working following this thread (Create alphabetical Pagination in wordpress) but I dont understand how my initial page (/exposants) can show all the results.
<div class="exposant__filter" id="exposants">
<?php _e('Tout', 'festival'); ?>
<?php
$posts = get_posts(array(
'numberposts' => -1,
'post_type' => 'exposant',
'orderby' => 'title',
'order' => 'ASC',
));
$firstLetters = array();
foreach($posts as $post) {
$title = $post->post_title;
$startingLetter = substr($title, 0, 1);
$dupeFirstLetters[] = $startingLetter;
$firstLetters = array_unique($dupeFirstLetters);
sort($firstLetters);
}
foreach($firstLetters as $letter) {
echo "$letter";
}
if(!empty($_GET['lettre'])) {
$letter = $_GET['lettre'];
}
else {
$letter = $firstLetters[0];
} ?>
</div>
<?php
$exposantsArchive = new WP_Query(array(
'posts_per_page' => -1,
'post_type' => 'exposant',
'orderby' => 'title',
'order' => 'ASC',
)); ?>
<div class="row row--2col u-m-top--8">
<?php
while($exposantsArchive->have_posts()) {
$exposantsArchive->the_post();
$first_letter = strtoupper(substr(apply_filters('the_title',$post->post_title),0,1));
$logo = get_field('logo');
if($first_letter == strtoupper($letter)) { ?>
<div class="exposant__thumb col--padding-right">
<div class="exposant__logo">
<img src="<?php echo $logo['url'] ?>" alt="<?php echo $logo['alt'] ?>">
</div>
<div class="exposant__thumb-content">
<h2 class="heading--as-h4 heading--no-margin"><?php the_title(); ?></h2>
<?php
$related = get_field('pieces_liees');
if($related) {
echo '<p class="exposant__categories">';
foreach ($related as $k=>$category) {
if($k) echo '/';
?>
<?php echo get_the_title($category); ?>
<?php }
}
?></p>
<p class="exposant-thumb__excerpt"><?php echo wp_trim_words( get_field('description'), 16, '...' ); ?></p>
<?php _e('Plus de détails', 'festival'); ?>
</div>
</div>
<?php
}
}
wp_reset_postdata() ?>
</div>
I imagine I'd have to replace the else {$letter = $firstLetters[0];} but I have no idea with what.
Thanks in advance for your precious support.
EDIT!
Here is the solution that ended up working flawlessly!
So in functions.php
<?php
add_filter( 'posts_where', 'tomtom_posts_where', 10, 2 );
function tomtom_posts_where( $args, $wp_query_obj )
{
global $wpdb;
$starts_with = $wp_query_obj->get( 'starts_with' );
if ( $starts_with ) {
$args .= ' AND ' . $wpdb->posts . '.post_title LIKE \'' . esc_sql( $wpdb->esc_like( $starts_with ) ) . '%\'';
}
return $args;
}
And here is the page
<?php
/**
* Outputs an alphabetic paginator.
*
* #return void
*/
function tomtom_output_alphabetic_paginator() {
$posts = get_posts( array(
'numberposts' => -1,
'post_type' => 'exposant',
'orderby' => 'title',
'order' => 'ASC',
) );
$firstLetters = array();
foreach ( $posts as $post ) {
$title = $post->post_title;
$startingLetter = substr( $title, 0, 1 );
$dupeFirstLetters[] = $startingLetter;
}
$firstLetters = array_unique( $dupeFirstLetters );
sort( $firstLetters );
echo "" . __('Tout', 'festival') . "";
foreach ( $firstLetters as $letter ) {
echo "{$letter}";
}
}
/**
* Gets an array of exposant custom post types.
*
* #return array
*/
function tomtom_get_exposants() {
$args = array(
'posts_per_page' => -1,
'post_type' => 'exposant',
'orderby' => 'title',
'order' => 'ASC',
);
if ( !empty( $_GET['lettre'] ) ) {
$args['starts_with'] = $_GET['lettre'];
}
$wp_query = new WP_Query( $args );
return $wp_query->get_posts();
}
/**
* Outputs links related to exposant custom post type object.
*
* #return void
*/
function tomtom_output_related( $related ) {
foreach ( $related as $k => $category ) {
if ( $k ) {
echo ' / ';
}
echo "" . get_the_title( $category ) . "";
}
}
?>
<div class="exposant__filter" id="exposants">
<?php tomtom_output_alphabetic_paginator(); ?>
</div>
<?php $exposantsArchive = tomtom_get_exposants(); ?>
<div class="row row--2col u-m-top--8">
<?php foreach ( $exposantsArchive as $exposant ): ?>
<?php $logo = get_field('logo', $exposant->ID); ?>
<?php $related = get_field('pieces_liees', $exposant->ID); ?>
<?php $description = get_field('description', $exposant->ID); ?>
<div class="exposant__thumb col--padding-right">
<div class="exposant__logo">
<img src="<?php echo $logo['url'] ?>" alt="<?php echo $logo['alt'] ?>">
</div>
<div class="exposant__thumb-content">
<h2 class="heading--as-h4 heading--no-margin"><?php echo $exposant->post_title; ?></h2>
<?php if ( $related ): ?>
<p class="exposant__categories">
<?php tomtom_output_related( $related ); ?>
</p>
<?php endif; ?>
<p class="exposant-thumb__excerpt"><?php echo wp_trim_words( $description, 20, '...' ); ?></p>
<?php _e( 'Plus de détails', 'festival' ); ?>
</div>
</div>
<?php endforeach; ?>
</div>
If I understand the problem correctly, here's an slightly optimized version of your code. I've taken the liberty of decoupling your php and your html as much as I could for clarity.
It's not tested, it may take a few tweaks, but overall I hope this does the trick!
In your functions.php file, add this, which will allow you to filter your database queries by first letter:
add_filter( 'posts_where', 'tomtom_posts_where', 10, 2 );
function tomtom_posts_where( $args, $wp_query_obj )
{
global $wpdb;
$starts_with = $wp_query->get( 'starts_with' )
if ( $starts_with ) {
$args .= ' AND ' . $wpdb->posts . '.post_title LIKE \'' . esc_sql( $wpdb->esc_like( $starts_with ) ) . '%\'';
}
return $where;
}
Then:
<?php
/**
* Outputs an alphabetic paginator.
*
* #return void
*/
function tomtom_output_alphabetic_paginator() {
$posts = get_posts( array(
'numberposts' => -1,
'post_type' => 'exposant',
'orderby' => 'title',
'order' => 'ASC',
) );
$firstLetters = array();
foreach ( $posts as $post ) {
$title = $post->post_title;
$startingLetter = substr( $title, 0, 1 );
$dupeFirstLetters[] = $startingLetter;
}
$firstLetters = array_unique( $dupeFirstLetters );
sort( $firstLetters );
echo "" . __('Tout', 'festival') . "";
foreach ( $firstLetters as $letter ) {
echo "{$letter}";
}
}
/**
* Gets an array of exposant custom post types.
*
* #return array
*/
function tomtom_get_exposants() {
$args = array(
'posts_per_page' => -1,
'post_type' => 'exposant',
'orderby' => 'title',
'order' => 'ASC',
);
if ( ! empty( $_GET['lettre'] ) ) {
$args['starts_with'] = $_GET['lettre'];
}
return new WP_Query( $args );
}
/**
* Adds fields to an exposant custom post type object.
*
* #param WP_Post $exposant Exposant custom post type.
* #return void
*/
function tomtom_hydrate_exposant( &$exposant ) {
$exposant->logo = get_field( 'logo', $exposant->ID );
$exposant->related = get_field( 'pieces_liees', $exposant->ID );
$exposant->description = get_field( 'description', $exposant->ID );
}
/**
* Outputs links related to exposant custom post type object.
*
* #return void
*/
function tomtom_output_related( $exposant ) {
if ( ! isset( $exposant->related ) ) {
tomtom_hydrate_exposant( $exposant );
}
foreach ( $exposant->related as $k => $category ) {
if ( $k ) {
echo '/';
}
echo "" . get_the_title( $category ) . "";
}
}
?>
<div class="exposant__filter" id="exposants">
<?php tomtom_output_alphabetic_paginator(); ?>
</div>
<?php $exposantsArchive = tomtom_get_exposants(); ?>
<div class="row row--2col u-m-top--8">
<?php foreach ( $exposantsArchive as $exposant ): ?>
<?php tomtom_hydrate_exposant( $exposant ); ?>
<div class="exposant__thumb col--padding-right">
<div class="exposant__logo">
<img src="<?php echo $exposant->logo['url'] ?>" alt="<?php echo $exposant->logo['alt'] ?>">
</div>
<div class="exposant__thumb-content">
<h2 class="heading--as-h4 heading--no-margin"><?php echo $exposant->post_title; ?></h2>
<?php if ( $exposant->related ): ?>
<p class="exposant__categories">
<?php tomtom_output_related( $exposant->related ); ?>
</p>
<?php endif; ?>
<p class="exposant-thumb__excerpt"><?php echo wp_trim_words( $exposant->description, 16, '...' ); ?></p>
<?php _e( 'Plus de détails', 'festival' ); ?>
</div>
</div>
<?php endforeach; ?>
</div>
I built a custom blog page in my custom wordpress theme, and I'm trying to add pagination to the blog page. Im' using a foreach loop, instead your standard "if while post" loop.
Everything is working find, however I'm not sure where to add "paged" as an argument.
Here is my code:
<?php if (is_page( 'Blog' )) : ?>
<?php
//Get the Posts
$posts = get_posts();
foreach ($posts as $post) :
setup_postdata( $post );
//Setup Post data
$haystack = get_the_category($post->ID);
$i = count($haystack);
$string = "";
for ($j=0; $j < $i; $j++) {
$string .= " ";
$string .= $haystack[$j]->slug;
}
$link = wp_get_attachment_image_src(get_post_thumbnail_id($post->ID), 'large', false );
$href = get_the_permalink();
$theCat = wp_get_post_categories($post->ID);
if (has_post_thumbnail($post->ID)){
$theCols = 'span12';
$imgWidth = 'span4';
$contentWidth = 'span8';
} else {
$theCols = 'span12';
$imgContainer ='display: none;';
$contentWidth = 'width: 100%;';
}
?>
<div class="<?php echo $string;?>">
<div id="post-<?php the_ID(); ?>" class="post-content <?php echo $theCols;?> group nopad">
<div class="post-content--image <?php echo $imgWidth;?> <?php echo $imgContainer;?>">
<img src="<?php echo $link[0]; ?>">
</div>
<!-- Post Content -->
<div class="post-content--container <?php echo $contentWidth;?>">
<?php
$post_title = get_the_title();
$post_title = explode(' ', $post_title);
$title = '';
for ($i=0; $i < 5 ; $i++) {
$title .= $post_title[$i];
$title .= ($i == 50) ? "..." : " ";
}
?>
<p class="post-content--date"><?php echo get_the_date('d M Y'); ?></p>
<h4 class="post-content--heading"><?php echo $title;?></h4>
<p class="post-content--cat"><?php echo $string;?></p>
<div class="post-content--text">
<?php
if ($theCat){
$str = substr(get_the_excerpt(), 0,255);
} else {
$str = get_the_excerpt();
}
$n = strpos($str, '<a');
if ($n > 0){
$rest = substr($str, 0, $n);
echo $rest;
} else {
echo $str;
}
?> ...
</div>
<button class="see-more-btn">Read More</button>
</div>
</div>
</div>
<?php endforeach;
wp_reset_postdata();?>
<?php else : ?>
<p>Critiria Not Found</p>
<?php endif; ?>
what am I missing? Thanks for the help in advance.
If you are going to use the get_posts function you need to set the posts_per_page and offset parameters. You need to check the current page and set the offset according to how many posts you are showing per page and the current page. For eg. On Page 2 and showing 5 posts per page you need to set the offset to 5 in order to skip the first 5 posts.
Note: The posts_per_page parameter does NOT work without setting the offset parameter.
$args = array(
'posts_per_page' => 5,
'offset' => 0
);
$posts_array = get_posts( $args );
One other way is to use the WP_Query and instead of passing the offset argument you just pass the page argument only like the example below where get_query_var('paged') get the value of the ?paged=x and if it its not set will default to '1'.
$paged = ( get_query_var('paged') ) ? get_query_var('paged') : 1;
$query = new WP_Query( array( 'paged' => $paged ) );
If you are going to use WP_Query you need to change from foreach to:
if ( $the_query->have_posts() ) {
while ( $the_query->have_posts() ) {
$the_query->the_post();
$post_id = get_the_ID();
$haystack = get_the_category($post_id);
$i = count($haystack);
}
}
To output the pagination links after the WP_Query you can use the paginate_links function as below. The advantage of using WP_Query is that you will also get the total number of posts found matching the current query parameters in found_posts and other values which you might need like max_num_pages.
echo paginate_links( array(
'base' => '%_%',
'total' => $query->max_num_pages,
'current' => max( 1, get_query_var( 'paged' ) ),
'format' => '?paged=%#%',
'show_all' => false,
'prev_next' => true,
'prev_text' => __('« Previous'),,
'next_text' => __('Next »'),
'add_args' => false,
'add_fragment' => '',
) );
get_posts: https://codex.wordpress.org/Template_Tags/get_posts
WP_Query: https://codex.wordpress.org/Class_Reference/WP_Query#Pagination_Parameters
paginate_links: https://codex.wordpress.org/Function_Reference/paginate_links
I have created a section on home where i am showing 6 post starting from offset 3 and below that i add a custom pagination code.
I have total 93 published post and as i set offset 3 so the pagination is set for rest 90 posts.
For 90 posts, total number of links is 15 in pagination.
Pagination works fine till 11 page i.e mysiteurl/page/11. when i click 12 in the pagination links, it show me 404. It should show me next 6 posts.
Here is my code:
<?php
// function to get page number
function get_url_var($name){
$strURL = $_SERVER['REQUEST_URI'];
$arrVals = split("/",$strURL);
$found = 0;
foreach ($arrVals as $index => $value){
if($value == $name) $found = $index;
}
$place = $found + 1;
return $arrVals[$place];
}
function myprefix_query_offset(&$query) {
//Before anything else, make sure this is the right query...
if ( ! $query->is_home() ) {
return;
}
//First, define your desired offset...
$offset = 3;
//Next, determine how many posts per page you want (we'll use WordPress's settings)
$ppp = 6;
$page = get_url_var('page');
//Next, detect and handle pagination...
if ( $page ) {
//Manually determine page query offset (offset + current page (minus one) x posts per page)
$page_offset = $offset + ( ($page-1) * $ppp );
//Apply adjust page offset
$query->set('offset', $page_offset );
}
else {
//This is the first page. Just use the offset...
$query->set('offset',$offset);
}
}
add_action('pre_get_posts', 'myprefix_query_offset', 1 );
function myprefix_adjust_offset_pagination($found_posts, $query) {
//Define our offset again...
$offset = 3;
//Ensure we're modifying the right query object...
if ( $query->is_home() ) {
//Reduce WordPress's found_posts count by the offset...
return $found_posts - $offset;
}
return $found_posts;
}
add_filter('found_posts', 'myprefix_adjust_offset_pagination', 1, 2 );
$page = get_url_var('page');
$paged = ( $page ) ? $page : 1;
if($paged == 1){
$custom_args = array(
'post_type' => 'post',
'posts_per_page' => 6,
'paged' => $paged,
'offset' => 3,
'post_status' => 'publish'
);
}else{
$custom_args = array(
'post_type' => 'post',
'posts_per_page' => 6,
'paged' => $paged,
'offset' => 3 + ( ($paged-1) * 6),
'post_status' => 'publish'
);
}
$wpb_ll_query = new WP_Query( $custom_args );
if ( $wpb_ll_query->have_posts() ) : while ( $wpb_ll_query->have_posts() ) : $wpb_ll_query->the_post();
?>
<div class="col-lg-4 col-sm-6 col-md-4 col-xs-6 rec-first1">
<a href="
<?php the_permalink();?>">
<div class="grid-latest-posts">
<?php
if(has_post_thumbnail())
{
the_post_thumbnail();
}
else
{
?>
<img class="no-image" src="/wp-content/uploads/2017/02/no-image.png">
<?php
}
$category_object = get_the_category(get_the_ID());
$category_name = $category_object[0]->name;
?>
<label><?php echo $category_name;?></label>
</div>
</a>
<div class="style-txt-nxt">
<span> <a href="<?php the_permalink();?>">
<?php
$string = get_the_title();
$post_title = (strlen($string) > 30) ? substr($string,0,30)."..." : $string;
?>
<?php
echo $post_title;
?>
</a></span>
<p id="art-date2">
<?php echo get_the_date(); ?></p>
<div class="line1">
</div>
<h3>
<a href="
<?php the_permalink();?>">read more</a>
</h3>
</div>
</div>
<?php
endwhile;
//wp_reset_postdata();
else : ?>
<p>
<?php _e( 'Sorry, no posts matched your criteria.' ); ?></p>
<?php endif; ?>
</div>
</div>
</section>
<!-- Pagination for posts -->
<section>
<div class="container">
<div class="row">
<div class="col-lg-12 col-md-12 col-sm-12 col-xs-12">
<!--<h3><a id="more_posts">Load More</a></h3>-->
<?php
if (function_exists(custom_pagination)) {
custom_pagination($wpb_ll_query->max_num_pages,"",$paged);
}
wp_reset_postdata();
?>
</div>
</div>
</div>
</section>
I defined custom_pagination() function in function.php
<?php
function custom_pagination($numpages = '', $pagerange = '', $paged='') {
if (empty($pagerange)) {
$pagerange = 2;
}
/**
* This first part of our function is a fallback
* for custom pagination inside a regular loop that
* uses the global $paged and global $wp_query variables.
*
* It's good because we can now override default pagination
* in our theme, and use this function in default queries
* and custom queries.
*/
global $paged;
if (empty($paged)) {
$paged = 1;
}
if ($numpages == '') {
global $wp_query;
$numpages = $wp_query->max_num_pages;
if(!$numpages) {
$numpages = 1;
}
}
/**
* We construct the pagination arguments to enter into our paginate_links
* function.
*/
$pagination_args = array(
'base' => get_pagenum_link(1) . '%_%',
'format' => 'page/%#%',
'total' => $numpages,
'current' => $paged,
'show_all' => False,
'end_size' => 1,
'mid_size' => $pagerange,
'prev_next' => True,
'prev_text' => __('«'),
'next_text' => __('»'),
'type' => 'plain',
'add_args' => false,
'add_fragment' => ''
);
$paginate_links = paginate_links($pagination_args);
if ($paginate_links) {
echo "<nav class='custom-pagination'>";
echo "<span class='page-numbers page-num'>Page " . $paged . " of " . $numpages . "</span> ";
echo $paginate_links;
echo "</nav>";
}
}?>
Can anyone suggest me some solution to fix it.
Wordpress ninjas... I require some help regarding pagination.
I have the following code :
global $wp_query;
$paged = (get_query_var('paged')) ? get_query_var('paged') : 1;
$args = array_merge( $wp_query->query_vars,
array(
'post_type' => 'attachment',
'posts_per_page' => 10,
'paged' => $paged
)
);
How come $query->max_num_pages returns 0 ?
And is there a way to alter the original archive query with the $query->max_num_pages ?
[EDIT]
In Addition to the above code I have the following
$output = '<div class="download-attachments left_content_container"><ul>';
//this does not retrieve anything
$query = new WP_Query( $args );
// this does retrieve posts
$attachments = get_posts( $args );
// this block is only used for testing purposes..
// ie. it is not being executed because the query does not return anything, Whilst get_posts() works
if( $query->have_posts() ){
while( $query->have_posts() ){
$query->the_post();
echo the_ID();
}
}
foreach ($attachments as $attachment) {
setup_postdata($attachment);
//get attachments metadata etc.
$url = wp_get_attachment_url( $attachment->ID );
$title = get_the_title( $attachment );
$caption = $attachment->post_excerpt;
$size = get_readable_size( filesize(get_attached_file( $attachment->ID )) );
$icon = get_icon_for_attachment( $attachment->ID );
$mime = get_post_mime_type( $attachment->ID );
$date_added = $attachment->post_date;
$filename = ( !$caption == '' ) ? $caption : $title ;
$description = ($attachment->post_content != '') ? '<span class="attachment-author"><span class="attachemnt-label">Added by: ' . $attachment->post_content . '</span></span>' : '';
$output .= '<li class="'.$mime.'">
<img class="attachment-icon" src="'.$icon.'" alt="pdf">
'. $filename .' '.$description.'
<span class="attachment-date"><span class="attachment-label">Date added: </span>'.$date_added.'</span>
<span class="attachment-size"><span class="attachment-label">Attachment size: </span>'.$size.'</span></li>' ;
}
$output .= '</ul></div>';
echo $output;
echo '<div class="paging pull-left">';
$paged = $wp_query->get( 'paged' );
if ( ! $paged) {/* do nothing */ ;}
else { bootstrap_pagination(); var_dump($wp_query->max_num_pages); // returns 0 }
echo '</div>';
You have a couple of problems here. You don't need to call the global $wp_query because you are not going to use it. Secondly, array_merge is totally out of place. This should not be used at all in this situation. Your code should look something like this
$paged = (get_query_var('paged')) ? get_query_var('paged') : 1;
$args = array(
'post_type' => 'attachment',
'posts_per_page' => 10,
'paged' => $paged
)
);
$query = new WP_Query( $args );
For more info on custom queries with WP_Query have a look here