how to query only one post in wordpress widget - php

I am making a wordpress widget for my wordpress theme. In the widget I am trying to query only one post on the front-page.php I am using WP_query for that. But the problem is it is getting all the posts available. I have no idea how to fix this. Any suggestion will be helpful.
My code
public function widget($args, $instance) {
$posts_args = array(
'post_type' => 'post',
'post_per_page' => 1,
'order' => 'DESC'
);
$posts_query = new WP_Query($posts_args);
echo $args['before_widget'];
if($posts_query -> have_posts()):
while($posts_query->have_posts()): $posts_query->the_post();
echo '<div class="widget-single-content" style="background-image: url('.get_the_post_thumbnail_url().')">';
echo '<div class="content-box">';
echo '<h1><span>"</span>'.get_the_title().'<span>"</span></h1>';
echo '<button class="readmore-btn text-captalize">
Read More</button>';
echo '</div>';
echo '</div>';
endwhile;
endif;
echo $args['after_widget'];
//Query
}

$posts_args = array(
'post_type' => 'post',
'numberposts' => 1, //this show how many posts to query from DB
'order' => 'DESC',
'posts_per_page' => 1//this show how many posts display
);
posts_per_page

Related

Filter WP_QUERY by custom taxonomy

I'm trying to solve one issue with one of the functions which I've created recently. Below you will find a piece of code which creates a dropdown field in which each represents specific 'partner company'. The code works perfectly.
function fnc_select_1() {
$args = array(
'post_type' => 'freecourses',
'orderby' => 'meta_value',
'status' => 'publish',
'order' => 'DESC',
'meta_key' => 'validation_date',
);
$the_query = new WP_Query($args);
if ($the_query->have_posts()):
while ($the_query->have_posts()) : $the_query->the_post();
if(have_rows('validation_date')):
while (have_rows('validation_date')) : the_row();
if( get_sub_field('company')) {
$firm_array[] = get_sub_field('company');
}
endwhile;
wp_reset_query();
else :
// no rows found
endif;
endwhile;
$firms = array_unique($firm_array);
natsort($firms);
echo '<select type="text" class="form-control" name="company" id="company">';
echo '<option value="">company</option>';
foreach ($firms as $firm) {
echo '<option value="'. $firm .'">';
echo $firm;
echo '</option>';
}
echo '</select>';
endif;
}
add_shortcode( 'select_1', 'fnc_select_1' );
Because of certain reasons I've decided to enhance this function by adding:
extra filtering based on custom taxonomy (called "type")
based on a page in which function will be displayed I wanted to limit / filter those companies by specific terms of this taxonomy.
So I've created this kind of code:
if (is_page(29557) ):
$childno = '205';
elseif (is_page(29640) ):
$childno = '206';
endif;
and simply to my wp_query args I thought I may add:
'tax_query' => array(
'relation' => 'AND',
array(
'taxonomy' => 'type',
'child_of' => $childno
),
),
but it doesn't work. It do not display the dropdown at all..
Where is the issue then?

How to render formatted post content in widget in Wordpress

