Two different WordPress hooks with the same callback - php

I made a plugin that converts any uri to a hyperlink, if it finds hyper-link it will ignore it and only convert the no hyper-links uri.
In the plugin admin page I set two options, first to convert links only for the front-end, and the second option is to convert uri when ever a post/comment saved to database.
// permanently means before save to database
if ( $this->plugin_options['uri2links_convert_method'] == 'permanently' ) {
add_action( 'wp_insert_post_data', array($this, 'make_post_url_clickable' ) );
//add_action( 'preprocess_comment', array($this, 'make_comment_url_clickable' ) );
}
else {
add_filter( 'the_content', array($this, 'make_post_url_clickable' ) );
//add_filter( 'preprocess_comment', array($this, 'make_comment_url_clickable' ) );
}
My problem here if I set the plugin option to convert uri for front-end it will ignore hyper-links and convert the other uri, but if I set it to convert before save to database it 'll not ignore hyper-links and treat them as normal uri witch make the results look like this:
<a class="sdf" href=" <a href="http://test.test-75.1474.stackoverflow.com/" >http://test.test-75.1474.stackoverflow.com/ </a>
<a class="sdf" href=" <a href="https://www.stackoverflow.com" >https://www.stackoverflow.com </a>
The complete plugin source code:
<?php
/*
Plugin name: URIs to a click-able links
Plugin URI:
Description: Convert URI's to a click-able links
Author: h Abdou
Author URI: habdou.me
Version: 1.0
*/
// The admin page for the plugin
require_once( 'uri2links-menu.php' );
class Uri2Links {
protected $css = '';
protected $rel = '';
protected $target = '';
protected $convert_links = '';
protected $convert_emails = '';
protected $plugin_options = array();
protected $url_match_pattern = '/[a-zA-Z0-9\.\/\?\:#\-_=#]+\.([a-zA-Z0-9\.\/\?\:#\-_=#])+/';
protected $email_match_pattern = '/^[a-zA-Z0-9_.+-]+#[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$/';
//protected $links_match_pattern = '/<a(?:"[^"]*"[\'"]*|\'[^\']*\'[\'"]*|[^\'">])+>^[a-zA-Z0-9_.+-]+#[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$<\/a>/';
protected $links_match_pattern = '/<a[^>]*>(.*?)<\/a>/';
protected $links_matched = array();
public function __construct() {
//$this->plugin_options = get_option( 'uri2links_plugin_options' );
$this->plugin_options = array( 'uri2links_convertLinksEmails' => array( 'Links', 'Emails' ), 'uri2links_convert_method' => 'permanently' );
$this->css = isset( $this->plugin_options['uri2links_custom_css'] ) ? ' class="' . $this->plugin_options['uri2links_custom_css'] . '"' : '';
$this->rel = isset( $this->plugin_options['uri2links_rel_attr'] ) ? ' rel="' . $this->plugin_options['uri2links_rel_attr'] . '"' : '';
if ( isset( $this->plugin_options['uri2links_open_links_method'] ) && $this->plugin_options['uri2links_open_links_method'] == 'new')
$this->target = ' target="_blank"';
$this->convert_links = isset( $this->plugin_options['uri2links_convertLinksEmails'][0] ) ? $this->plugin_options['uri2links_convertLinksEmails'][0] : '';
$this->convert_emails = isset( $this->plugin_options['uri2links_convertLinksEmails'][1] ) ? $this->plugin_options['uri2links_convertLinksEmails'][1] : '';
if ( $this->plugin_options['uri2links_convert_method'] == 'permanently' ) {
add_action( 'wp_insert_post_data', array($this, 'make_post_url_clickable' ) );
//add_action( 'preprocess_comment', array($this, 'make_comment_url_clickable' ) );
}
else {
add_filter( 'the_content', array($this, 'make_post_url_clickable' ) );
//add_filter( 'preprocess_comment', array($this, 'make_comment_url_clickable' ) );
}
// The admin page for the plugin
new Uri2LinksMenu;
}
// Convert all URI in a post to hyper-links.
public function make_post_url_clickable( $content ) {
$links = $this->hash_links( $content );
if ( $this->convert_links == 'Links' ) {
$content = preg_replace($this->url_match_pattern, ' <a href="\\0"' . $this->css . $this->rel . $this->target . ' >\\0</a> ', $content);
}
if ( $this->convert_emails == 'Emails' ) {
$content = preg_replace($this->email_match_pattern, ' <a href="mailto:\\0"' . $this->css . $this->rel . $this->target . ' >\\0</a> ', $content);
}
// Replace back the hashed 'a' tags to the original status.
foreach ( $links as $link_hash => $link_text ) {
$content = str_replace( $link_hash, $link_text, $content );
}
return $content;
}
// Same as 'make_post_url_clickable' but this for comments
public function make_comment_url_clickable( $content ) {
$links = hash_links( $content['comment_content']['comment_content'] );
if ( $this->convert_links == 'Links' ) {
$content['comment_content'] = preg_replace($this->url_match_pattern, ' <a href="\\0"' . $this->css . $this->rel . $this->target . ' >\\0</a> ', $content['comment_content']);
}
if ( $this->convert_emails == 'Emails' ) {
$content['comment_content'] = preg_replace($this->email_match_pattern, ' <a href="mailto:\\0"' . $this->css . $this->rel . $this->target . ' >\\0</a> ', $content['comment_content']);
}
foreach ( $links as $link_hash => $link_text ) {
$content['comment_content'] = str_replace( $link_hash, $link_text, $content['comment_content'] );
}
return $content;
}
// hash all 'a' tags so 'make_*_url_clickable' will ignore them.
public function hash_links( &$content ) {
$links = array();
if ( preg_match_all( $this->links_match_pattern, $content, $matches ) ) {
$array_size = sizeof( $matches[0] );
for ( $i = 0; $i < $array_size; ++$i ) {
$link_hash = md5( $matches[0][$i] );
$links[$link_hash] = $matches[0][$i];
$content = str_replace( $matches[0][$i], $link_hash, $content );
}
}
//die('hash_links called!');
return $links;
}
}
new Uri2Links;
?>

