Skip to content

Instantly share code, notes, and snippets.

@harisrozak
Last active October 9, 2017 09:30
Show Gist options
  • Save harisrozak/1520974de004a48c515b to your computer and use it in GitHub Desktop.
Save harisrozak/1520974de004a48c515b to your computer and use it in GitHub Desktop.
WordPress :: Sample WP Query
<?php
$args = array(
'post_type' => 'product',
'posts_per_page' => -1, // -1 mean show all data
'post_status' => 'publish',
// with multiple taxonomy, if not just get rid the relation and put only one taxonomy array
'tax_query' => array(
'relation' => 'AND',
array(
'taxonomy' => 'color',
'field' => 'slug',
'terms' => array( 'white', 'gray' ),
),
array(
'taxonomy' => 'type',
'field' => 'id',
'terms' => array( 103, 115, 206 ),
'operator' => 'NOT IN',
),
),
// select that only have this meta
'meta_key' => 'brand',
'meta_value' => 'adidas',
// pagination, based on posts_per_page option
'paged' => 1
);
$the_query = new WP_Query($args);
$total_number = $the_query->found_posts; //total without limit
$displayed_number = $the_query->post_count; //total with limit
// loop
while ($the_query->have_posts()) : $the_query->the_post();
if(! has_post_format() && has_post_thumbnail()) {
// size: thumbnail, medium, large or full
$thumb = wp_get_attachment_image_src(get_post_thumbnail_id($post->ID), 'large');
$url = $thumb[0];
$width = $thumb[1];
?>
<a href="<?php the_permalink() ?>">
<img alt="<?php the_title() ?>" src="<?php echo $url ?>">
</a>
<?php
}
// or just do the_post_thumbnail
the_post_thumbnail('post-thumbnail', array('class' => 'img-responsive', 'alt' => get_the_title()))
the_title(); // post title
the_content(); // post content
the_terms(get_the_ID(), 'category', 'Categories: ', ', '); // categories
// terms without link
$terms = get_the_terms(get_the_ID(), 'category');
if (! is_wp_error($terms)) {
$term_links = wp_list_pluck($terms, 'name');
$term_text = implode(", ", $term_links);
echo "Categories: $term_text";
}
else {
echo "Categories: Uncategorized";
}
endwhile;
wp_reset_postdata();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment