Take the 2-minute tour ×
WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. It's 100% free, no registration required.

I’m trying to push the boundaries of Wordpress by turning it into a SPA CMS. Everything works fine until now except for a redirection issue.

github angularpresstheme

How it works:

When I create a page and publish it (or update) wordpress will generate an Angularjs html view template. All pages are redirected to the index.php (hence the name SPA) where there is a directive that handles all view states. I use HTTP_API to do it.

Issue:

If you go for the first time (the second time is loaded using php .You may need to clear your browser session) to http://angularpresstheme.com/full-width/ you will see that the page briefly appears and then reloads ( this doesn’t happen if you just go to ‘/’). I use JavaScript (Angularjs) to redirect the page. The main problem with this approach is that it is pretty slow and the pages flickers. This happens because it was the only way I could find to avoid the following:

  • Whenever I tried to create a page and published it the resulting Angularjs html template was always based on index.php template! This occurred because I simply had redirected all pages to index.php (using .htaccess or php) .

What I did to mitigate the problem:

  • I solved part of the problem by redirecting the “/” (front-page) and the other pages (when loaded for the second time) using PHP.
  • When pages other than the front-page (“/” ) are loaded for the first time I had to use Javascript in order to avoid the “index.php” only template generation effect.

What I would like to do:

On click publish or update it must ignore that we are redirecting all pages to index.php (using .htaccess or PHP) and just keep the normal wordpress template system flow. For example: I could create a page with slug called home and use a front-page.php template and then it should generate a Page called Home based on the front-page template (as Wordpress normally does) .

To Resume:

  • I would like to redirect all pages to index.php using .htaccess (even better) or PHP
  • And when creating or editing a new page Wordpress should work just as normal for the front-end and back-end

Possible ways to solve it:

  • Use Wordpress rewrite rules with template_redirect
  • Another way to generate html template other than HTTP_API or OB_START.

Could someone help me out with this, please? II would be very nice!

