Sunday, June 21, 2015

Wordpress loop based on the meta value

Usually we add additional meta fields to post or post types. Wordpress provides very flexible way to get the post/post types based on the meta fields and the values.

The get_posts and the WP_query follow the same structure for accepting arguments and the args mentioned below could be used for both of them.

If we want to display the post/post type based on a particular value of a meta key we could use the following code

1:  $args = array(
2:  'post_type' => 'post',//or the slug of your post type
3:  'meta_key' => 'the_meta_field_name',
4:  'meta_value' => 'the_meta_field_value',
5: );

The problem with the above approach is there is no option to add one more meta field. A more desirable or if you want a more complex result to display then the meta_query is better option.

The meta_query option gives option to add multiple options based on the multiple meta fields associated with the post or post type.


1:  $args = array(
2:  'post_type' => 'post',//or slug of the post type
7:  'meta_query' => array(
8:   array(
9:      'key'     => 'the_meta_field_name',
10:      'value'   => 'the_meta_field_value',
11:      'compare' => '='
12:   ),
13:   array(
14:      'key'     => 'the_meta_field_another',
15:      'value'   => '"%the_meta_field_another_value"',
16:      'compare' => 'LIKE'
17:   ),
18:   )
19:  );

The the above array could be used with both get_posts and WP_query as per your need.

Tuesday, June 16, 2015

Wordpress post showing an old featured image even though there are no image associated with post

I am using wordpress 4.2 and I faced an issue in which an old featured image was displayed . I had removed the featured image and also made sure that there was no image in the post content also.  Still an old image which was associated to the post was displayed in the listing page.

The theme that I was using a fallback so the image associated to the post was being displayed. I did not want to modify the theme files. I logged in to the database and then found the image that was appearing in the post. The data for that image was available in 'wp_posts' table. In the table there is a column called 'post_parent'. The value for this column for the particular image was the id for the post which was displaying the old image. I updated that to zero and my issue was solved.

The post parent for this image was set to this particular post because while setting the post featured image, the image was uploaded through that interface.

So hope this would help someone where they face this issue of a non associated image is coming for a post.