I am trying to write a little plugin which allows me to add a different theme to each page. well.. still trying.. 😉
code: http://pastebin.com/dP1GH43E
When I put return 'mytesttheme';
at the end it works just perfect!
when I add an ID ($page_theme = get_post_meta('66', [...]
) it also works..
when I write echo $page_theme.', ';
before the return, it outputs: , , , mytesttheme, mytesttheme, mytesttheme, mytesttheme,
The empty spaces are the problem I think.
in wp-backend it shows “mytesttheme” as post meta content in wp-core post meta content box.. so the saving works as it should..
Any ideas how to solve the problem? :S
There are several issues with your code. Let’s start at the beginning…
Adding hooks
All your hooks will be added at the backend. Even those which are outside the
if((is_admin))
branch. Add your hooks explicitly where they should work:In the loop or not?
get_the_ID()
must be within the loop. Where are your hooks (‘option_template’, ‘template’ and ‘option_stylesheet’) are done? Before the query is done or after (means: inside the loop or outside) ?Two lines of code give us the answer:
If
$post
is empty (null), we are outside the loop. We hooked to early. We need a hook after the query is done. The ´init´ hook is an odd one. Let’s alter the code above a bit and get the plugin working:Now our hooks are inside the loop and the plugin works fine.
Deprecated function
On line 28 of your plugin code you use
$themes = get_themes();
.get_themes()
is deprecated and should be replaced with ´wp_get_themes()´.Development
Please enable WP-debugging (set WP_DEBUG to TRUE in your wp-config.php). The debug messages will help you much.
You can find the complete modified code on Github
As far I know, to use post->ID outside of loop, wp_query should be called first. I mean something like that the code bellow which is already suggested by @Jan
Optionally,
get_post_id()
can work for you, check codex for more.