Code:

        /**
         * When page (frontpage '/') loads or reloads then set a template_req session
         * at the template_redirect hook time (just before template_include).
         * After that redirect to index.php with redirect_all_pages_to_index_template() using
         * 'template_include' hook.
         *
         * */
        function angp_set_index_for_redirect() {

            if (!is_front_page()) return;

            angp_set_session('index.php', 'template_req');

        }

        add_action('template_redirect', 'angp_set_index_for_redirect', 10);


        /**
         * When pages (other then the frontpage) loads the first time  then set a
         * template_req_pages session at the wp_head(for page preview) and get_header(for frontend) hook time.
         * But redirection will just happens after page is reloaded from the second time onwards with
         * redirect_other_pages_to_index_template() using 'template_include' hook.
         *
         * */
        function angp_set_index_for_pages_redirect() {

            if (is_front_page()) return;
            angp_set_session('index.php', 'template_req_pages');

        }
        add_action('wp_head', 'angp_set_index_for_pages_redirect');
        add_action('get_header', 'angp_set_index_for_pages_redirect', 10);

            /**
             * when  '/' is reloaded (for the first time or not)
             * check if there is a  session key 'template_req'(that is set at template_redirect hook time
             * in angp_set_index_for_redirect()) and if yes redirect to  index.php
             *
             * */
            function redirect_all_pages_to_index_template($template) {
                global $pagenow;

                if (('template_include' == current_filter()) && $pagenow
                    == 'index.php'
                ) {

                    $key = 'template_req';
                    if (isset($_SESSION[$key])) {

                        $array = $_SESSION[$key];
                        $req_url = $array['url'];

                        $new_template = locate_template($req_url);

                        if ('' != $new_template) {

                            return $new_template;

                        }
                    }
                }

                return $template;
            }

            add_filter('template_include', 'redirect_all_pages_to_index_template', 10, 1);


            /**
             * when a page other then '/' is reloaded (for the first time or not)
             * check if there is a  session key 'template_req_pages' and , if yes redirect to index.php
             * The session 'template_req_pages' is set in set-index-redirect.php with get_header and wp_head
             * hooks
             * */
            function redirect_other_pages_to_index_template($template) {
                global $pagenow;

                if (('template_include' == current_filter()) && $pagenow
                    == 'index.php'
                ) {

                    $key = 'template_req_pages';
                    if (isset($_SESSION[$key])) {

                        $array = $_SESSION[$key];
                        $req_url = $array['url'];

                        $new_template = locate_template($req_url);

                        if ('' != $new_template) {

                            return $new_template;

                        }
                    }
                }

                return $template;
            }

            add_filter('template_include', 'redirect_other_pages_to_index_template', 20, 1);

            /**
             * This tells the browser at the init hook phase that we are loading a page for the first time
             * ever. It works for pages other then '/'. Redirection will be done by angularjs in app.js
             * MainCtrl
             *
             * */
            function angp_is_page_first_loaded() {
                if (!isset($_SESSION['template_req_onload'])) {
                    angp_set_session('template_req_onload', 'template_req_onload');

                }
            }

            add_action('init', 'angp_is_page_first_loaded', 10);

            /**
             * This tells the browser at the get_header hook phase to delete 'template_req_onload' after the
             * page is fully loaded, so that dont get into a redirection loop. It checks if $_COOKIE['is_page_loaded']
             * or $_SESSION['page_loaded'] were already set. *
             *
             * */
            function destroy_session_index_onload() {
                //cookie set in app.js
                if (isset($_COOKIE['is_page_loaded']) || isset($_SESSION['page_loaded'])) {
                    unset($_SESSION['template_req_onload']);

                }
            }

            add_action('get_header', 'destroy_session_index_onload', 20);

            /**
             * Set session page_loaded when page is fully loaded
             * $_COOKIE['is_page_loaded'] does the same for google chrome canary
             *
             * */

            function angp_page_fully_loaded() {
                angp_set_session('page_loaded', 'page_loaded');
            }
            add_action('wp_footer', 'angp_page_fully_loaded');
            add_action('get_footer', 'angp_page_fully_loaded', 20);

            /**
             * This code generates the angularjs html views templates
             * It uses HTTP-API with  wp_remote_get()
             * */
            function angp_get_template_content($new_status, $old_status) {
                global $post;

                if (isset($post->post_name)) {
                    $post_slug = $post->post_name;

                    $file = get_template_directory() . '/library/views/pages/' . $post_slug . '.html';

                    if (($old_status != 'trash' && $new_status == 'trash')) {
                        if (file_exists($file))
                            unlink($file);
                    }
                }
                if (($old_status != 'publish' && $new_status == 'publish') || did_action('wp_insert_post') === 1) {


                    angp_get_page_http_api(site_url(), 'newsloop');
                    $pages = get_pages(array('sort_order' => 'asc'));

                    if (!empty($pages))

                        foreach ($pages as $page) {

                            $slug = $page->post_name;
                            $url = get_page_link($page->ID);

                            angp_set_session('index.php', 'template_req');
                            angp_get_page_http_api($url, $slug);

                        }
                }
            }



            if ($_SERVER['REQUEST_URI'] == '/wp-admin/nav-menus.php'
                || (isset($_POST['action']) && $_POST['action'] == 'add-menu-item')
                || (@$_POST['post_type'] == 'post')
            ) return;


            add_action('quick_edit_custom_box', 'angp_get_template_content', 10,2);
            add_action('wp_insert_post', 'angp_get_template_content', 20, 2);
            add_action('transition_post_status', 'angp_get_template_content', 20, 2);
            add_action('wp_restore_post_revision', 'angp_get_template_content', 10, 2);

            if (!function_exists('angp_get_page_http_api')) {
                function angp_get_page_http_api($url, $slug) {
            /*
             * request a page extract content between tags <content></content> or <homenewsloop></homenewsloop>
             * */
                    $response = wp_remote_get($url);

                    if (is_wp_error($response) || (200 != wp_remote_retrieve_response_code($response))) {
                        wp_die('Request could not be executed.');

                    }

                    try {
                        $result = wp_remote_retrieve_body($response);
                        //extract content and pass it to a html template_generator
                        if ($url !== site_url()) {
                            preg_match_all('/<content[^>]*>(.*?)<\/content>/is', $result, $t);

                            angp_wp_to_angular_template_generator($slug, $t[1][0]);

                        } else {
                            preg_match_all('/<homenewsloop[^>]*>(.*?)<\/homenewsloop>/is', $result, $t);
                            angp_wp_to_angular_template_generator($slug, $t[1][0]);

                        }

                    } catch (Exception $ex) {
                        return $ex;

                    }

                }

            }

            if (!function_exists('wp_to_angular_template_generator')) {
                function angp_wp_to_angular_template_generator($slug, $body_response) {
                    if ($slug === 'newsloop') {
                        $file = get_template_directory() . '/library/views/loops/' . $slug . '.html';
                    } else {
                        $file = get_template_directory() . '/library/views/pages/' . $slug . '.html';
                    }

                    if (!empty($body_response)) {

                        try {
                            global $checkfile;

                            if(file_exists($file)){
                                $checkfile = file_get_contents($file);

                            }
                            //just write content if file content is empty or content is different than the
                            //$body_response
                            if ($body_response !== $checkfile || $checkfile === '' || !isset($checkfile)) {

                                file_put_contents($file, $body_response, LOCK_EX);

                                return false;
                            }

                        } catch (Exception $ex) {

                            return 'Could not write file!';
                        }
                    }
                }
            }

            if (!function_exists('angp_set_session')) {

                function angp_set_session($key_name, $template_req_name) {

                    $template_req = $key_name;
                    $key = $template_req_name;
                    $_SESSION[$key]['url'] = $template_req;

                }
            }
share|improve this question

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Browse other questions tagged or ask your own question.