Skip to content

Instantly share code, notes, and snippets.

@pixelbart
Created December 21, 2019 17:47
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save pixelbart/649944849bb52b519762dc7c48da18da to your computer and use it in GitHub Desktop.
Save pixelbart/649944849bb52b519762dc7c48da18da to your computer and use it in GitHub Desktop.
Helpful: Get all pro posts order by pro count
<?php
/**
* Shortcode for displaying all posts with pro, order by pro count
*/
function helpful_pro_shortcode() {
global $wpdb;
$table_name = $wpdb->prefix . 'helpful';
/**
* Select all pro posts
*/
$sql = "SELECT DISTINCT post_id FROM $table_name WHERE pro = 1";
$rows = $wpdb->get_results( $sql );
$items = [];
foreach ( $rows as $row ) :
/**
* Get pro count
*/
$sql = "SELECT COUNT(*) FROM $table_name WHERE post_id = %d AND pro = 1";
$sql = $wpdb->prepare( $sql, $row->post_id );
$count = $wpdb->get_var( $sql );
$items[] = [
'post_id' => $row->post_id,
'count' => $count,
];
endforeach;
/**
* Sort by count
*/
usort( $items, 'sort_by_count' );
$output = '<ul>';
/**
* Loop trough items and create a linked post list
*/
foreach ( $items as $item ) :
$output .= sprintf(
'<li><a href="%1$s">%2$s</a> (%3$d)</li>',
get_the_permalink( $item['post_id'] ),
get_the_title( $item['post_id'] ),
$item['count']
);
endforeach;
$output .= '</ul>';
return $output;
}
/**
* Callable for usort (sort by count)
*/
function sort_by_count($a, $b) {
return $b['count'] - $a['count'];
}
/**
* Register shortcode
*/
add_shortcode( 'helpful_pro', 'helpful_pro_shortcode' );
/**
* Usage: [helpful_pro] inside post content
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment