Wordpress- Get Posts by Custom Field - php

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)

Related

Function to display Images based on category on WordPress

Hi There I am writing some PHP code to get some images assigned a custom category given to them via a WordPress Plugin which allows me to assign category's to individual images. The code is below is what I have at the moment
function showFooterImages() {
$footerImagesArray = array(
'post_type' => 'attachment',
'post_status' => 'published',
'posts_per_page' => 4,
'orderby' => 'rand',
'category' => 'footer-images',
);
// Query to get footer images
$footerImagesQuery = new WP_Query( $footerImagesArray );
// The Loop
if ( $the_query-> have_posts() ) {
echo '<ul>';
while ( $footerImagesQuery->have_posts() ) {
$footerImagesQuery->the_post();
echo '<li>' . get_the_post() . '</li>';
}
echo '</ul>';
}
/* Restore original Post Data */
wp_reset_postdata();
}
If I replace the
echo '<li>' . get_the_post() . '</li>';
with the following
echo "<p> this is a test </p>";
I do get 4 lines of text from the echo showing it is working and if i change the posts_per_page to 6 for example I then get 6 however I am struggling to get the images even displaying and any assistance would be greatly appreciated.
Was able to get this working with some advice from CBroe for some reason cant tag him but he pointed me in the right direction
Got this working by doing the following
function showFooterImages() {
$footerImagesArray = array(
'post_type' => 'attachment',
'post_status' => 'published',
'posts_per_page' => 4,
'orderby' => 'rand',
'category' => 'footer-images',
);
// Query to get footer images
$footerImagesQuery = new WP_Query( $footerImagesArray );
$images = array();
foreach ( $footerImagesQuery->posts as $image ) {
?>
<img src="<?php echo wp_get_attachment_url( $image->ID ) ; ?>">
<?php
}
/* Restore original Post Data */
wp_reset_postdata();
}

get_template_part inside get_posts()

Im trying to show a list of posts including their Title & Image on a post. Im using the get_posts() function with an array to filter the posts. I know that $template_loader->get_template_part( 'content-listing-image'); get the post image, but when I use it on the output it shows me the image of the current post, not the filtered ones ($evento)
This is my code:
<?php
$args = array(
'author' => $post->post_author,
'order' => 'ASC',
'posts_per_page' => -1,
'meta_query' => array(
array(
'key' => '_listing_type',
'value' => 'event'
)
)
);
$eventos = get_posts( $args );
foreach ( $eventos as $evento ) {
$template_loader = new Listeo_Core_Template_Loader;
$output .= '<div> '.$template_loader->get_template_part( 'content-listing-image').' '.$evento->post_title.'</div>';
}
if(!empty($eventos)) : ?>
<div id="listing-eventosartista" class="listing-section">
<h3 class="listing-desc-headline margin-top-60 margin-bottom-30"><?php esc_html_e('Eventos','listeo_core'); ?></h3>
<div class="single-item">
<?php echo $output; ?>
</div>
</div>
<?php endif ?>
I want to show the corresponding image to each $evento (post).
Hope yoy can help me!
You can use get_the_post_thumbnail(), like this
$output .= 'ID ).'" target="_blank"> '.get_the_post_thumbnail( $evento->ID).' '.$evento->post_title.'';

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 query only one post in wordpress widget

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

Wordpress Notice: Trying to get property of non-object

I have a custom post type set up on my blog and a special page for the taxonomy. On the taxonomy page I am getting the below error. Can anyone give me some tips on how to resolve this error?
The page loads fine and works as I would expect. But I get the below error if I have debug set to true. I would like to resolve this. I pasted the cost from the loop which is run two time on the page with different criteria.
Notice: Trying to get property of non-object in /home3/ans/public_html/wp-includes/post-template.php on line 29
Code:
<?php
query_single('dealers', 'publish', '1', $taxtype, $value);
?>
<?php if (have_posts()) : ?>
<?php while (have_posts()) : the_post(); ?>
<?php
$address=get_post_meta($post->ID, 'wpcf-street_address', TRUE);
$city=get_post_meta($post->ID, 'wpcf-city', TRUE);
$state=get_post_meta($post->ID, 'wpcf-state_abbreviation', TRUE);
$zip=get_post_meta($post->ID, 'wpcf-zip_code', TRUE);
$phone=get_post_meta($post->ID, 'wpcf-phone_number', TRUE);
$paid=get_post_meta($post->ID, 'wpcf-paid', TRUE);
$post_id=get_the_ID();
get_each_dealer_brand($post_id);?>
<?php
echo "<ul class=\"ullisting\">";
if($paid==1)
{
echo "<li><p class=\"plisting\"><strong>";the_title();echo "</strong></p></li>";
echo "<li><p class=\"plisting\">$address | $city, $state $zip</p></li>";
echo "<li><p class=\"plisting\">P: $phone</p></li>";
echo "<li><p class=\"listing\"><span><small>$brands_list</small></span></p></li>";
}
echo "</ul>";
?>
<?php endwhile; ?>
<?php
wp_reset_query();
wp_reset_postdata();
unset($brands_list);
?>
This is the function referenced above:
function query_single($posttype, $poststatus, $paidvalue, $taxtype, $value) {
global $wp_query;
$wp_query = new WP_Query();
$args = array(
'post_type' => $posttype,
'post_status' => array($poststatus),
'orderby' => 'rand',
'posts_per_page' => 20,
'meta_query' => array(
array(
'key' => 'wpcf-paid',
'value' => array($paidvalue),
'compare' => 'IN',
)
),
'tax_query' => array(
array(
'taxonomy' => $taxtype,
'field' => 'slug',
'terms' => $value
)
)
);
return $wp_query->query($args);
}
This error will arise when you try to access posts inside your theme,
in page-template.php we have,
function get_the_ID() {
return get_post()->ID;
}
Whenever we are accessing posts we need to check the below condition and make sure it works as default, because we may not use wp_reset_postdata(); all the time so,
global $post;
//check if post is object otherwise you're not in singular post
if( !is_object($post) )
return;
//If Object
$somevariable = get_post_meta(get_the_ID(), $something->get_the_id(), TRUE);
Hope this helps. Thanks.
You can try to execute your commands within ACTION (because wordpress is already loaded normally at that time).
like this:
ADD_ACTION('init','your_function');
function your_function(){
YOUR CODES HEREEEEEEEEEEE............
}

Categories