I just want to mention that WordPress already got the make_clickable() function that takes text uri to HTML links.
To activate it for the post content we only need this simple plugin:
<?php
/** Plugin Name: Make text uri to HTML links in the post content **/
add_filter( 'the_content', 'make_clickable', 9 );
By default this function runs on the comment text:
add_filter( 'comment_text', 'make_clickable', 9 );

Related

Wordpress: invoke function in a page / post

I rephrase my question in this new post to which I have not had any answer. These two functions create a page on the user's account endpoint. A table is published on this page. I would like this table to be published in a new page / post of the site accessible to all. Any suggestions? Thank you
1 add_action( 'init', array(__CLASS__, 'wsc_add_my_account_endpoint') );
2 public static function wsc_add_my_account_endpoint() { add_rewrite_endpoint( 'wsc-share-cart', EP_ROOT | EP_PAGES ); }
3 The content that I would to print in a wordpress page:
if ( !isset($_GET['wc-wsc']) || !isset($_GET['nounce']) ) {
return;
}
if ( ! wp_verify_nonce( wc_clean($_GET['nounce']), 'wsc_save_share_cart' ) ) {
return;
}
$posted_fields = wc_clean($_POST);
$fields = get_option('wsc_form_fields');
$errors = array();
$form_submission = array();
$form_submission_html = '';
$customer_email = '';
if ( !empty($fields) ) {
$form_submission_html .= '<table>';
foreach ( $fields as $key => $field ) {
if ( true == $field['required'] && empty($posted_fields['wsc_form_field_' . esc_attr($key)]) ) {
$errors['wsc_form_field_' . esc_attr($key)] = wp_sprintf( '%s %s', esc_html__($field['label'], 'wc-wsc'), esc_html__('is required.', 'wc-wsc') );
}
$label = !empty($field['label']) ? $field['label'] : 'wsc_form_field_' . esc_attr($key);
$field_value = wc_clean($posted_fields['wsc_form_field_' . esc_attr($key)]);
if ( 'email' == $field['type'] ) {
if ( !is_email($field_value) ) {
$errors['wsc_form_field_' . esc_attr($key)] = wp_sprintf( '%s %s', esc_html__($field['label'], 'wc-wsc'), esc_html__('must be an email.', 'wc-wsc') );
}
$customer_email = $field_value;
}
if ( isset($posted_fields['wsc_form_field_' . esc_attr($key)]) ) {
$form_submission[$label] = $field_value;
}
$form_submission_html .= '<tr><th>' . esc_html($label) . '</th><td>' . esc_html($field_value) . '</td></tr>';
}
$form_submission_html .= '</table>';
} ```

Ajax filter not returning page content with filter

I have a special function on some of my pages that returns a modified embed code. It works great:
if (/*is_page() &&*/ has_category('Krajské zprávy')) {
/* get subtitle */
$subtitle = apply_filters( 'plugins/wp_subtitle/get_subtitle', '', array(
) );
if ((strpos($subtitle , 'kraj') == false) && (strpos($subtitle , 'Praha') == false) && (strpos($subtitle , 'Vysočina') == false)) {
$subtitle = "Všechny kraje";
};
/* get page id with embed code */
$id_short = 357;
$tag_id = array (
'Ovzduší' => 357
);
foreach ($tag_id as $k => $v) {
if (has_tag($k)) {$id_short = $v;}
}
/* get embed code & replace */
$acf_kod = get_field('embed_kod', $id_short /*,false*/);
$replace_sub = "<param name='filter' value='Parameters.Kraj=" . $subtitle . "'>";
preg_match_all('/<param [^>]*>/', $acf_kod, $matches);
$m_1 = $matches[0][0]; $m_2 = $matches[0][1];
$pos = strpos( $acf_kod, $m_1) + strlen( $m_1 );
if (strpos($acf_kod,$m_2)-(strpos($acf_kod,$m_1)+strlen($m_1))<2) {
$before = substr ($acf_kod, 0, $pos);
$after = substr( $acf_kod, $pos, strlen( $acf_kod ) );
$whole = $before . $replace_sub . $after;
$content = $whole .'<!--more-->' . $content;
};
/*echo $whole;*/
};
return $content;
};
add_filter('the_content', 'add_embed_parameter');
However, I also have a filter on my site that filters pages by categories and tags and returns them via Ajax. That, too, works just fine - but only with "standard pages" that don't use the code above. For the pages that do, it returns nothing.
This is a snippet of the php code that is used by the filter:
$query = new WP_Query( $args );
if( $query->have_posts() ) :
while( $query->have_posts() ): $query->the_post();
/*$content = get_post_field( 'post_content', get_the_ID() );*/
$content = get_the_content (/*get_the_ID()*/);
$content_parts = get_extended( $content );
echo '<h2>' . $query->post->post_title . '</h2>',
$content/*$content_parts['main'] /*'<p>' . $query->post->post_excerpt . '</p>'*/;
endwhile;
wp_reset_postdata();
else :
echo 'No posts found';
endif;
die();
This is the whole AJAX thing (it's not mine, I'm using the tutorial here):
jQuery(function($){
$('#filter').submit(function(){
var filter = $('#filter');
$.ajax({
url:filter.attr('action'),
data:filter.serialize(), // form data
type:filter.attr('method'), // POST
beforeSend:function(xhr){
filter.find('button').text('Processing...'); // changing the button label
},
success:function(data){
filter.find('button').text('Apply filter'); // changing the button label back
$('#response').html(data); // insert data
}
});
return false;
});
});
Any idea where the problem might be? Many thanks!

How to print to console from a php file in wordpress

I have a php file which is part of a wordpress plugin. I need to debug an issue we are having. I want to find out what a variable's value is. How can I print the variable's value to console? echo or chrome or firefox extensions have been suggested. I couldn't get echo to output to console (echo “$variablename";) and neither using the firephp extension for firefox.
To answer your question, you can do this:
echo '<script>console.log("PHP error: ' . $error . '")</script>';
but I would recommend doing one of the things #Ishas suggested instead. Make sure $error doesn't contain anything that can mess up your script.
If you are thinking about the javascript console, you can not do this from PHP.
You have a few options you could choose from:
echo
var_dump
create a log file
xdebug
For a quick check for a variables value I would use var_dump, it will also show you the data type of the variable. This will be output to the browser when you request the page.
Logging to the DevTools console from PHP in WordPress
Here you can see my solution for the problem in action while debugging coupon logic in WooCommerce. This solution is meant for debug purposes, only. (Note: Screenshot not up to date, it will also expose private members.)
Features
Allow printing before and after rendering has started
Works in front-end and back-end
Print any amount of variables
Encode arrays and objects
Expose private and protected members of objects
Also log to the log file
Safely and easily opt-out in the production environment (in case you keep the calls)
Print the caller class, function and hook (quality of life improvement)
Solution
wp-debug.php
function console_log(): string {
list( , $caller ) = debug_backtrace( false );
$action = current_action();
$encoded_args = [];
foreach ( func_get_args() as $arg ) try {
if ( is_object( $arg ) ) {
$extract_props = function( $obj ) use ( &$extract_props ): array {
$members = [];
$class = get_class( $obj );
foreach ( ( new ReflectionClass( $class ) )->getProperties() as $prop ) {
$prop->setAccessible( true );
$name = $prop->getName();
if ( isset( $obj->{$name} ) ) {
$value = $prop->getValue( $obj );
if ( is_array( $value ) ) {
$members[$name] = [];
foreach ( $value as $item ) {
if ( is_object( $item ) ) {
$itemArray = $extract_props( $item );
$members[$name][] = $itemArray;
} else {
$members[$name][] = $item;
}
}
} else if ( is_object( $value ) ) {
$members[$name] = $extract_props( $value );
} else $members[$name] = $value;
}
}
return $members;
};
$encoded_args[] = json_encode( $extract_props( $arg ) );
} else {
$encoded_args[] = json_encode( $arg );
}
} catch ( Exception $ex ) {
$encoded_args[] = '`' . print_r( $arg, true ) . '`';
}
$msg = '`📜`, `'
. ( array_key_exists( 'class', $caller ) ? $caller['class'] : "\x3croot\x3e" )
. '\\\\'
. $caller['function'] . '()`, '
. ( strlen( $action ) > 0 ? '`🪝`, `' . $action . '`, ' : '' )
. '` ➡️ `, ' . implode( ', ', $encoded_args );
$html = '<script type="text/javascript">console.log(' . $msg . ')</script>';
add_action( 'wp_enqueue_scripts', function() use ( $html ) {
echo $html;
} );
add_action( 'admin_enqueue_scripts', function() use ( $html ) {
echo $html;
} );
error_log( $msg );
return $html;
}
wp-config.php (partially)
// ...
define( 'WP_DEBUG', true );
// ...
/** Include WP debug helper */
if ( defined( 'WP_DEBUG' ) && WP_DEBUG && file_exists( ABSPATH . 'wp-debug.php' ) ) {
include_once ABSPATH . 'wp-debug.php';
}
if ( ! function_exists( 'console_log' ) ) {
function console_log() {
}
}
/** Sets up WordPress vars and included files. */
require_once( ABSPATH . 'wp-settings.php' );
Usage
Before the HTML <head> is rendered:
console_log( $myObj, $myArray, 123, "test" );
After the HTML <head> is rendered (in templates, etc. / use when the above does not work):
echo console_log( $myObj, $myArray, 123, "test" );
Output format
📜 <caller class>\<caller function>() 🪝 <caller action/hook> ➡️ <variables ...>
Special thanks to
Andre Medeiros for the property extraction method
You can write a utility function like this:
function prefix_console_log_message( $message ) {
$message = htmlspecialchars( stripslashes( $message ) );
//Replacing Quotes, so that it does not mess up the script
$message = str_replace( '"', "-", $message );
$message = str_replace( "'", "-", $message );
return "<script>console.log('{$message}')</script>";
}
The you may call the function like this:
echo prefix_console_log_message( "Error Message: This is really a 'unique' problem!" );
and this will output to console like this:
Error Message: This is really a -unique- problem!
Notice the quotes replaced with "-". It is done so that message does not mess up your script as pointed by #Josef-Engelfrost
You may also go one step further and do something like this:
function prefix_console_log_message( $message, $type = "log" ) {
$message_types = array( 'log', 'error', 'warn', 'info' );
$type = ( in_array( strtolower( $type ), $message_types ) ) ? strtolower( $type ) : $message_types[0];
$message = htmlspecialchars( stripslashes( $message ) );
//Replacing Quotes, so that it does not mess up the script
$message = str_replace( '"', "-", $message );
$message = str_replace( "'", "-", $message );
return "<script>console.{$type}('{$message}')</script>";
}
and call the function like this:
echo prefix_console_log_message( "Error Message: This is really a 'unique' problem!" , 'error');
It will output error in console.

