-
Notifications
You must be signed in to change notification settings - Fork 217
Useful Functions and Queries
Imran Sayed edited this page Jul 30, 2021
·
4 revisions
get_post_type_archive_link( TCC_DEFAULT_POST_SLUG )
$args = [
'posts_per_page' => $number,
'post_type' => $post_type,
'no_found_rows' => true,
'update_post_meta_cache' => false,
'update_post_term_cache' => false,
'category__in' => [ 1, 2, 3 ],
'fields' => 'ids',
'meta_key' => 'featured',
'meta_value' => 'yes',
'meta_query' => [
'relation' => 'OR',
[
'compare' => 'NOT EXISTS',
'meta_key' => 'featured',
],
[
'meta_key' => 'featured',
'meta_value' => 'no',
],
],
];
$my_query = new \WP_Query( $args );
- Loop with custom query
if ( $my_query->have_posts() ) :
while ( $my_query->have_posts() ) :
$my_query->the_post();
<article id="post-<?php the_ID(); ?>" class="related-post">
<?php
if ( has_post_thumbnail() ) {
the_post_thumbnail(
'medium',
[ 'class' => 'post-img' ]
);
} else {
?>
<img src="https://via.placeholder.com/520x328?text=Insight" width="520" height="328"
loading="lazy" class="post-img"
alt="<?php printf( 'article-%s', esc_html( $the_post_id ) ); ?>">
<?php
}
?>
<div class="related-post-text text-left">
<?php the_title( '<h4 class="related-post-title"><a href="' . esc_url( get_permalink() ) . '" rel="bookmark">', '</a></h4>' ); ?>
<?php the_excerpt(); ?>
</div>
</article>
/**
* Get the First Term
*
* @param int $the_post_ID Post ID.
* @param string $taxonomy Taxonomy.
* @param bool $only_slug If set to false entire term object is returned, else just the slug ( defaults to true )
*
* @return string|\WP_Term Term slug or object, empty string on failure.
*/
function get_first_term_by_post_id( int $the_post_ID, string $taxonomy, bool $only_slug = true ) {
if ( empty( $the_post_ID ) || empty( $taxonomy ) ) {
return '';
}
$terms = get_the_terms( $the_post_ID, $taxonomy );
if ( empty( $terms ) || is_wp_error( $terms ) ){
return '';
}
// Get the first term
$term = array_shift( $terms );
return $only_slug ? $term->slug : $term;
}