I run a wordpress multisite on ayp.no and I am trying to figure out a way to present all subsites with logos and recent posts from all blogs, I know there is a wpmudev premium plugin for this, but I was hoping there was some coding i could do myself (well, obviously not myself, but at least ask here and see)..
First, we need a function to get all sites, with that at hand we iterate thought the array of sites and pull the information with wp_get_recent_posts() (which is a customized version of get_posts()).
Use the following as a Must Use plugin, so the function b5f_print_recent_posts() is available throughout the network:
<?php
/**
* Plugin Name: Recent Network Posts
* Plugin URI: http://stackoverflow.com/q/23713801/1287812
* Description: Creates a function that lists recent posts from all sites of the network. Call it in another plugins or themes.
* Author: brasofilo
*/
/**
* Iterates throught all sites of the network and grab the recent posts
*/
function b5f_print_recent_posts()
{
$blogs = b5f_get_blog_list( 0, 'all', true );
$current_blog_id = get_current_blog_id();
foreach( $blogs as $blog )
{
switch_to_blog( $blog[ 'blog_id' ] );
echo '<h3>' . $blog['name'] . ' - ' . $blog['domain'] . ' - ' . $blog['desc'] . '</h3>';
$posts = wp_get_recent_posts( array(), OBJECT );
if( $posts )
{
foreach( $posts as $post )
{
printf(
'- %s<br />',
get_permalink( $post->ID ),
$post->post_title
);
}
}
}
switch_to_blog( $current_blog_id );
}
/**
* Returns an array of arrays containing information about each public blog
* hosted on this WPMU install.
*
* Only blogs marked as public and flagged as safe (mature flag off) are returned.
*
* #author Frank Bueltge
*
* #param Integer The first blog to return in the array.
* #param Integer The number of blogs to return in the array (thus the size of the array).
* Setting this to string 'all' returns all blogs from $start
* #param Boolean Get also Postcount for each blog, default is False for a better performance
* #param Integer Time until expiration in seconds, default 86400s (1day)
* #return Array Returns an array of arrays each representing a blog.
* Details are represented in the following format:
* blog_id (integer) ID of blog detailed.
* domain (string) Domain used to access this blog.
* path (string) Path used to access this blog.
* postcount (integer) The number of posts in this blog.
* name (string) Blog name.
* desc (string) Blog description.
*/
function b5f_get_blog_list( $start = 0, $num = 10, $details = FALSE, $expires = 86400 ) {
// get blog list from cache
$blogs = get_site_transient( 'multisite_blog_list' );
// For debugging purpose
if ( defined( 'WP_DEBUG' ) && WP_DEBUG )
$blogs = FALSE;
if ( FALSE === $blogs ) {
global $wpdb;
// add limit for select
if ( 'all' === $num )
$limit = '';
else
$limit = "LIMIT $start, $num";
$blogs = $wpdb->get_results(
$wpdb->prepare( "
SELECT blog_id, domain, path
FROM $wpdb->blogs
WHERE site_id = %d
AND public = '1'
AND archived = '0'
AND mature = '0'
AND spam = '0'
AND deleted = '0'
ORDER BY registered ASC
$limit
", $wpdb->siteid ),
ARRAY_A );
// Set the Transient cache
set_site_transient( 'multisite_blog_list', $blogs, $expires );
}
// only if usable, set via var
if ( TRUE === $details ) {
$blog_list = get_site_transient( 'multisite_blog_list_details' );
// For debugging purpose
if ( defined( 'WP_DEBUG' ) && WP_DEBUG )
$blog_list = FALSE;
if ( FALSE === $blog_list ) {
global $wpdb;
$current_blog_id = get_current_blog_id();
foreach ( (array) $blogs as $details ) {
$blog_list[ $details['blog_id'] ] = $details;
$blog_list[ $details['blog_id'] ]['postcount'] = $wpdb->get_var( "
SELECT COUNT(ID)
FROM " . $wpdb->get_blog_prefix( $details['blog_id'] ). "posts
WHERE post_status='publish'
AND post_type='page'"
);
switch_to_blog( $details['blog_id'] );
$blog_list[ $details['blog_id'] ]['name'] = get_blog_details()->blogname;
$blog_list[ $details['blog_id'] ]['desc'] = get_bloginfo( 'description' );
}
switch_to_blog( $current_blog_id );
// Set the Transient cache
set_site_transient( 'multisite_blog_list_details', $blog_list, $expires );
}
unset( $blogs );
$blogs = $blog_list;
}
if ( FALSE === is_array( $blogs ) )
return array();
return $blogs;
}
You can add the following network dashboard widget in the previous plugin to test it out:
add_action( 'wp_network_dashboard_setup', 'dashboard_setup_so_23713801' );
function dashboard_setup_so_23713801()
{
wp_add_dashboard_widget( 'widget_so_23713801', __( 'Test widget' ), 'print_widget_so_23713801' );
}
function print_widget_so_23713801()
{
b5f_print_recent_posts();
}
Related
I am trying to create a shortcode that returns a list of doctors matching a specialty.
So far, I can get the base shortcode to return the contents of the entire table, but I can't get it to query based on an attribute string.
Here's what I have:
// Add Shortcode
function list_docs( $atts ) {
// Attributes
$atts = shortcode_atts(
array(
'specialty' => '',
),
$atts,
'doctors'
);
global $wpdb;
$specialty = $atts['specialty'];
$specget = $wpdb->prepare("SELECT * FROM doctors WHERE specialty = '%s'", $specialty);
$specresults = $wpdb->get_results($specget);
foreach($specresults as $details) {
echo $details;
}
}
add_shortcode( 'doctors', 'list_docs' );
If I query the database directly with:
SELECT * FROM `doctors` WHERE `specialty` = 'cardiology'
I get the expected result.
I'm trying to call it with [doctors specialty="cardiology"] (I've tried double and single quotes) on the WordPress page.
Right now, I don't know what I don't know. I'm not sure if I've entered something wrong, have a typo, or am missing a line of code. Any assistance would be terrific.
May be problem is not with the query at all assuming that your table name is indeed doctors( & not wp_doctors or something like that )
$specresults will contain an array of objects. Let's say your doctors table has name column, then below changes may work for you.
function list_docs( $atts ) {
// Attributes
$atts = shortcode_atts(
array(
'specialty' => '',
),
$atts,
'doctors'
);
global $wpdb;
$specialty = $atts['specialty'];
$specget = $wpdb->prepare( 'SELECT * FROM doctors WHERE specialty = %s', $specialty );
$specresults = $wpdb->get_results( $specget );
if ( $specresults ) {
$doctor_names = array_map(
function( $doctor_object ) {
return $doctor_object->name;
},
$specresults
);
return implode( ', ', $doctor_names );
}
return '';
}
add_shortcode( 'doctors', 'list_docs' );
Couple of things to keep in mind:-
Shortcodes should always return & not echo directly.
Query only for required data from the database as far as possible instead of doing *
If you are going to need only one column, prefer using get_col method on $wpdb instead of get_results.
Please try with this -
function list_docs( $atts ) {
global $wpdb;
$specialty = $atts['specialty'];
$specget = $wpdb->prepare("SELECT * FROM doctors WHERE specialty = %s", $specialty);
$specresults = $wpdb->get_results($specget);
foreach($specresults as $details) {
echo $details;
}
}
add_shortcode( 'doctors', 'list_docs' );
I have implemented WP List Table to display my custom data. Data are displaying correctly. I have also implemented Sorting and Pagination
But Searching functionality not working.
When I enter values in textbox and submit it then it's redirecting me to ...wp-admin/edit.php
I have followed tutorials and has same code as they have.
This code is displaying Data and searchbox
$table = new AngellEYE_Give_When_Givers_Table();
$table->prepare_items();
echo '<form method="post">';
echo '<input type="hidden" name="page" value="ttest_list_table">';
$table->search_box('Search', 'givers_search_id');
$table->display();
echo '</form>';
Here is my Class that extends WP ListTable and Displays data.
class AngellEYE_Give_When_Givers_Table extends WP_List_Table {
public function __construct() {
parent::__construct( [
'singular' => __( 'Giver', 'angelleye_give_when' ), //singular name of the listed records
'plural' => __( 'Givers', 'angelleye_give_when' ), //plural name of the listed records
'ajax' => false //should this table support ajax?
] );
}
/**
* Hook in methods
* #since 1.0.0
* #access static
*/
public static function init() {
// add_action for the class
}
/**
* Retrieve givers’s data from the database
*
* #param int $per_page
* #param int $page_number
*
* #return mixed
*/
public static function get_givers( $per_page = 5, $page_number = 1 ) {
global $wpdb;
$sql = "SELECT
(SELECT usrmeta.meta_value from wp_usermeta as usrmeta where usrmeta.user_id = um.user_id and usrmeta.meta_key = 'give_when_gec_billing_agreement_id') as BillingAgreement,
um.meta_value As PayPalEmail,
um.user_id,
u.display_name as DisplayName,
pm.meta_value as amount,
(SELECT usrmeta.meta_value from wp_usermeta as usrmeta where usrmeta.user_id = um.user_id and usrmeta.meta_key = 'give_when_gec_payer_id') as PayPalPayerID
FROM `wp_posts` as p
join `wp_users` as u on p.post_author = u.ID
join `wp_postmeta` as pm on pm.post_id = p.ID
left join wp_usermeta as um on um.user_id=u.ID
WHERE pm.`post_id` IN (SELECT post_id FROM wp_postmeta WHERE `meta_value` = '{$_REQUEST['post']}' AND `meta_key` = 'give_when_signup_wp_goal_id')
group by u.ID";
if(isset($_REQUEST['orderby'])){
if(!empty($_REQUEST['orderby'])){
$sql .= ' ORDER BY '.$_REQUEST['orderby'];
}
else{
/* by default we will add post time/post type time order by */
$sql .= ' ORDER BY PayPalEmail ';
}
$sql .= ! empty( $_REQUEST['order'] ) ? ' ' . esc_sql( $_REQUEST['order'] ) : ' ASC';
}
else{
/* by default we will add post time/post type time order by */
$sql .= ' ORDER BY PayPalEmail ';
$sql .= ! empty( $_REQUEST['order'] ) ? ' ' . esc_sql( $_REQUEST['order'] ) : ' ASC';
}
$sql .= " LIMIT $per_page";
$sql .= ' OFFSET ' . ( $page_number - 1 ) * $per_page;
$result_array = $wpdb->get_results( $sql, 'ARRAY_A' );
return $result_array;
}
/**
* Delete a customer record.
*
* #param int $id customer ID
*/
public static function delete_customer( $id ) {
global $wpdb;
$wpdb->delete(
"{$wpdb->prefix}customers",
[ 'ID' => $id ],
[ '%d' ]
);
}
/**
* Returns the count of records in the database.
*
* #return null|string
*/
public static function record_count() {
global $wpdb;
$sql = "SELECT
(SELECT usrmeta.meta_value from wp_usermeta as usrmeta where usrmeta.user_id = um.user_id and usrmeta.meta_key = 'give_when_gec_billing_agreement_id') as BillingAgreement,
um.meta_value As PayPalEmail,
um.user_id,
pm.meta_value as amount,
(SELECT usrmeta.meta_value from wp_usermeta as usrmeta where usrmeta.user_id = um.user_id and usrmeta.meta_key = 'give_when_gec_payer_id') as PayPalPayerID
FROM `wp_posts` as p
join `wp_users` as u on p.post_author = u.ID
join `wp_postmeta` as pm on pm.post_id = p.ID
left join wp_usermeta as um on um.user_id=u.ID
WHERE pm.`post_id` IN (SELECT post_id FROM wp_postmeta WHERE `meta_value` = '{$_REQUEST['post']}' AND `meta_key` = 'give_when_signup_wp_goal_id')
group by u.ID";
$wpdb->get_results( $sql, 'ARRAY_A' );
return $wpdb->num_rows;
}
/** Text displayed when no giver's data is available */
public function no_items() {
_e( 'No Givers avaliable.', 'angelleye_give_when' );
}
/**
* Method for name column
*
* #param array $item an array of DB data
*
* #return string
*/
public function column_name( $item ) {
//
// // create a nonce
// $delete_nonce = wp_create_nonce( 'sp_delete_customer' );
//
// $title = '<strong>' . $item['name'] . '</strong>';
//
// $actions = [
// 'delete' => sprintf( 'Delete')
// ];
//
// return $title . $this->row_actions( $actions );
}
/**
* Render a column when no column specific method exists.
*
* #param array $item
* #param string $column_name
*
* #return mixed
*/
public function column_default( $item, $column_name ) {
switch ( $column_name ) {
case 'BillingAgreement':
echo $item['BillingAgreement'];
break;
case 'PayPalEmail':
echo $item['PayPalEmail'];
break;
case 'amount' :
echo $item['amount'];
break;
case 'PayPalPayerID' :
echo $item['PayPalPayerID'];
break;
case 'DisplayName' :
echo $item['DisplayName'];
break;
}
}
/**
* Render the bulk edit checkbox
*
* #param array $item
*
* #return string
*/
public function column_cb( $item ) {
return sprintf(
'<input type="checkbox" name="bulk-delete[]" value="%s" />', $item['user_id']
);
}
/**
* Associative array of columns
*
* #return array
*/
public function get_columns() {
$columns = [
'cb' => '<input type="checkbox" />',
'BillingAgreement'=> __( 'Billing Agreement ID', 'angelleye_give_when' ),
'DisplayName' => __( 'Name', 'angelleye_give_when' ),
'PayPalEmail' => __( 'Givers', 'angelleye_give_when' ),
'amount' => __( 'Amount', 'angelleye_give_when' ),
'PayPalPayerID' => __('PayPal Payer ID','angelleye_give_when')
];
return $columns;
}
/**
* Columns to make sortable.
*
* #return array
*/
public function get_sortable_columns() {
$sortable_columns = array(
'BillingAgreement' => array( 'BillingAgreement', true ),
'DisplayName' => array('DisplayName',true),
'PayPalEmail' => array( 'PayPalEmail', true ),
'amount' => array( 'amount', true ),
'PayPalPayerID' => array( 'PayPalPayerID', true )
);
return $sortable_columns;
}
/**
* Returns an associative array containing the bulk action
*
* #return array
*/
public function get_bulk_actions() {
$actions = [
'bulk-delete' => 'Delete'
];
return $actions;
}
/**
* Handles data query and filter, sorting, and pagination.
*/
public function prepare_items() {
$columns = $this->get_columns();
$hidden = array();
$sortable = $this->get_sortable_columns();
$this->_column_headers = array($columns, $hidden, $sortable);
/** Process bulk action */
$this->process_bulk_action();
$per_page = $this->get_items_per_page( 'givers_per_page', 5 );
$current_page = $this->get_pagenum();
$total_items = self::record_count();
$this->set_pagination_args( [
'total_items' => $total_items, //WE have to calculate the total number of items
'per_page' => $per_page //WE have to determine how many items to show on a page
] );
$this->items = self::get_givers( $per_page, $current_page );
}
public function process_bulk_action() {
//Detect when a bulk action is being triggered...
if ( 'delete' === $this->current_action() ) {
// In our file that handles the request, verify the nonce.
$nonce = esc_attr( $_REQUEST['_wpnonce'] );
if ( ! wp_verify_nonce( $nonce, 'sp_delete_customer' ) ) {
die( 'Go get a life script kiddies' );
}
else {
self::delete_customer( absint( $_GET['customer'] ) );
wp_redirect( esc_url( add_query_arg() ) );
exit;
}
}
// If the delete bulk action is triggered
if ( ( isset( $_POST['action'] ) && $_POST['action'] == 'bulk-delete' )
|| ( isset( $_POST['action2'] ) && $_POST['action2'] == 'bulk-delete' )
) {
$delete_ids = esc_sql( $_POST['bulk-delete'] );
// loop over the array of record IDs and delete them
foreach ( $delete_ids as $id ) {
self::delete_customer( $id );
}
wp_redirect( esc_url( add_query_arg() ) );
exit;
}
}
}
AngellEYE_Give_When_Givers_Table::init();
Any good way how can I fix that ?
Any information on this would be greatly appreciated. Thanks!
I have a custom post type that has a bunch of posts all formatted like so
Artist - Song Title
for example
The Smashing Pumpkins - Quiet
I am trying to put 'Artist' in a variable $artist and 'Song Title' in a variable $song
$artistsong = get_the_title();
$songeach = explode("-", $artistsong);
$artist = $songeach[0];
$song = $songeach[1];
But this does not work. Echo-ing $artist gets the full title
The Smashing Pumpkins - Quiet
and echoing $song does not output anything
This works if I am just starting from plaintext, but not with 'get_the_title()'
$song = "The Smashing Pumpkins - Quiet";
$songeach = explode("-", $song);
$artist = trim($songeach[0]);
$song = trim($songeach[1]);
echo $artist;
//echos 'The Smashing Pumpkins'
echo $song;
//echos 'Quiet'
Is there another way to put the full title into a variable initially other than get_the_title() which does not seem to be working for me, or am I missing something else?
Add this code to your functions.php
function get_the_title_keep_hyphen( $post = 0 ) {
$post = get_post( $post );
$title = isset( $post->post_title ) ? $post->post_title : '';
$id = isset( $post->ID ) ? $post->ID : 0;
if ( ! is_admin() ) {
if ( ! empty( $post->post_password ) ) {
/**
* Filter the text prepended to the post title for protected posts.
*
* The filter is only applied on the front end.
*
* #since 2.8.0
*
* #param string $prepend Text displayed before the post title.
* Default 'Protected: %s'.
* #param WP_Post $post Current post object.
*/
$protected_title_format = apply_filters( 'protected_title_format', __( 'Protected: %s' ), $post );
$title = sprintf( $protected_title_format, $title );
} elseif ( isset( $post->post_status ) && 'private' == $post->post_status ) {
/**
* Filter the text prepended to the post title of private posts.
*
* The filter is only applied on the front end.
*
* #since 2.8.0
*
* #param string $prepend Text displayed before the post title.
* Default 'Private: %s'.
* #param WP_Post $post Current post object.
*/
$private_title_format = apply_filters( 'private_title_format', __( 'Private: %s' ), $post );
$title = sprintf( $private_title_format, $title );
}
}
/**
* Filter the post title.
*
* #since 0.71
*
* #param string $title The post title.
* #param int $id The post ID.
*/
return $title;
}
And use this code in your single.php
$artistsong = get_the_title_keep_hyphen();
$songeach = explode(" - ", $artistsong);
$artist = $songeach[0];
$song = $songeach[1];
See the last line
I change from return apply_filters( 'the_title', $title, $id ); to return $title;
Because apply_filters function change the hyphen from - => –.
It's because of the dash symbol.
Try $songeach = explode("P", $artistsong); and you'll see what I mean. You could try a different character between artist and song title - although probably not ideal.
I'm getting the following error in my wordpress dashboard which correlates to a piece of code i've written, however I'm not sure how to fix the error:
Notice: Undefined index: draft in /home/sites/samskirrow.com/public_html/skizzar-test/wp-content/mu-plugins/skizzar-dashboard.php on line 331
Here is the code it's referring to:
/******************************************************************
/* REMOVE BRACKETS AROUND PAGE COUNTS
/******************************************************************/
foreach( array( 'edit-post', 'edit-page', 'edit-movie', 'upload' ) as $hook )
add_filter( "views_$hook" , 'wpse_30331_custom_view_count', 10, 1);
function wpse_30331_custom_view_count( $views )
{
global $current_screen;
switch( $current_screen->id )
{
case 'edit-post':
$views = wpse_30331_manipulate_views( 'post', $views );
break;
case 'edit-page':
$views = wpse_30331_manipulate_views( 'page', $views );
break;
case 'edit-movie':
$views = wpse_30331_manipulate_views( 'movie', $views );
break;
case 'upload':
$views = wpse_30331_manipulate_views( 'attachment', $views );
break;
}
return $views;
}
function wpse_30331_manipulate_views( $what, $views )
{
global $user_ID, $wpdb;
/*
* This is not working for me, 'artist' and 'administrator' are passing this condition (?)
*/
if ( !current_user_can('artist') )
return $views;
/*
* This needs refining, and maybe a better method
* e.g. Attachments have completely different counts
*/
$total = $wpdb->get_var("SELECT COUNT(*) FROM $wpdb->posts WHERE (post_status = 'publish' OR post_status = 'draft' OR post_status = 'pending') AND (post_author = '$user_ID' AND post_type = '$what' ) ");
$publish = $wpdb->get_var("SELECT COUNT(*) FROM $wpdb->posts WHERE post_status = 'publish' AND post_author = '$user_ID' AND post_type = '$what' ");
$draft = $wpdb->get_var("SELECT COUNT(*) FROM $wpdb->posts WHERE post_status = 'draft' AND post_author = '$user_ID' AND post_type = '$what' ");
$pending = $wpdb->get_var("SELECT COUNT(*) FROM $wpdb->posts WHERE post_status = 'pending' AND post_author = '$user_ID' AND post_type = '$what' ");
$trash = $wpdb->get_var("SELECT COUNT(*) FROM $wpdb->posts WHERE post_status = 'trash' AND post_author = '$user_ID' AND post_type = '$what' ");
/*
* Only tested with Posts/Pages
* - there are moments where Draft and Pending shouldn't return any value
*/
$views['all'] = preg_replace( '/\(.+\)/U', ''.$total.'', $views['all'] );
$views['publish'] = preg_replace( '/\(.+\)/U', ''.$publish.'', $views['publish'] );
$views['draft'] = preg_replace( '/\(.+\)/U', ''.$draft.'', $views['draft'] );
$views['pending'] = preg_replace( '/\(.+\)/U', ''.$pending.'', $views['pending'] );
$views['trash'] = preg_replace( '/\(.+\)/U', ''.$trash.'', $views['trash'] );
return $views;
}
I know that the issue is that certain parameters aren't found in the db (for example, there may not be any "pending" posts) so it throws out an error. How can I code my way around this, for example, to say, if the parameter exists...
The goal here is to remove the '(' ')' brackets from post counts in wordpress. So when you are on the view posts, or view pages screen, there is a sub menu above the lists of posts/pages with the following items 'all', 'published', 'trash', 'pending' - these are filters that the user can click on. Next to each filter is a number, the number of posts/pages within that filter. The format of this count is ([NUMBER]) - This code is to simply get rid of those brackets.
I noticed by google'ing a bit that you're using the code form this Wordpress SE answer. This doesn't match your needs, as this code is here to recalculate the number of posts after some manipulation on that by the OP.
To just remove the parenthesis, look at the following function in class-wp-list-table.php:
public function views() {
$views = $this->get_views();
$views = apply_filters( "views_{$this->screen->id}", $views );
if ( empty( $views ) )
return;
$this->screen->render_screen_reader_content( 'heading_views' );
echo "<ul class='subsubsub'>\n";
foreach ( $views as $class => $view ) {
$views[ $class ] = "\t<li class='$class'>$view";
}
echo implode( " |</li>\n", $views ) . "</li>\n";
echo "</ul>";
}
This is the function that build the user menu that you try to change. If you look closer at this, you will see that the $view being echo'ed come from a $views that is being filtered previously:
$views = apply_filters( "views_{$this->screen->id}", $views )
$this->screen->id stand for the ID of the current screen, like edit-post for example.
So by adding this simple filter you will achieve what you want to do here:
add_filter('views_edit-post', 'remove_count_parenthesis', 10, 1);
function remove_count_parenthesis($views) {
foreach($views as $key => $view) {
$views[$key] = str_replace(array('(', ')'), '', $view);
}
return $views;
}
You need to check if there is a value 'draft' in your array
if (isset( $views['draft'] )) {
$views['draft'] = preg_replace( '/\(.+\)/U', ''.$draft.'', $views['draft'] );
}
I've purchased a theme and the blog excerpt works fine on their demo site, but not on my website's blog overview page.
this is the code I found, but this is the wordpress post-template.php
The theme does not have any blog settings which leads me to think it's a wordpress issues?
Hopre someone can help,
Many thanks!
P.S. Php newbie so please explain how I can fix this.
function get_the_excerpt( $deprecated = '' ) {
if ( !empty( $deprecated ) )
_deprecated_argument( __FUNCTION__, '2.3' );
$post = get_post();
if ( empty( $post ) ) {
return '';
}
if ( post_password_required() ) {
return __( 'There is no excerpt because this is a protected post.' );
}
/**
* Filter the retrieved post excerpt.
*
* #since 1.2.0
*
* #param string $post_excerpt The post excerpt.
*/
return apply_filters( 'get_the_excerpt', $post->post_excerpt );
}
/**
* Whether post has excerpt.
*
* #since 2.3.0
*
* #param int|WP_Post $id Optional. Post ID or post object.
* #return bool
*/
function has_excerpt( $id = 0 ) {
$post = get_post( $id );
return ( !empty( $post->post_excerpt ) );
}
/**
* Display the classes for the post div.
*
* #since 2.7.0
*
* #param string|array $class One or more classes to add to the class list.
* #param int|WP_Post $post_id Optional. Post ID or post object.
*/
function post_class( $class = '', $post_id = null ) {
// Separates classes with a single space, collates classes for post DIV
echo 'class="' . join( ' ', get_post_class( $class, $post_id ) ) . '"';
}
By default the_excerpt() return the text in the excerpt field. Though you can use a filter to change what it returns:
add_filter( 'get_the_excerpt', 'my_custom_excerpt' );
It will trigger this function when the_excerpt() will be called:
function my_custom_excerpt($excerpt) {
if(empty($excerpt)) {
return get_custom_excerpt();
} else {
return $excerpt;
}
}
That way a custom excerpt will be used if the excerpt field is empty. Here is the code for get_custom_excerpt (it will do a "smart" ceasure):
function print_excerpt($length)
{
global $post;
$text = $post->post_excerpt;
if ( '' == $text ) {
$text = get_the_content('');
$text = apply_filters('the_content', $text);
$text = str_replace(']]>', ']]>', $text);
}
$text = strip_shortcodes($text);
$text = strip_tags($text, '<a>'); // change this to the tags you want to keep
if (preg_match('/^.{1,'.$length.'}\b/s', $text, $match))
$text = $match[0];
$excerpt = reverse_strrchr($text, array('.','!'), 1, 100);
if($excerpt) {
echo apply_filters('the_excerpt',$excerpt);
} else {
echo apply_filters('the_excerpt',$text.'...');
}
}
function reverse_strrchr($haystack, $needle, $trail, $offset=0)
{
return strrposa($haystack, $needle, $offset) ? substr($haystack, 0, strrposa($haystack, $needle, $offset) + $trail) : false;
}
// strrpos in Array mode
function strrposa($haystack, $needles=array(), $offset=0)
{
if(!is_array($needles))
$needles = array($needles);
foreach($needles as $query) {
if(strrpos($haystack, $query, $offset) !== false)
return strrpos($haystack, $query, $offset);
}
return false;
}