سؤال

Is not a matter of code, I just don't get the idea of how things works in this specific case.

I'm woking on a Wordpress theme which should dynamically load portions of php code through javascript. It actually works combined with UA Sniffing because if the device is mobile, the mobile template should be used anyway but that's not the point.

  • If the screen.width is < 1080px the Mobile version menu of my Wordpress theme should be loaded.
  • otherwise, if the screen.width is bigger, the desktop menu version should be loaded
  • a solution based just on CSS Media queries is not acceptable since the desktop version is too heavy.

So I decided to conditional dynamically load content through enquire.js The first part of my WP-homepage-template.php is:

enquire.register("screen and (max-width:1080px)", {
<script type="text/javascript">
    match : function() {
        $("body").load(
          "/path/headernav-phone.php"
        );

    unmatch : function() {
            $("body").load(
          "/path/headernav-desktop.php"
        );
    }
}

So, when the size of the screen hits 1080px, Wordpress should to load headernav-phone.php which contains just a wp_nav_menu(MOBILE) call. If the screen size is bigger, Wordpress loads headernav-desktop.php which includes wp_nav_menu(DESKTOP).

This doesn't work:

Fatal error: Call to undefined function wp_nav_menu() in /XX/YYY/ZZZ/webseiten/XXX.YY/wp-content/themes/MyTheme/templates/headernav-phone.php on line 14

It looks like that my code is run before the CMS, and it breaks its own functions.

هل كانت مفيدة؟

المحلول

IMO, the logic is flawed.
For one, there's no way to detect the screen width with PHP.

Secondly, if you were to generate a PHP -> JS file (my-script.js.php), you'd have to load WordPress engine two times.
The Answer in this link is super-pro. You'll find easier methods that use wp-load.php and WP_USE_THEMES.

Thirdly, the way you're trying to load a theme template would require the "load two times" approach. Or solving it with AJAX and wp_localize_script.

If I understood the Question correctly, I think the best bet would be to use WordPress user-agent detection and enqueue your scripts and styles accordingly. Study the core function to adapt to your needs.

[update]

Still not sure if all this complexity is really needed. Would something like this work in a generic header.php?

if( wp_is_mobile() )
    wp_nav_menu(MOBILE);
else
    wp_nav_menu(DESKTOP);

But, if you really need this changes to happen dynamically, then AJAX would be the choice.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top