Unable to use the get_excerpt function in wordpress - php

I am new to wordpress and php. I am trying to get the excerpt of a post retrieved using foreach in wordpress. I am trying to display all the posts on a page but I dont want to display the whole content I want only excerpt.
I am able to displat the title but unable to get the excerpt.
I have tried: $excerpt = get_post_excerpt($post),$excerpt = get_the_excerpt($post);, $excerpt = $post->the_excerpt()
please also tell me if iam missing some basics.
here is my full code
<?php
function some_code() {
// query
$query = 'orderby=date&order=asc&posts_per_page=-1';
$wpq = new WP_Query($query);
$posts = $wpq->get_posts();
foreach($posts as $post)
{
$link = get_permalink($post);
echo "<a href='$link'><h3>{$post->post_title}</h3></a>";
$excerpt = get_the_excerpt($post);
echo "$excerpt";
}
}
?>

An easy solution compatible with your code would be to use setup_postdata($post); inside your foreach loop, which makes all the post related data available:
$query = 'orderby=date&order=asc&posts_per_page=-1';
$wpq = new WP_Query($query);
$posts = $wpq->get_posts();
foreach($posts as $post)
{
setup_postdata($post);
$excerpt = get_the_excerpt($post);
echo $excerpt;
}
More about setup_postdata() can be found here.
Try this also if that doesn't work, I think using a traditional loop instead of foreach is a better approach:
$query = array('orderby' => 'date', 'order' => 'asc', 'posts_per_page' => '-1');
$wpq = new WP_Query($query);
if($wpq->have_posts()){
while($wpq->have_posts()){
$wpq->the_post();
the_excerpt();
}
}
Or you can use a function called wp_trim_words:
echo wp_trim_words( $post->post_content );

Related

List each custom post type separately in a wp_query without repeating the loop