I am new on wordpress and try to make a widget which will only show the last post of particuler category.
TO do this I have given some settings in admin to select category for which admin wants to display last post (post of last ID).
I am using the below code to in widget to display post content:
$query_arguments = array(
'posts_per_page' => (int) 1,
'post_type' => 'post',
'post_status' => 'publish',
'cat' => (int) $settings['category'],
'order' => 'DESC',
'orderby' => (($settings['display_by'] == 0) ? 'ID' : 'date')
);
$posts_query = new WP_Query( $query_arguments );
if ($posts_query->have_posts()) {
$posts = $posts_query->get_posts();
$post = $posts[0];
echo $post->post_content;
}
But the above code is showing content in one paragraph or you can say that without format. I have done lot of search and found that, I need to apply "the_content" filter to format the content. So I have done the same as below code:
if ($posts_query->have_posts()) {
$posts = $posts_query->get_posts();
$post = $posts[0];
$content = apply_filters('the_content', $post->post_content);
echo $content;
}
Now the above changes is returning the null string. I have google lot of things but everyone is saying that to use apply filter or use the_content() function. I have tried both solutions but nothing happening.
Can anyone please share the solution for this problem?
please check whether you are getting any text in $post->post_content
by echo $post->post_content
All you need to do is,
$query_arguments = array(
'posts_per_page' => (int) 1,
'post_type' => 'post',
'post_status' => 'publish',
'cat' => (int) $settings['category'],
'order' => 'DESC',
'orderby' => (($settings['display_by'] == 0) ? 'ID' : 'date')
);
$posts_query = new WP_Query( $query_arguments );
while ($posts_query->have_posts()) {
$posts_query->the_post();
echo get_the_content();
}

How to display latest posts in Wordpress

On one of my pages, I want a section to show the latest 3 news posts.
Is there a simple way to retrieve the n latest posts so that they can be displayed?
<?php
function latest_post() {
$args = array(
'posts_per_page' => 3, /* how many post you need to display */
'offset' => 0,
'orderby' => 'post_date',
'order' => 'DESC',
'post_type' => 'post', /* your post type name */
'post_status' => 'publish'
);
$query = new WP_Query($args);
if ($query->have_posts()) :
while ($query->have_posts()) : $query->the_post();
?>
<?php the_title(); ?>
<?php echo get_the_post_thumbnail('thumbnail'); ?>
/* here add code what you need to display like above title, image and more */
<?php
endwhile;
endif;
}
add_shortcode('lastest-post', 'latest_post');
?>
Add Above code in function.php file.
After that paste below shortcode there you want to display latest post.
Adin side : [lastest-post]
in file : <?php echo do_shortcode('[lastest-post]'); ?>
<?php
//Query 3 recent published post in descending order
$args = array( 'numberposts' => '3', 'order' => 'DESC','post_status' => 'publish' );
$recent_posts = wp_get_recent_posts( $args );
//Now lets do something with these posts
foreach( $recent_posts as $recent )
{
echo 'Post ID: '.$recent["ID"];
echo 'Post URL: '.get_permalink($recent["ID"]);
echo 'Post Title: '.$recent["post_title"];
//Do whatever else you please with this WordPress post
}
?>

WordPress Custom Taxonomies WP_Query

I'm trying to create a query where I create multiple categories (taxonomies) in a custom post type, and then on the homepage query based on specific which is working fine. Currently I have 3 taxonomies:
current-specials
meineke-difference
featured
I have already written code that pulls these. The problem I'm running into is that on the homepage it needs to only pull these posts when they are also attached to the "featured" taxonomy. So an example of standard logic for this would be:
if taxonomy = current-specials AND featured then success else fail
But what it's doing is pulling them all because the current code is OR, and I need AND
Thoughts? (code below)
<?php
$post_type = 'coupons';
$tax = 'coupons_category';
$tax_terms = get_terms($tax);
if ($tax_terms):
foreach ($tax_terms as $tax_term):
echo '<div id="'.$tax_term->slug.'" class="coupon-box '.$tax_term->slug.'">';
$args = array(
'post_type' => $post_type,
"$tax" => array($tax_term->slug, 'featured'),
'post_status' => 'publish',
'posts_per_page' => -1,
'caller_get_posts' => 1
);
$myQuery = null;
$myQuery = new WP_Query($args);
if($myQuery->have_posts()):
while ($myQuery->have_posts()) : $myQuery->the_post();
$price = get_field('price_image', $myQuery->ID);
$print = get_field('print', $myQuery->ID);
$product = get_field('product_box_image', $myQuery->ID);
$title = get_the_title();
$content = get_the_content();
echo '<div class="fourty9 left box center">';
echo '<h1>'.$title.'</h1>';
echo '<p class="center"><img src="'.$price.'" /></p>';
echo '<p>'.$content.'</p>';
echo '<p class="center">Print Coupon</p>';
echo '<p class="center"><img src="'.$product.'" alt="Filter"></p>';
echo '</div>';
endwhile;
endif;
echo '</div>';
wp_reset_query();
endforeach;
endif;
?>
You may try this (tax - use taxonomy slug. Deprecated as of Version 3.1 in favor of 'tax_query')
$args = array(
'post_type' => 'coupons',
'posts_per_page' => -1,
'caller_get_posts' => 1,
'tax_query' => array(
array(
'taxonomy' => 'coupons_category',
'field' => 'slug',
'terms' => array( 'current-specials', 'featured' ),
'operator' => 'AND'
)
)
);
$query = new WP_Query( $args );

Wordpress- Get Posts by Custom Field

I'm trying to make a Wordpress plugin for my blog that scans for posts that contain the custom field _videoembed. I've got everything made and it activates correctly but I receive a PHP error when I open up a page to test it out:
Fatal error: Call to a member function get_results() on a non-object in .../wp-content/plugins/youtubesubscription/videos.php on line 26.
Does anyone know enough about PHP to help me out? Here's my plugin code (pasted on pastebin because of size):
http://pastebin.com/uaEWjTn2
EDIT 1
I'm no longer getting any errors after inserting global $wpdb; but now nothing's showing up. Here's my updated code: http://pastebin.com/R2ZuEknY. Note, this code also incorporates auto YouTube thumbnails, which were obtained from a function that trims YouTube URLs to the IDs (link).
EDIT 2
Got it working, turns out all I needed to do was insert '_videoembed' as the 'meta_key' argument for a wp_query. Here's my working code below:
<?php
$args = array(
'meta_key' => '_videoembed',
'post_status' => 'publish',
'posts_per_page' => '' . $number . '',
'order' => 'date'
);
query_posts( $args );
while ( have_posts() ) : the_post(); ?>
<?php
global $post;
$VIDEOID = ytvideoID($post->ID);
?>
<li onClick="window.location.href='<?php the_permalink(); ?>'">
<?php
global $post;
$videoId = ytvideoID($post->ID);
$videoInfo = parseVideoEntry($videoId);
echo '<a href="'.get_permalink().'">';
echo '<div class="image">';
echo '<img src="http://img.youtube.com/vi/'.$VIDEOID.'/default.jpg">';
echo '<div id="time" style="position:absolute;z-index:9;bottom:2px;right:2px;font-size:10px;color:#fff;background:#000;padding:0px 2px;-webkit-border-radius: 4px;-moz-border-radius: 4px;border-radius: 4px;opacity:0.75;">'.hms($videoInfo->length).'</div>';
echo '</div>';
echo '<h4>'.get_the_title().'</h4>';
echo '<div id="description">';
echo '<div id"views"><h3>'.number_format($videoInfo->viewCount).' Views</h3></div>';
echo '<div class="singleauthor"><h3>by '.$videoInfo->author.'</h3></div>';
echo '</div>';
echo '</a>';
?>
</li>
<?php endwhile;
// Reset Query
wp_reset_query();
?>
you get the post by custom field using the meta_query.
$args= array(
'category_name' => 'courses',
'orderby' => 'menu_order',
'order' => 'ASC',
'meta_query' => array(
array(
'key' => 'front_page',
'value' => 'yes',
'compare' => 'LIKE',
))
);
$the_query = new WP_Query( $args );
please refer my tutorial for more details.
http://www.pearlbells.co.uk/filter-posts-custom-fields-wp_query/
You'll have to to add global $wpdb;
try replacing
function mbrecentvids()
{ ?>
<?php
with
function mbrecentvids()
{
global $wpdb;
It looks like you're missing a semi-colon on line 26.
I see:
$pageposts = $wpdb->get_results($querydetails, OBJECT_K)

Categories