Skip to content

Instantly share code, notes, and snippets.

@ChrisFlannagan
Last active December 13, 2016 11:21
Show Gist options
  • Save ChrisFlannagan/a6f63a02ea16268a25bc5d386e9ac63a to your computer and use it in GitHub Desktop.
Save ChrisFlannagan/a6f63a02ea16268a25bc5d386e9ac63a to your computer and use it in GitHub Desktop.
<?php
public function __construct() {
add_action( 'rest_api_init', function() {
register_rest_route( SITE_PREFIX . '/v1', '/yoastprimary/(?P<id>\d+)', array(
'methods' => 'GET',
'callback' => array( $this, 'get_posts_by_primary_cat' ),
) );
} );
}
<?php
public function get_posts_by_primary_cat( $data ) {
$child_cats = get_categories( array( 'parent' => $data['id'] ) );
$children = array();
foreach( $child_cats as $child ) {
$children[] = (String)$child->term_id;
}
$children[] = $data['id'];
$posts = new WP_Query(
array(
'post_status' => 'publish',
'meta_query' => array(
array(
'key' => '_yoast_wpseo_primary_category',
'value' => $children,
'compare' => 'IN',
),
)
)
);
$return = array();
while( $posts->have_posts() ) {
$posts->the_post();
$return_post = array();
if ( ! get_the_post_thumbnail_url() ) {
// I set this constant in my theme's function.php
$return_post['thumb'] = CHILD_THEME_URI . '/assets/imgs/default-thumbnail.jpg';
} else {
$return_post['thumb'] = get_the_post_thumbnail_url();
}
$return_post['link'] = get_the_permalink();
$return_post['title'] = get_the_title();
$return_post['time'] = get_the_time( 'F d, Y' );
$return[] = $return_post;
}
return $return;
}
<?php
class Rest_Api_Posts_By_Primary_Category {
public function __construct() {
add_action( 'rest_api_init', function() {
register_rest_route( SITE_PREFIX . '/v1', '/yoastprimary/(?P<id>\d+)', array(
'methods' => 'GET',
'callback' => array( $this, 'get_posts_by_primary_cat' ),
) );
} );
}
public function get_posts_by_primary_cat( $data ) {
$child_cats = get_categories( array( 'parent' => $data['id'] ) );
$children = array();
foreach( $child_cats as $child ) {
$children[] = (String)$child->term_id;
}
$children[] = $data['id'];
$posts = new WP_Query(
array(
'post_status' => 'publish',
'meta_query' => array(
array(
'key' => '_yoast_wpseo_primary_category',
'value' => $children,
'compare' => 'IN',
),
)
)
);
$return = array();
while( $posts->have_posts() ) {
$posts->the_post();
$return_post = array();
if ( ! get_the_post_thumbnail_url() ) {
// I set this constant in my theme's function.php
$return_post['thumb'] = CHILD_THEME_URI . '/assets/imgs/default-thumbnail.jpg';
} else {
$return_post['thumb'] = get_the_post_thumbnail_url();
}
$return_post['link'] = get_the_permalink();
$return_post['title'] = get_the_title();
$return_post['time'] = get_the_time( 'F d, Y' );
$return[] = $return_post;
}
return $return;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment