How to use get_sidebar in plugin folder?
-
I’ve created the plugin that adds custom post type and custom taxonomies for this post type. Templates for the post type and the taxonomies are located in plugin folder.
Now I need to add sidebar for the post type and taxonomies pages. I’ve tried to use the following code for sidebar:
function mytype_get_sidebar($mytype_sidebar) { // load sidebar template if (file_exists(plugin_dir_path(__FILE__) . '/sidebar-mytype.php')) return plugin_dir_path(__FILE__) . '/sidebar-mytype.php'; // Default return return $mytype_sidebar; } add_filter('get_sidebar', 'mytype_get_sidebar');
And then on the page where the sidebar should be:
get_sidebar ( apply_filters( 'mytype_get_sidebar', '' ) );
But it doesn’t work. var_dump returns NULL:$my = get_sidebar ( apply_filters( 'mytype_get_sidebar', '' ) ); var_dump($my);
Is there any way how to do that?
Thanks in advance.
-
You’re not really using filter hooks correctly. First of all, ‘get_sidebar’ is an action, not filter. Using
add_filter()
will still register your callback, the problem is actions don’t expect returned values, so returning your file path will have no effect.In order to load a template from an action callback, just load the template, no need to return anything. The problem here though is a call to
get_sidebar()
will still load sidebar.php from the theme no matter what you do from the action callback, short of usingdie()
orexit()
or similar.I suggest forgetting
get_sidebar()
. If you want to load your sidebar template, useload_template()
.FYI, you’re not using
apply_filters()
correctly either, unless you’ve added another filter like so:
add_filter( 'mytype_get_sidebar', 'some_other_callback' );
or you’re simply providing a hook for others to use in the future (a good idea actually) and you really intend to pass an empty string toget_sidebar()
, because without an added filter, applying filters just returns the second parameter.If I were a mind reader and knew your intention was to ensure
mytype_get_sidebar()
is called when you callget_sidebar()
, I would tell you to not apply any filters. The fact you added your function as a callback means simply callingget_sidebar()
with no extra coding is all that’s needed to cause your function to be executed. But I’m not a mind reader. I’m not sure what you’re trying to do, but it doesn’t look right.One last thing and I’ll stop picking apart your code.
get_sidebar()
never returns a value, so there’s no point in checking the return with var_dump().Thank you bcworkz, finally I understood how add_filter() and get_sidebar() work.
I’ve done like this:
load_template ( dirname( __FILE__ ) . '/sidebar-mytype.php' ) ;
You’re welcome. Filters are a little hard to grasp at first, but understanding them is very important when hacking WordPress. Your knowledge should serve you well in the future.
- The topic ‘How to use get_sidebar in plugin folder?’ is closed to new replies.