I'm using an AJAX search to pull 3 custom post types from wordpress (post, guides, advice). As you can see in my if while loop, the results show which results are which but I'm trying to section them out individually so it will show something like this:
section 1
blog posts
section 2
guides
The problem seems to be that I need to edit the if while loop because adding anything inside that loop will just cause it to be in that loop. Does anyone know the best way to modify the if while loop to achieve this?
function data_fetch(){
$the_query = new WP_Query(
array(
'posts_per_page' => 6,
's' => esc_attr( $_POST['keyword'] ),
'post_type' => array('post' , 'guides', 'advice'),
'post_status' => 'publish'
)
);
global $post;
if( $the_query->have_posts()) :
while( $the_query->have_posts() ): $the_query->the_post(); ?>
<?php $type = get_post_type();
$term = $_POST['keyword'];
$i++;
$total = $the_query->found_posts;
?>
<span class="search-title">
<?php if ($type == 'post'):?>
<?php echo 'Article: ';?>
<?php elseif($type == 'guide' ):?>
<?php echo 'Guide: ';?>
<?php elseif($type == 'advice' ):?>
<?php echo 'advice: ';?>
<?php endif;?>
<?php the_title();?><br>
</span>
<?php endwhile; ?>
<?php
wp_reset_postdata();
else:
echo '<h3>No Results Found</h3>';
endif;
die();
}
If I were you, I'd probably just do three separate queries. They seem simple enough that it shouldn't cause any issues at all. Otherwise you have to either sort through or reorder the WP_Query results somehow.
If you're set on the single query, however - since these are such short HTML strings, I'd probably just control the output with the Output Buffer.
Basically you can create an associative array, and add the HTML strings to the appropriate keys. You could get a bit more elaborate and have them be nested arrays, but since your output is so light, you can probably get by just by having HTML strings as the values for the keys.
I took the liberty of cleaning up your code a little bit and removing some unused variables, etc.
function data_fetch(){
// Build the Query Arguments
$the_query = new WP_Query( array(
's' => esc_attr($_POST['keyword']),
'posts_per_page' => 6,
'post_type' => array('post' , 'guides', 'advice'),
'post_status' => 'publish'
) );
// Do we have posts?
if( $the_query->have_posts()){
// We do. Start an array that will fill with HTML from the output buffer
$output = array(
'post' => '',
'guides' => '',
'advice' => '',
);
// Loop through the posts
while( $the_query->have_posts() ){
$the_query->the_post();
ob_start(); // Turn on the output buffer
$type = get_post_type(); ?>
<span class="search-title">
<?php echo ($type == 'post') ? 'Article: ' : ucwords($type).': '; // Output "Articles: " for posts, or just capitalize the other post type names ?>
<?php the_title();?><br>
</span>
<?php $output[$type] .= ob_get_clean(); // Add the HTML output from the buffer to our array
}
wp_reset_postdata();
// Here we have an array with 3 HTML strings that we can output wherever
echo $output['post'];
echo $output['guides'];
echo $output['advice'];
} else {
echo '<h3>No Results Found</h3>';
}
}
if I understood your concern, I propose to divide your code by creating a generic class.
and you make calls to the different Post Type :
class Custom_Query {
public $post_type;
public $key_word;
public function __construct($post_type, $keyword) {
$this->post_type = $post_type;
$this->key_word = $keyword;
}
public function getResult() {
echo '<h1>Article : ' . $this->post_type . '</h1>';
$the_query = new WP_Query(
array(
'posts_per_page' => 6,
's' => esc_attr($this->key_word),
'post_type' => array($this->post_type),
'post_status' => 'publish'
)
);
if ($the_query->have_posts()):
while ($the_query->have_posts()): $the_query->the_post();
echo '<span class="search-title">';
echo '' . the_title() . '<br>';
echo '</span>';
endwhile;
else:
echo '<h3>No Results Found</h3>';
endif;
wp_reset_postdata();
}
}
global $post;
$type = get_post_type();
$term = $_POST['keyword'];
$article = new Custom_Query($type, $term);
$article->getResult();
You were on the right track initially. You can just use the standard post objects to check for post type. You can adjust to fit your needs, but try something like this:
<?php
query = new WP_Query( array(
's' => esc_attr($_POST['keyword']),
'posts_per_page' => 6,
'post_type' => array('post' , 'guides', 'advice'),
'post_status' => 'publish'
) );
if ($query->have_posts()) {
while ($query->have_posts()):
$query->the_post();
?>
<div class="posts">
<?php
if ($query->post->post_type === 'post') {
// add your content
} else if ($query->post->post_type === 'guides' {
// add your content
} else {
// add your content
}
?>
</div>
<?php endwhile;
} else {
// no posts found
}

Get post content by ID for custom post types

I'm trying to fetch specific post content by ID for a custom post type.
I've tried the following solutions and a few more. At best I seem to be retrieving the title. But none of the content.
1:
<?php
$post_id = 15002;
$queried_post = get_post($post_id);
$title = $queried_post->post_title;
echo $queried_post->post_content;
?>
2:
<?php
$my_postid = 15002;
$content_post = get_post($my_postid);
$content = $content_post->post_content;
$content = apply_filters('the_content', $content);
$content = str_replace(']]>', ']]>', $content);
echo $content;
?>
3:
<?php
$ID = 15002;
$args = array('p' => $ID, 'post_type' => 'ct_template');
$loop = new WP_Query($args);
?>
<?php while ( $loop->have_posts() ) : $loop->the_post(); ?>
<?php global $post; ?>
<?php the_content () ?>
<?php endwhile; ?>
If you are using Toolset and want to get content by page Id then use below code in your function.php
add_filter( 'wpv_filter_content_template_output', 'get_content_template_id', 99, 4 );
function get_content_template_id( $content, $template_selected, $id, $kind ) {
global $current_archive_template_id;
$current_archive_template_id = $template_selected; // $template_selected = current Content Template ID
return $content;
}
Then use below code to get title and content
$content_template_title = get_the_title($current_archive_template_id);
$content_template_content = get_the_content($current_archive_template_id);

Wordpress, setup_postdata() not doing its job

My posts get ordered by date which is picked by an advanced custom field datepicker. I want to use the regular Wordpress function references [the_title(), etc …] and the post related custom field's.
Right now the output of every loop is the the same. I read setup_postdata() can solve this issue and enable the use of the regular function references. I tried to apply it, but the output keeps being always the same. Thanks
<?php
global $posts;
$posts = get_posts(array(
'post_type' => 'post',
'meta_key' => 'release_date',
'orderby' => 'meta_value_num',
'order' => 'DESC'
));
$group_posts = array();
if( $posts ) {
foreach( $posts as $post ) {
$date = get_field('release_date', $post->ID, false);
$date = new DateTime($date);
$year = $date->format('Y');
$month = $date->format('F');
$group_posts[$year][$month][] = array($post, $date);
}
}
foreach ($group_posts as $yearKey => $years) {
foreach ($years as $monthKey => $months) {
echo '<li class="time">' . $monthKey . ' ' . $yearKey . '</li>';
foreach ($months as $postKey => $posts) {
setup_postdata($posts); ?>
<li class="item clearfix">
<!-- Wordpress Functions -->
<?php the_title();?>
<?php the_permalink();?>
<!-- Advanced Custom Fields -->
<?php the_field('blabla')?>
</li>
<?php
}
}
} wp_reset_postdata();
?>
You just need to add a line $post = $current_post; just before calling setup_postdata( $post ). See my example below to have a clear idea:
$posts = get_posts(array(.......));
// Call global $post variable
global $post;
// Loop through sorted posts and display using template tags
foreach( $posts as $current_post ) :
//the below line is what you missed!
$post = $current_post; // Set $post global variable to the current post object
setup_postdata( $post ); // Set up "environment" for template tags
// Use template tags normally
the_title();
the_post_thumbnail( 'featured-image-tiny' );
the_excerpt();
endforeach;
wp_reset_postdata();
For details please see this comment posted in the WP-Codex;

wordpress shortcode render content in dashboard also

I am using a simple wordpress shortcode
function my_recent_post()
{
echo 'hello';
}
add_shortcode( 'recent', 'my_recent_post' );
with the shortcode [recent] and its working fine and visible in front page,
but the problem is, its printing the hello in the dashboard also.
below is the screenshot, can anyone please help.
Update:
I was actually trying to show posts, so can you help me with this, because it renders the lists of posts in the dashboard itself like the "hello". I tried:
function lorem_function() {
global $post;
$args = array( 'posts_per_page' => 10, 'order'=> 'ASC', 'orderby' => 'title' );
$postslist = get_posts( $args );
foreach ( $postslist as $post ) :
setup_postdata( $post ); ?>
<div>
<?php the_date(); ?> <br /> <?php the_title(); ?> <?php the_excerpt(); ?>
</div>
<?php endforeach;
wp_reset_postdata();
return;
}
add_shortcode('lorem', 'lorem_function');
Based on your comments to me & Nikita Dudarev, what you need to do is create a variable to hold all the post information and then return it. Using the function you posted as an example:
function lorem_function() {
global $post;
$args = array( 'posts_per_page' => 10, 'order'=> 'ASC', 'orderby' => 'title' );
$postslist = get_posts( $args );
// create a variable to hold the post information
$html ="";
foreach ( $postslist as $post ) :
setup_postdata( $post );
$backgroundstyle = "";
// get the featured image and set it as the background
if ( has_post_thumbnail() ) { // make sure the post has a featured image
$imageurl = wp_get_attachment_image_src( get_post_thumbnail_id($post->ID), 'medium' ); // you can change "medium" to "thumbnail or full depending on the size you need
// add the css for the background image. You can include background-size etc ad required
$backgroundstyle = "background-image: url('".$imageurl[0]."');";
}
// add the information to the variable
$html .= '<div style="'.$backgroundstyle.'">';
$html .= get_the_date();
$html .= "<br />";
$html .= get_the_title();
$html .= get_the_excerpt();
$html .= "</div>";
endforeach;
wp_reset_postdata();
return $html;
}
add_shortcode('lorem', 'lorem_function');
Note that the_date(), the_title() and the_excerpt() all display the information (just like echo).
Instead you must use get_the_date(), get_the_title() and get_the_excerpt() - these get the same information, but instead of displaying it directly, they return it as a variable which you can then store in your html string to be returned.
Update:
As you don't want to use the variable name on each line for whatever reason, you can do it like this:
$html .= "<div>".get_the_date()."<br />".get_the_title().get_the_excerpt()."</div>";
I'm not sure why you specifically want to change it to do that - it makes absolutely no difference to how it works, it just makes it harder to read and identify any errors :-)
Your function must return a value, not output
function my_recent_post()
{
return 'hello';
}
add_shortcode( 'recent', 'my_recent_post' );

Can't get most recent post from categories

I'm trying to get a category and loop through its sub categories getting one post from each of those sub-categories. Below is my code:
<?
$homepage_cat = get_category_by_slug( 'home-page-slider' );
$id = $homepage_cat->cat_ID;
print($id);
$sub_cat = get_categories('hide_empty=0&child_of=' . $id);
print_r($sub_cat);
foreach ($sub_cat as $key => $cat)
{
echo $cat->term_id;
query_posts('cat=' . $cat->term_id);
if ( have_posts() )
{ echo '<h1> HELL YEAH </h1>';
while ( have_posts() )
{
echo '<h1>' get_the_title(); '</h1>';
} // end while
} // end if
} //end foreach
?>
The code is not returing any posts as HELL YEAH is not being echoed. Can anyone suggest a solution?
Use get_posts() not query_posts, it is better for these kinds of situations.
$args = array('posts_per_page' => 1, 'category' => $cat->term_id);
$posts = get_posts($args);
foreach($posts as $post) : setup_postdata( $post ) ?>
<h1><?php get_the_title(); ?></h1>
<?php endforeach; ?>
There are quite a few problems here
First of all, never use query_posts to construct custom queries. It breaks the main query, is unreliable and outright fails in most cases in pagination
Secondly, you have to reset your postdata after every custom query
Thirdly, never use short tags. Always use full tag ie <?php and not just <?
Lastly, you are missing the_post() which should return post objects
Your query should look something like this
<?php
$homepage_cat = get_category_by_slug( 'home-page-slider' );
$id = $homepage_cat->cat_ID;
print($id);
$sub_cat = get_categories('posts_per_page=1&hide_empty=0&child_of=' . $id);
print_r($sub_cat);
foreach ($sub_cat as $key => $cat)
{
echo $cat->cat_ID;
$q = new WP_Query('cat=' . $cat->cat_ID);
if ( $q->have_posts() )
{ echo '<h1> HELL YEAH </h1>';
while ( $q->have_posts() )
{
$q->the_post();
echo '<h1>' get_the_title(); '</h1>';
} // end while
} // end if
wp_reset_postdata();
} //end foreach
?>
Replace this
$post_args = array(
'showposts' => 1,
'cat' => $cat->term_id
);
with this.
$post_args = array(
'posts_per_page' => 1,
'category' => $cat->term_id
);
I hope it'll work.

Categories