loop won't work inside my plugin - wordpress

Is it possible to loop in a wordpress plugin?
I've created this plugin that utilizes a wordpress loop to grab some info about posts in my custom post type of events:
function getEventsFeed() {
$args = array( 'post_type' => 'events' );
$loop = new WP_Query( $args );
$htmlOutput = '<h2>Events</h2>';
while ( $loop->have_posts() ) : $loop->the_post();
$date = get_post_meta($post->ID, 'events_0');
$location = get_post_meta($post->ID, 'events_9');
$htmlOutput .= '<tr><td>' . the_title() . '</td><td>' . $date[0] . '</td><td>' . $post->post_title .'</td><td>' . $location[0] . '</td></tr>';
endwhile;
$htmlOutput .= '</div>';
echo $htmlOutput;
}
Problem is only the the_title info is being returned. $post is not working within the loop so $post->ID and $post->post_title are not being returned. I'm using this exact code in another page template and it returns all the data correctly. I'm not sure why it won't return when I use it in a plugin.
Any ideas?

Try adding
global $post;
to the beginning of your function. $loop->the_post() will set the global $post variable, but it is not available inside your function scope.

Related

Using WP_Query in functions.php only returning one result

I've written a function in my functions.php file that runs a new WP_Query class to fetch some child pages on my custom page template according to their meta key/value. It's kind of working but it's only returning one result - I know there are more as I had the query running properly on the specific page before I turned it into a function. It returned all the correct results, but as I may need this functionality in several pages I decided to turn it into a function.
Here is my function code…
function contact_profiles($args) {
global $post;
$output = "";
$the_query = new WP_Query( $args );
while ( $the_query->have_posts() ) : $the_query->the_post();
$output = '<div class="staff-member">'
.'' . get_the_post_thumbnail() . ''
.'<h2 class="name">' . get_the_title() . '</h2>'
.'<h3 class="job-role">' . get_post_meta( $post->ID, 'job_role', true ) . '</h3>'
.'</div>';
endwhile;
wp_reset_postdata();
return $output;
}
and here is how I am calling it in my custom page template…
$myarray = array('meta_key' => 'job_area', 'meta_value' => 'Online', 'post_type' => 'page',);
echo contact_profiles($myarray);
Am I doing something obvious that I shouldn't be? Is the global $post bit causing the issue as I'm not sure I should call it from the functions file.
Most probably you have your posts per page setting to 1 in the back end reading section. If no custom value is passed to a custom query, the default option get_option( 'posts_per_page' ) is used as value to the posts_per_page parameter.
You solution would be to explicitely set posts_per_page to a desired amount or to -1 to get all posts
EDIT
I have missed this before, your concatenation is wrong.
$output = '<div class="staff-member">'
should be
$output .= '<div class="staff-member">'
Here is an updated version of your code
function contact_profiles($args)
{
$output = "";
$the_query = new WP_Query( $args );
while ( $the_query->have_posts() ) : $the_query->the_post();
$output .= '<div class="staff-member">'
.'' . get_the_post_thumbnail() . ''
.'<h2 class="name">' . get_the_title() . '</h2>'
.'<h3 class="job-role">' . get_post_meta( $post->ID, 'job_role', true ) . '</h3>'
.'</div>';
endwhile;
wp_reset_postdata();
return $output;
}

<!--more--> being ignored when WordPress content is displayed

