Pagination in FOREACH Loop - wordpress

Can anybody point me in the right direction? I'm trying to get pagination to work because I just have too many entries on the page (see link to sample page below), but am completely in the weeds.
This is for an archive page which lists custom posts based on a custom field (start date) and also drops them from the list when the start date passes.
Here's a sample page:
http://www.musicfestivaljunkies.com/festival-guide/us-festivals/
Here's the code I've been working with:
<?php
/**
* Do we need to filter by event tag?
*/
if(is_tax('event_tags') ) :
$tag = strip_tags( get_query_var('event_tags') );
$querystr = "
SELECT wposts.*
FROM $wpdb->posts wposts, $wpdb->postmeta wpostmeta, $wpdb->terms wterms, $wpdb->term_taxonomy wtax, $wpdb->term_relationships wrels
WHERE wposts.ID = wpostmeta.post_id
AND wterms.term_id = wtax.term_id
AND wtax.term_taxonomy_id = wrels.term_taxonomy_id
AND wrels.object_id = wposts.ID
AND wterms.slug = '$tag'
";
else:
$querystr = "
SELECT wposts.*
FROM $wpdb->posts wposts, $wpdb->postmeta wpostmeta
WHERE wposts.ID = wpostmeta.post_id";
endif;
// Build the rest of the query, i.e. only get events with dates, and order newest first.
$querystr .= "
AND wpostmeta.meta_key = 'Date'
AND STR_TO_DATE(wpostmeta.meta_value,'%m/%d/%Y') >= CURDATE()
AND wposts.post_status = 'publish'
AND wposts.post_type = 'events'
ORDER BY STR_TO_DATE(wpostmeta.meta_value,'%m/%d/%Y') ASC
";
$events = $wpdb->get_results($querystr, OBJECT);
if ($events):
echo '<ul>';
foreach ($events as $post):
global $post;
setup_postdata($post);
// Get a friendlier version of the date.
$date = get_post_meta($post->ID, 'Date', true);
$date = date_create($date);
$date = date_format($date, 'jS F, Y');
?>
<li><?php the_title(); ?> - <?php echo $date; ?></li>
<?php endforeach;
echo '</ul>';
endif; ?>