Buddypress plugin bug - XML to PHP

It is an external group blogs plugin
It gives group creators and administrators on your BuddyPress install the ability to attach external blog RSS feeds to groups.
Blog posts will appear within the activity stream for the group.
New posts will automatically be pulled every hour, or every 30 minutes if someone specifically visits a group page.
There are so many bugs that I found.
1) it is not fetching feeds automatically
2) if I try to manually updates feeds it is reposting the same entries, I mean it is not fetching new feeds.
3) WordPress admin bar is also not working properly with this plugin.
This plugin contains 2 webpages.
First and the main page is loader.php
<?php
/*
Plugin Name: External Group Blogs
Plugin URI: http://wordpress.org/extend/plugins/external-group-blogs/
Description: Allow group creators to supply external blog RSS feeds that will attach future posts on blogs to a group.
*/
/* Only load the plugin functions if BuddyPress is loaded and initialized. */
function bp_groupblogs_init() {
require( dirname( __FILE__ ) . '/bp-groups-externalblogs.php' );
}
add_action( 'bp_init', 'bp_groupblogs_init' );
/* On activation register the cron to refresh external blog posts. */
function bp_groupblogs_activate() {
wp_schedule_event( time(), 'hourly', 'bp_groupblogs_cron' );
}
register_activation_hook( __FILE__, 'bp_groupblogs_activate' );
/* On deacativation, clear the cron. */
function bp_groupblogs_deactivate() {
wp_clear_scheduled_hook( 'bp_groupblogs_cron' );
/* Remove all external blog activity */
if ( function_exists( 'bp_activity_delete' ) )
bp_activity_delete( array( 'type' => 'exb' ) );
}
register_deactivation_hook( __FILE__, 'bp_groupblogs_deactivate' );
?>
And the 2nd file is bp-groups-externalblogs.php
<?php
/* Group blog extension using the BuddyPress group extension API */
if ( class_exists('BP_Group_Extension' ) ) {
class Group_External_Blogs extends BP_Group_Extension {
function __construct() {
global $bp;
$this->name = __( 'External Blogs', 'bp-groups-externalblogs' );
$this->slug = 'external-blog-feeds';
$this->create_step_position = 21;
$this->enable_nav_item = false;
}
function create_screen() {
global $bp;
if ( !bp_is_group_creation_step( $this->slug ) )
return false;
?>
<p><?php _e(
"Add RSS feeds of blogs you'd like to attach to this group in the box below.
Any future posts on these blogs will show up on the group page and be recorded
in activity streams.", 'bp-groups-externalblogs' ) ?>
</p>
<p class="desc"><?php _e( "Seperate URL's with commas.", 'bp-groups-externalblogs' ) ?></span>
<p>
<label for="blogfeeds"><?php _e( "Feed URL's:", 'bp-groups-externalblogs' ) ?></label>
<textarea name="blogfeeds" id="blogfeeds"><?php echo attribute_escape( implode( ', ', (array)groups_get_groupmeta( $bp->groups->current_group->id, 'blogfeeds' ) ) ) ?></textarea>
</p>
<?php
wp_nonce_field( 'groups_create_save_' . $this->slug );
}
function create_screen_save() {
global $bp;
check_admin_referer( 'groups_create_save_' . $this->slug );
$unfiltered_feeds = explode( ',', $_POST['blogfeeds'] );
foreach( (array) $unfiltered_feeds as $blog_feed ) {
if ( !empty( $blog_feed ) )
$blog_feeds[] = trim( $blog_feed );
}
groups_update_groupmeta( $bp->groups->current_group->id, 'blogfeeds', $blog_feeds );
groups_update_groupmeta( $bp->groups->current_group->id, 'bp_groupblogs_lastupdate', gmdate( "Y-m-d H:i:s" ) );
/* Fetch */
bp_groupblogs_fetch_group_feeds( $bp->groups->current_group->id );
}
function edit_screen() {
global $bp;
if ( !bp_is_group_admin_screen( $this->slug ) )
return false; ?>
<p class="desc"><?php _e( "Enter RSS feed URL's for blogs you would like to attach to this group. Any future posts on these blogs will show on the group activity stream. Seperate URL's with commas.", 'bp-groups-externalblogs' ) ?></span>
<p>
<label for="blogfeeds"><?php _e( "Feed URL's:", 'bp-groups-externalblogs' ) ?></label>
<textarea name="blogfeeds" id="blogfeeds"><?php echo attribute_escape( implode( ', ', (array)groups_get_groupmeta( $bp->groups->current_group->id, 'blogfeeds' ) ) ) ?></textarea>
</p>
<input type="submit" name="save" value="<?php _e( "Update Feed URL's", 'bp-groups-externalblogs' ) ?>" />
<?php
wp_nonce_field( 'groups_edit_save_' . $this->slug );
}
function edit_screen_save() {
global $bp;
if ( !isset( $_POST['save'] ) )
return false;
check_admin_referer( 'groups_edit_save_' . $this->slug );
$existing_feeds = (array)groups_get_groupmeta( $bp->groups->current_group->id, 'blogfeeds' );
$unfiltered_feeds = explode( ',', $_POST['blogfeeds'] );
foreach( (array) $unfiltered_feeds as $blog_feed ) {
if ( !empty( $blog_feed ) )
$blog_feeds[] = trim( $blog_feed );
}
/* Loop and find any feeds that have been removed, so we can delete activity stream items */
if ( !empty( $existing_feeds ) ) {
foreach( (array) $existing_feeds as $feed ) {
if ( !in_array( $feed, (array) $blog_feeds ) )
$removed[] = $feed;
}
}
if ( $removed ) {
/* Remove activity stream items for this feed */
include_once( ABSPATH . WPINC . '/rss.php' );
foreach( (array) $removed as $feed ) {
$rss = fetch_rss( trim( $feed ) );
if ( function_exists( 'bp_activity_delete' ) ) {
bp_activity_delete( array(
'item_id' => $bp->groups->current_group->id,
'secondary_item_id' => wp_hash( $rss->channel['link'] ),
'component' => $bp->groups->id,
'type' => 'exb'
) );
}
}
}
groups_update_groupmeta( $bp->groups->current_group->id, 'blogfeeds', $blog_feeds );
groups_update_groupmeta( $bp->groups->current_group->id, 'bp_groupblogs_lastupdate', gmdate( "Y-m-d H:i:s" ) );
/* Re-fetch */
bp_groupblogs_fetch_group_feeds( $bp->groups->current_group->id );
bp_core_add_message( __( 'External blog feeds updated successfully!', 'bp-groups-externalblogs' ) );
bp_core_redirect( bp_get_group_permalink( $bp->groups->current_group ) . '/admin/' . $this->slug );
}
/* We don't need display functions since the group activity stream handles it all. */
function display() {}
function widget_display() {}
}
bp_register_group_extension( 'Group_External_Blogs' );
function bp_groupblogs_fetch_group_feeds( $group_id = false ) {
global $bp;
include_once( ABSPATH . 'wp-includes/rss.php' );
if ( empty( $group_id ) )
$group_id = $bp->groups->current_group->id;
if ( $group_id == $bp->groups->current_group->id )
$group = $bp->groups->current_group;
else
$group = new BP_Groups_Group( $group_id );
if ( !$group )
return false;
$group_blogs = groups_get_groupmeta( $group_id, 'blogfeeds' );
$group_blogs = explode(";",$group_blogs[0]);
/* Set the visibility */
$hide_sitewide = ( 'public' != $group->status ) ? true : false;
foreach ( (array) $group_blogs as $feed_url ) {
$rss = fetch_feed( trim( $feed_url ) );
if (!is_wp_error($rss) ) {
foreach ( $rss->get_items(0,10) as $item ) {;
$key = $item->get_date( 'U' );
$items[$key]['title'] = $item->get_title();
$items[$key]['subtitle'] = $item->get_title();
//$items[$key]['author'] = $item->get_author()->get_name();
$items[$key]['blogname'] = $item->get_feed()->get_title();
$items[$key]['link'] = $item->get_permalink();
$items[$key]['blogurl'] = $item->get_feed()->get_link();
$items[$key]['description'] = $item->get_description();
$items[$key]['source'] = $item->get_source();
$items[$key]['copyright'] = $item->get_copyright();
}
}
}
if ( $items ) {
ksort($items);
$items = array_reverse($items, true);
} else {
return false;
}
/* Record found blog posts in activity streams */
foreach ( (array) $items as $post_date => $post ) {
//var_dump($post);
if (substr($post['blogname'],0,7) == "Twitter") {
$activity_action = sprintf( __( '%s from %s in the group %s', 'bp-groups-externalblogs' ), '<a class="feed-link" href="' . esc_attr( $post['link'] ) . '">Tweet</a>', '<a class="feed-author" href="' . esc_attr( $post['blogurl'] ) . '">' . attribute_escape( $post['blogname'] ) . '</a>', '' . attribute_escape( $group->name ) . '' );
} else {
$activity_action = sprintf( __( 'Blog: %s from %s in the group %s', 'bp-groups-externalblogs' ), '<a class="feed-link" href="' . esc_attr( $post['link'] ) . '">' . esc_attr( $post['title'] ) . '</a>', '<a class="feed-author" href="' . esc_attr( $post['blogurl'] ) . '">' . attribute_escape( $post['blogname'] ) . '</a>', '' . attribute_escape( $group->name ) . '' );
}
$activity_content = '<div>' . strip_tags( bp_create_excerpt( $post['description'], 175 ) ) . '</div>';
$activity_content = apply_filters( 'bp_groupblogs_activity_content', $activity_content, $post, $group );
/* Fetch an existing activity_id if one exists. */
if ( function_exists( 'bp_activity_get_activity_id' ) )
$id = bp_activity_get_activity_id( array( 'user_id' => false, 'action' => $activity_action, 'component' => $bp->groups->id, 'type' => 'exb', 'item_id' => $group_id, 'secondary_item_id' => wp_hash( $post['blogurl'] ) ) );
/* Record or update in activity streams. */
groups_record_activity( array(
'id' => $id,
'user_id' => false,
'action' => $activity_action,
'content' => $activity_content,
'primary_link' => $item->get_link(),
'type' => 'exb',
'item_id' => $group_id,
'secondary_item_id' => wp_hash( $post['blogurl'] ),
'recorded_time' => gmdate( "Y-m-d H:i:s", $post_date ),
'hide_sitewide' => $hide_sitewide
) );
}
return $items;
}
/* Add a filter option to the filter select box on group activity pages */
function bp_groupblogs_add_filter() { ?>
<option value="exb"><?php _e( 'External Blogs', 'bp-groups-externalblogs' ) ?></option><?php
}
add_action( 'bp_group_activity_filter_options', 'bp_groupblogs_add_filter' );
add_action( 'bp_activity_filter_options', 'bp_groupblogs_add_filter' );
/* Add a filter option groups avatar */
/* Fetch group twitter posts after 30 mins expires and someone hits the group page */
function bp_groupblogs_refetch() {
global $bp;
$last_refetch = groups_get_groupmeta( $bp->groups->current_group->id, 'bp_groupblogs_lastupdate' );
if ( strtotime( gmdate( "Y-m-d H:i:s" ) ) >= strtotime( '+30 minutes', strtotime( $last_refetch ) ) )
add_action( 'wp_footer', 'bp_groupblogs_refetch' );
/* Refetch the latest group twitter posts via AJAX so we don't stall a page load. */
function _bp_groupblogs_refetch() {
global $bp; ?>
<script type="text/javascript">
jQuery(document).ready( function() {
jQuery.post( ajaxurl, {
action: 'refetch_groupblogs',
'cookie': encodeURIComponent(document.cookie),
'group_id': <?php echo $bp->groups->current_group->id ?>
});
});
</script><?php
groups_update_groupmeta( $bp->groups->current_group->id, 'bp_groupblogs_lastupdate', gmdate( "Y-m-d H:i:s" ) );
}
}
add_action( 'groups_screen_group_home', 'bp_groupblogs_refetch' );
/* Refresh via an AJAX post for the group */
function bp_groupblogs_ajax_refresh() {
bp_groupblogs_fetch_group_feeds( $_POST['group_id'] );
}
add_action( 'wp_ajax_refetch_groupblogs', 'bp_groupblogs_ajax_refresh' );
function bp_groupblogs_cron_refresh() {
global $bp, $wpdb;
$group_ids = $wpdb->get_col( $wpdb->prepare( "SELECT group_id FROM " . $bp->groups->table_name_groupmeta . " WHERE meta_key = 'blogfeeds'" ) );
foreach( $group_ids as $group_id )
bp_groupblogs_fetch_group_feeds( $group_id );
}
add_action( 'bp_groupblogs_cron', 'bp_groupblogs_cron_refresh' );
}
// Add a filter option groups avatar
function bp_groupblogs_avatar_type($var) {
global $activities_template, $bp;
if ( $activities_template->activity->type == "exb" ) {
return 'group';
} else {
return $var;
}
}
add_action( 'bp_get_activity_avatar_object_groups', 'bp_groupblogs_avatar_type');
add_action( 'bp_get_activity_avatar_object_activity', 'bp_groupblogs_avatar_type');
function bp_groupblogs_avatar_id($var) {
global $activities_template, $bp;
if ( $activities_template->activity->type == "exb" ) {
return $activities_template->activity->item_id;
}
return $var;
}
add_action( 'bp_get_activity_avatar_item_id', 'bp_groupblogs_avatar_id');
?>
I have a suggestion for stopping data repeating in activity stream. Maybe use wp-cron api and a current date xml feeds fetching system once in a day. So it will not repeat the same feeds in a group activity stream. We need a criteria by which we can stop data repetition in the bp group activity stream. It is a part of my project. Is there another way of fetching feeds and saving it to the mysql table (in the group activity stream) and then show it as a latest group updates?
Actually IT IS fetching automatically.
I see the cron usage in a plugin. WordPress Cron fires only when any user opens your site. So no users (no pageviews) - no cron activity. On every pageview WP-Cron check whether the time to fire any function came or not.
Perhaps this plugin will help you a bit - display a RSS feed in a separate group tab.

Adding caption area to 'Flexslider Plug-in'

I have this question on the Wordpress stack exchange as well, but not having any luck there. So, as my solution probably involves me hard-coding php and css, It may be better to have it here.
I'm using 'Flex Slider' plugin - that works on top of 'WP rotator' plug-in on my Wordpress 3.2 website. I have it implemented fine, and beginning to look at inserting my content - but I need to add a caption to be on top of the slider. As are present on most sliders on the web, within the documentation of the non-Wordpress plugin of the tool it suggests I can do something like;
<div class="flex-container">
<div class="flexslider">
<ul class="slides">
<li>
<img src="slide1.jpg" />
<p class="flex-caption">Captions and cupcakes. Winning combination.</p>
</li>
<li>
<img src="slide2.jpg" />
<p class="flex-caption">This image is wrapped in a link!</p>
</li>
<li>
<img src="slide3.jpg" />
</li>
</ul>
</div>
</div>
Problem is; with the Wordpress plug-in version, I can't find that markup to work inside.
Here's the only non-css non-js file in the plug-ins directory, so I assume I have to work in there.
I've tried inserting the mark-up that was suggested non-Wordpress above, but not sure where to insert it as it's broke it with my attempts thus far.
<?php
/*
Plugin Name: Flex Slider for WP Rotator
Plugin URI: http://wordpress.org/extend/plugins/flex-slider-for-wp-rotator/
Description: Turns WP Rotator into FlexSlider, a fully responsive jQuery slider.
Version: 1.1
Author: Bill Erickson
Author URI: http://www.billerickson.net/blog/wordpress-guide
*/
class BE_Flex_Slider {
var $instance;
function __construct() {
$this->instance =& $this;
register_activation_hook( __FILE__, array( $this, 'activation_hook' ) );
add_action( 'plugins_loaded', array( $this, 'init' ) );
}
/**
* Activation Hook
* Confirm WP Rotator is currently active
*/
function activation_hook() {
if( !function_exists( 'wp_rotator_option' ) ) {
deactivate_plugins( plugin_basename( __FILE__ ) );
wp_die( sprintf( __( 'Sorry, you can’t activate unless you have installed WP Rotator', 'flex-slider-for-wp-rotator'), 'http://wordpress.org/extend/plugins/wp-rotator/' ) );
}
}
function init() {
// Remove original scripts and styles
remove_action('wp_head','wp_rotator_css');
remove_action('admin_head','wp_rotator_css');
remove_action('wp_head','wp_rotator_javascript');
remove_action('admin_head','wp_rotator_javascript');
remove_action('init','wp_rotator_add_jquery');
remove_action('admin_init','wp_rotator_add_jquery');
// Enqueue Scripts and Styles
add_action( 'init', array( $this, 'enqueue_scripts_and_styles' ) );
// Remove original outer markup
remove_action( 'wp_rotator', 'wp_rotator' );
// Add new markup
add_action( 'wp_rotator', array( $this, 'flex_slider' ) );
remove_shortcode( 'wp_rotator' );
add_shortcode( 'wp_rotator', array( $this, 'flex_slider_markup' ) );
}
function enqueue_scripts_and_styles() {
// Use this filter to limit where the scripts are enqueued.
$show = apply_filters( 'be_flex_slider_show_scripts', true );
if ( true === $show ) {
wp_enqueue_style( 'flex-slider', plugins_url( 'flexslider.css', __FILE__ ) );
wp_enqueue_script( 'jquery ');
wp_enqueue_script( 'flex-slider', plugins_url( 'jquery.flexslider-min.js', __FILE__ ), array( 'jquery' ) );
add_action( 'wp_head', array( $this, 'flex_slider_settings' ) );
}
}
function flex_slider_settings() {
?>
<script type="text/javascript" charset="utf-8">
jQuery(window).load(function() {
jQuery('.flexslider').flexslider({
<?php
$flex_settings = array(
'animation' => '"' . wp_rotator_option( 'animate_style' ) . '"',
'slideshowSpeed' => wp_rotator_option( 'rest_ms' ),
'animationDuration' => wp_rotator_option( 'animate_ms' ),
);
$flex_slide_settings = array(
'controlsContainer' => '".flex-container"'
);
if( 'slide' == wp_rotator_option( 'animate_style' ) )
$flex_settings = array_merge( $flex_settings, $flex_slide_settings );
$flex_settings = apply_filters( 'be_flex_slider_settings', $flex_settings );
foreach ( $flex_settings as $field => $value ) {
echo $field . ': ' . $value . ', ';
}
?>
});
});
</script>
<?php
}
function flex_slider_markup() {
$output = '';
if( 'slide' == wp_rotator_option( 'animate_style' ) )
$output .= '<div class="flex-container">';
$output .= '<div class="flexslider"><ul class="slides">';
$loop = new WP_Query( esc_attr( wp_rotator_option('query_vars') ) );
while ( $loop->have_posts() ): $loop->the_post(); global $post;
$url = esc_url ( get_post_meta( $post->ID, 'wp_rotator_url', true ) );
if ( empty( $url ) ) $url = get_permalink($post->ID);
$show_info = esc_attr( get_post_meta( $post->ID, 'wp_rotator_show_info', true ) );
if ( true == $show_info ) {
$title = get_the_title();
if ( get_the_excerpt() ) $excerpt = get_the_excerpt();
else $excerpt = '';
$caption = $title . ' <span class="excerpt">' . $excerpt . '</span>';
$info = '<p class="flex-caption">' . apply_filters( 'be_flex_slider_caption', $caption, $title, $excerpt ) . '</p>';
} else {
$info = '';
}
$image = wp_get_attachment_image_src( get_post_thumbnail_id(), 'wp_rotator' );
$slide = '<li><img src="' . $image[0] . '" />' . $info . '</li>';
$output .= apply_filters( 'be_flex_slider_slide', $slide );
endwhile; wp_reset_query();
$output .= '</ul></div>';
if( 'slide' == wp_rotator_option( 'animate_style' ) )
$output .= '</div>';
return $output;
}
function flex_slider() {
echo $this->flex_slider_markup();
}
}
new BE_Flex_Slider;
?>
I have contacted the plug-in developer, he's not responding so I assume hes not going to support my question - so I'm left to handcode.
http://wordpress.org/extend/plugins/wp-rotator/
http://flex.madebymufffin.com/
http://wordpress.org/extend/plugins/flex-slider-for-wp-rotator/
Thanks for any pointers!
It looks like captions are automatically added to the slider as long as you set the post to show rotator info (wp_rotator_show_info... probably on the plugin settings page or on your individual post page). The automatic caption is made up of the title of the post plus the excerpt. Here's the key part in the plugin above:
$show_info = esc_attr( get_post_meta( $post->ID, 'wp_rotator_show_info', true ) );
if ( true == $show_info ) {
$title = get_the_title();
if ( get_the_excerpt() ) $excerpt = get_the_excerpt();
else $excerpt = '';
$caption = $title . ' <span class="excerpt">' . $excerpt . '</span>';
$info = '<p class="flex-caption">' . apply_filters( 'be_flex_slider_caption', $caption, $title, $excerpt ) . '</p>';
} else {
$info = '';
}
UPDATE: If you want the caption to show no matter what, replace the above portion with this:
$title = get_the_title();
if ( get_the_excerpt() ) $excerpt = get_the_excerpt();
else $excerpt = '';
$caption = $title . ' <span class="excerpt">' . $excerpt . '</span>';
$info = '<p class="flex-caption">' . apply_filters( 'be_flex_slider_caption', $caption, $title, $excerpt ) . '</p>';
Note that I merely deleted the part that checks for wp_rotator_show_info.

Categories