I'm trying to write a plugin that will take page id's and return a preview of the page. Here's my code:
function page_preview($atts,$pageid = null) {
extract(shortcode_atts(array(
"pageid" => '0'
), $atts));
$the_query = new WP_Query( 'page_id=' . $pageid . '' );
global $more;
$more = 0;
if ( $the_query->have_posts() ) {
while ( $the_query->have_posts() ) {
$the_query->the_post();
$title=get_the_title();
$thumbnail=get_the_post_thumbnail( $pageid, 'preview' );
$content=get_the_content();
}
}
return '<div class="callout">' .
'<h4>' .
$title .
'</h4>' .
$thumbnail .
$content . '<a href="' .
get_the_permalink($pageid) .
'">Continue reading</a></div>';
}
add_shortcode( 'pagepreview', 'page_preview' );
and it gets called on wpadmin editor like so:
[pagepreview pageid=11][pagepreview pageid=13][pagepreview pageid=8054]
i.e., that would display a page preview for each of those page ids.
The "more" doesn't work.
global $more;
$more = 0;
usually fixes this issue, but it's not in my case. Can anyone see what I"m doing wrong? Thanks.
You're getting the full content because
$content=get_the_content();
is not applying the_content() filters, and $more=0 must be on a line after $the_query->the_post(); inside the while loop. Change your while loop to this:
while ( $the_query->have_posts() ) {
$the_query->the_post();
$more=0;
$title=get_the_title();
$thumbnail=get_the_post_thumbnail( $pageid, 'preview' );
$content = apply_filters( 'the_content', get_the_content() );
$content = str_replace( ']]>', ']]>', $content );
}
See get_the_content and read more in pages on the WordPress Codex for where I sourced this.

Creating a recent posts widget for wordpress but ran into problems where it displays info from the first post

