This is a hack, so if you know a better way of doing this please tell me. I wanted to add a filter to get_permalink, but only when get_permalink was called from a function in another plugin. Here's the function I wanted to hook into, it's part of the Digg Digg plugin and you'll find it in the digg-digg.php file (In the example below I've removed most of the code):

1
2
3
4
5
6
7
8
9
add_filter( 'the_content', 'dd_hook_wp_content' );
function dd_hook_wp_content($content = ''){
	.
	.
	$postlink = get_permalink($id); //get post link
	.
	.
	return $content;
}

This is what I did:

1
2
3
4
5
6
7
8
9
function get_soderlind_permalink($permalink, $post, $leavename) {
	if ( function_exists('wp_debug_backtrace_summary') && stristr(wp_debug_backtrace_summary(), 'dd_hook_wp_content') !== FALSE) {
		/*
    	do stuff
    	*/
  	}
	return $permalink;
}
add_filter( 'post_link','get_soderlind_permalink', 10, 3 );

wp_debug_backtrace_summary return a comma separated string of functions that have been called to get to the current point in code.

So why did I need this hack? I needed to preserve my social sharing counters after I changed my permalink structure. My old permalink was /archives/%year%/%monthnum%/%day%/%postname%/ and the new is /%postname%/. I Changed my permalink structure on the 12.1.2013

The working hack, which I added to the child theme functions.php, is:

1
2
3
4
5
6
7
8
9
10
11
12
13
function get_soderlind_permalink($permalink, $post, $leavename) {
	// only run when get_permalink is called from dd_hook_wp_content
	if ( function_exists('wp_debug_backtrace_summary') && stristr(wp_debug_backtrace_summary(), 'dd_hook_wp_content') !== FALSE) {
		$url_change_date = strtotime( "12.1.2013" ); // use a date format strtotime understands. see notes at https://php.net/manual/en/function.strtotime.php
		$post_date = strtotime( get_the_date( ) );
		if ( $post_date < $url_change_date ) {
			$url_date_prefix = sprintf("/archives/%s/%s/%s", date( "Y", $post_date ),  date( "m", $post_date ), date( "d", $post_date ));
			$permalink = str_replace( site_url(), site_url() . $url_date_prefix, $permalink );
  		}
	}
	return $permalink;
}
add_filter( 'post_link','get_soderlind_permalink', 20, 3 );