Unless you're trying to get some seriously unique data, writing your own query is usually something to avoid in WordPress. In this case, you'll want to look into the get_posts() method ( http://codex.wordpress.org/Template_Tags/get_posts ). I'm not 100% sure exactly which parameters you'll need to accomplish your goals, but definitely start by looking at the 'post_type' argument, as well as 'meta_key' and 'meta_value', which you can use to find posts within a particular custom type that have a particular meta value set on them (it appears that's at least partially what you're looking to accomplish).
If this doesn't get you headed in the right direction, please let me know what you're trying to accomplish a little more specifically and maybe I can clarify further.
UPDATE: This section of the get_posts() doc should help specifically with custom fields, and as a bonus it's using a custom post_type as well: http://codex.wordpress.org/Template_Tags/get_posts#Custom_Field_Parameters

Related

Wordpress Code to show single category list in sidebar not including current month

I have found and tweaked some code to show a single category in monthly listings for wordpress in the sidebar. I have one issue though, I do not want it to show the current month. Not sure how to tweak it.
<?php
global $wpdb, $wp_locale;
$query = "select YEAR(post_date) AS <code>year</code>, MONTH(post_date) AS <code>month</code>, count(ID) as posts from $wpdb->posts, $wpdb->term_taxonomy, $wpdb->term_relationships
WHERE $wpdb->posts.post_status = 'publish'
AND $wpdb->posts.post_type = 'post'
AND $wpdb->term_taxonomy.term_id = 9
AND $wpdb->posts.ID = $wpdb->term_relationships.object_id
AND $wpdb->term_taxonomy.term_taxonomy_id = $wpdb->term_relationships.term_taxonomy_id
GROUP BY YEAR(post_date), MONTH(post_date) ORDER BY post_date DESC";
$arcresults = $wpdb->get_results($query);
foreach ($arcresults as $arcresult):
$text = sprintf(__('%1$s %2$d'), $wp_locale->get_month($arcresult->month), $arcresult->year);?>
<li><a href="<?php bloginfo('url') ?>/<?php echo $arcresult->year; ?>/<?php echo str_pad($arcresult->month, 2, '0', STR_PAD_LEFT); ?>/<?php echo "?cat=9"; ?>"><?php echo $text; ?> </li>
<?php endforeach; ?>
Read the documentation on WP_Query and Date_Query objects. You can pass a Date_Query to WP_Query which will filter out the latest month when given the correct parameters.
Using the WP_Query object is far more efficient (for the developer) than building complex SQL queries.

Wordpress - Order Custom Post Type By Custom Taxonomy

I have the following piece of code:
$args = array( 'post_status'=>"publish",
'posts_per_page' => 20,
'post_type'=>"equipment",
'orderby'=>"title",
'order'=>"ASC");
$postslist = get_posts( $args );
foreach ($postslist as $post) : setup_postdata($post); ?>
This all works fine but what I would like to do is to be able to specify the order of the posts by the category within the custom taxonomy.
Is this possible?
Have been trying to use the category array but with no luck.
Just to give all the information, my custom taxonomy is called 'equipcats' and under here I have several categories, e.g. 'Visuals', 'Stage', 'Lighting', 'Sound'...
As it currently stands the order of the posts will be shown as alphabetically ascending so the order will be:
Lighting
Sound
Stage
Visuals
What I would like to do is to be able to have strict control over this ordering, so for example:
Stage
Visuals
Lighting
Sound
All help is greatly appreciated.
Basically, the code below sets up filters to add a "join" clause to include the terms tables in the query, to restrict it to categories, and then to sort by the category ID. And then it re-queries, using the existing query variables (such as page number, etc.).
<?php add_filter('posts_join', create_function('$a', 'global $wpdb; return $a . " INNER JOIN $wpdb->term_relationships ON ($wpdb->posts.ID = $wpdb->term_relationships.object_id) INNER JOIN $wpdb->term_taxonomy ON ($wpdb->term_relationships.term_taxonomy_id = $wpdb->term_taxonomy.term_taxonomy_id) ";'));
add_filter('posts_where', create_function('$a', 'global $wpdb; return $a . " AND $wpdb->term_taxonomy.taxonomy = \'category\'";'));
add_filter('posts_orderby', create_function('$a','global $wpdb; return "$wpdb->term_taxonomy.term_id DESC";'));
query_posts('');
?>
<?php while ( have_posts() ) : the_post() ?>

Display First/Last Post from each Categories in wordpress

I'm new for WordPress. I need to display First/Last Post from Each Parent Categories. That may be in any sub-category.
I need Simple code to get that.
Thanks.
<?php
$category = get_categories();
foreach ($category as $cat)
{
query_posts( array ( 'cat' => $cat->cat_ID, 'posts_per_page' => 5 ) );
echo '<div class="post">';
echo '<h2>'.$cat->cat_name.'</h2>';
echo '<ul>';
while (have_posts())
{
the_post();
echo '<li>'.get_the_title().'</li>';
}
echo '</ul>';
$category_id = get_cat_ID($cat->cat_name);
$category_link = get_category_link($category_id);
echo '<div class="paging">';
echo 'More Post from '.$cat->cat_name.'';
echo '</div>';
echo '</div>';
}
?>
I managed to do this using a custom query here is the query I executed:
SELECT * FROM (
SELECT a.*, d.name as category FROM wp_posts AS a
INNER JOIN wp_term_relationships AS b ON b.object_id = a.ID
INNER JOIN wp_term_taxonomy AS c ON b.term_taxonomy_id = c.term_taxonomy_id AND c.parent = 0
INNER JOIN wp_terms AS d ON d.term_id = c.term_id AND c.taxonomy = 'category'
ORDER BY a.post_date DESC
) as f
GROUP BY f.category
ORDER BY f.post_date DESC;
What this does is get full dataset of posts that are related to category taxonomy then will sorted it in descending mode so It will have the lastest post in first place then group it by category and once again sort it back. If you want to get the oldest just change DESC to ASC.
I use this script in a database will 127,000 posts and even though my server is quite strong It takes 0.0042seg to execute this query.
Hope this might help someone, cheers!

Wordpress - get tags for posts with custom field

I have a custom field, say, "mood", and I need to display list of tags for all posts that have "mood" = "grumpy". Is it possible to do this without fetching all posts and then fetching tags for each of them?
You can use the function get_posts();
$args = array(
'meta_key' => 'mood',
'meta_value' => 'grumpy',
);
$your_posts = get_posts( $args );
Untested, but this should achieve what you want. Just look out for typos and missed semi-colons!
While you don't get the whole post, you do still have to query the database for the ID of posts with 'mood' = 'grumpy', so unless you have lots of posts, it's probably easier to just go with the answer #Dorel gave.
$query = $wpdb->prepare('
SELECT ID
FROM %1$s
LEFT JOIN %2$s
ON %1$s.ID = %2$s.post_id
WHERE %2$s.meta_key = "mood"
AND %2$s.meta_value = "grumpy"
', $wpdb->posts, $wpdb->postmeta
);
$ids = $wpdb->get_col($query);
if(!empty($ids)) : foreach($ids as $post_id) :
$tags = wp_get_post_tags($post_id, $args);
if(!empty($ids)) : foreach($tags as $tag) :
$tags[] = $tag->name;
endforeach;
endif;
endforeach;
endif;
// Now you have an array of Tag names, output them as you wish
Codex for wp_get_post_tags = http://codex.wordpress.org/Function_Reference/wp_get_post_tags
Codex for wp_get_object_terms (to see what $args are available for wp_get_post_tags) =
http://codex.wordpress.org/Function_Reference/wp_get_object_terms#Argument_Options

How can I get a post by title in Wordpress?

Wordpress 3.0
I want to have the contents of a specific post into a page by using the title of the post. As far as I can tell, I can't do it directly with get_post().
I can assume what the brute force way might be, but I suspect there's a more elegant way?
get_page_by_title($id, OBJECT, 'post');
There ye go.
<!--1.Get post ID by post title if you know the title or the title variable-->
<?php
$posttitle = 'post_title';
$postid = $wpdb->get_var( "SELECT ID FROM $wpdb->posts WHERE post_title = '" . $posttitle . "'" );
echo $postid;
?>
<!--2.use get_post($post_id) to get whatever you want to echo-->
<?php
$getpost= get_post($postid);
$postcontent= $getpost->post_content;
echo $postcontent;
?>
No need to SQL query's when you can use wordpress own functions for this.
$page = get_page_by_title( 'Startsida' );
$page_id = $page->ID;
post_exists is a good function for that :
https://developer.wordpress.org/reference/functions/post_exists/
<?php
$post_id = post_exists('Your title');
// return id or 0 if post doesn't exists.
if($post_id>0)
get_post($post_id);
See my answer on a very similar question. Do not query the data base with an unescaped string.
You can use this:
1)
global $wpdb;
$your_title = "yourtitle";
$id = $wpdb->get_var("SELECT ID FROM $wpdb->posts WHERE post_name = $your_title");
echo $id;
or 2)
$slug_to_get = 'my_title_or_slug';
// you can use custom post type too
$posttypee='post';
$args=array(
'title' => $slug_to_get,
'post_type' => $posttypee,
'post_status' => 'publish'
);
$my_posts = get_posts($args);
if( $my_posts ) {
echo 'ID on the first post found '.$my_posts[0]->ID;
}

Resources