Hey guys I am making a Widget to display a posts title, and excerpt from that post, and its date. The code I have is here:
public function widget( $args, $instance ) {
extract( $args );
$headline = $instance['headline'];
$category = $instance['category'];
$numberposts = $instance['numberposts'];
$readmore = $instance['readmore'];
echo $before_widget;
echo $before_title;
echo "<p class=\"headline\">$headline</p>";
echo $after_title;
$args = array( 'numberposts' => $numberposts, 'category_name' => $category );
$recent_posts = wp_get_recent_posts( $args );
foreach( $recent_posts as $recent ){
echo '<a href="' . get_permalink($recent["ID"]) . '" title=" '.esc_attr($recent["post_title"]).'" >' . $recent["post_title"].'</a> ';
echo the_time('F j, Y');
echo the_excerpt();
}
As you can see I am trying to call the time and the excerpt from the post. It is working but it is only displaying the date and and excerpt from the very first post that is called welcome. I want it to display the Date and excerpt from each individual post. I will post a link to the site with the widget in the side bar. Sorry if I am not being clear enough or if more info is needed I am very new to this.
http://www.modmacro.us/wpsandbox/
First thing: the_excerpt(), is already an echo statement. Not a return statement. It's the same with the_date(). Prefix them with "get_", and they will return the information you need, or you can get rid of the echo command preceding it.
Second thing: In order for those functions to work, they need to be used in a Wordpress loop.
Since we're already in a loop, we just have to make sure it changes the Wordpress Globals appropriately to reflect the information you need..
foreach( $recent_posts as $recent ){
setup_postdata(get_post($recent['ID']));
echo '<a href="' . get_permalink() . '" title=" '.esc_attr(get_the_title()).'" >' . get_the_title().'</a> ';
echo get_the_time('F j, Y', $recent['ID']);
the_excerpt();
}
wp_reset_postdata();

Getting the post ID outside outside of the Wordpress loop

So I have a snippet of code that grabs the categories and their coinciding posts and lists them outside of the loop (Below). I've been trying to get the post to link to #post-[ID] instead of the permalink - but I keep failing. Can anyone help?
<ul id="sidebar">
<?php
foreach( get_categories('orderby=ID&order=desc') as $cat ) :
if( !$cat->parent ) {
echo '<li class="title"><h2>' . $cat->name . '</h2>';
echo '<ul>';
process_cat_tree( $cat->term_id );
}
endforeach;
wp_reset_query(); //to reset all trouble done to the original query
//
function process_cat_tree( $cat) {
$args = array('category__in' => array( $cat ), 'numberposts' => -1);
$cat_posts = get_posts( $args );
$id = $post->ID;
global $post;
if( $cat_posts ) :
foreach( $cat_posts as $menuPost ) :
echo '<li';
if ( $menuPost->ID == $post->ID ) { echo ' class="active"'; }
echo '>';
echo '' . $menuPost->post_title . '';
echo '</li>';
endforeach;
endif;
echo '</ul></li>';
}
?>
The above code is outputting UL/LI tags like this:
CATEGORY
Post
Post
Post
CATEGORY
Post
Post
Post
CATEGORY
Post
Post
Post
Admittedly, I don't exactly understand what you mean by "linking to #post-[ID]", but going with the question title:
If you use get_permalink() when echoing the link, you will get the permalink - that's just what that function does.
Use get_the_ID() instead, if you want the post-ID returned, or the_ID() if you want it displayed (the_ID() is the same as echo get_the_ID()).
Edited from here:
If you're otherwise happy with the above code, changing
echo '' . $menuPost->post_title . '';
to
echo '' . $menuPost->post_title . '';
ought to do it.
However, I'd go about it like so:
echo '<ul>';
$cat_args = array(
'orderby' => 'name',
'order' => 'ASC'
);
$categories = get_categories($cat_args);
foreach($categories as $category) {
echo '<li class="title"><h2>' . $category->name . '</h2><ul>';
// query posts of that category:
$query_args = array(
'cat' => $category->cat_ID,
'posts_per_page' => -1
);
$your_query = new WP_Query( $query_args );
// loop through them:
while ( $your_query->have_posts() ) : $your_query->the_post();
echo '<li><a href="#post-';
the_ID();
echo '">';
the_title();
echo '</a></li>';
endwhile;
echo '</ul></li>';
// Reset Post Data
wp_reset_postdata();
}
echo '</ul>';

Only displaying a posts selected taxonomy terms?

When using wp_get_post_terms() I can produce a list of taxonomy terms associated with a post. However, I only want to show the taxonomy terms that have been selected for that post. Using the aforementioned function and get_terms() will successfully find the taxonomy terms, but it will show all of the terms. Not only the ones that have been selected. In the $args array for the functions I've looked for a 'selected' filter, but I found none and when I tried it, it didn't work.
Am I trying to do something that can't be done? I'm sure it's something that is starring me right in the face. I just want to ask the pro's before I make major changes to the way I'm doing things.
wp_get_post_terms only returns terms that have been selected for that post, it doesn't return all taxonomy terms.
http://codex.wordpress.org/Function_Reference/wp_get_post_terms
<?php
$the_selected = $_GET['cat'];
$args = array( 'post_type' => 'portfolio_item', 'posts_per_page' => 11, 'orderby' => 'id', 'order' => 'DESC', 'themes_categories' => "$the_selected");
$loop = new WP_Query( $args );
while ( $loop->have_posts() ) : $loop->the_post();
?>
This works well for me. I simply send the taxonomy slug to browser, and itterate through them with the code above.
I send by this:
<li>Filter By:</li>
<?php
$categories=get_categories($args);
foreach($categories as $category) {
echo '<li><a href="' . get_category_link( $category->term_id ) . '?cat=' . $category->slug.'" title="' . sprintf( __( "View all posts in %s" ), $category->name ) . '" ' . '>' . $category->name.'</a> </li> ';
}
?>
You can try out this code, it worked for me. I have a taxonomy named 'stores' and i wanted to display 2 selected taxonomy from it. so i used a include feature.
<?php
$taxonomy = 'stores';
$args1=array(
'include'=> array(12,30)
);
$terms = get_terms('stores',$args1 );
echo '<ul>';
foreach ($terms as $term) {
//Always check if it's an error before continuing. get_term_link() can be finicky sometimes
$term_link = get_term_link( $term, 'stores' );
if( is_wp_error( $term_link ) )
continue;
//We successfully got a link. Print it out.
echo '<li>' . $term->name . '</li>';
}
echo '</ul>';
?>
<?php echo get_the_term_list( $post->ID, 'your_taxonamy'); ?>
And if you want it without the term linking you can use this
<?php $terms_as_text = get_the_term_list( $post->ID,'your_taxonamy'); if (!empty($terms_as_text)) echo '', strip_tags($terms_as_text) ,''; ?>

Resources