QNimate

  • CoursesVideos
  • WP PremiumPlugins
  • DemosLab
  • Home
  • QIdea
  • QTrack
Home Carbon Ads Creating a One Page WordPress Theme

Creating a One Page WordPress Theme

one-page-wordpress-theme

In this tutorial we will see how to create a one page WordPress theme. One page WordPress theme is suitable for App landing page, portfolio, event etc sites. Its not suitable for blogs, ecommerce, forum sites etc.

DW Page Modern Single Page WordPress Theme

DW Page Modern Single Page WordPress Theme is one of the popular single page WordPress themes. Its a very good example about what functionalities a single page WordPress theme needs to contain.

Functionality of DW Page Theme

These are the functionalities of the theme

  • The home page template displays all other pages in a vertical order.
  • One of the pages contains the posts. When clicked they are viewed as popups.
  • Menu items internally link to the pages.
  • JavaScript is used to achieve smooth scrolling effect when menu items are clicked

Create a One Page WordPress Theme

We can create a one page wordpress theme from scratch or else we can edit existing themes to make them a one page wordpress theme. In this tutorial I am going to make the Twenty Twelve theme as single page theme. But if you want to create one from scratch then the procedure will be the same.

Create a Template file for Home Page

As the home page needs to display all other pages and posts we need to create a page template which does the same.

Create a file named single-page-theme.php. And put this code inside it

<?php
    /*
        Template Name: Single Page Theme Page
    */
?>

Programmatically Creating and Setting Home Page

Now we need to create a WordPress page with template Single Page Theme Page and set this as the home page.

This code does the same. Place it in functions.php file.

<?php

if(get_page_by_title("Home") == null)
{
    $post = array(
        "post_title" => "Home",
        "post_status" => "publish",
        "post_type" => "page",
        "menu_order" => "-100",
        "page_template" => "single-page-theme.php"
    );

    wp_insert_post($post);

    $home_page = get_page_by_title("Home");
    update_option("page_on_front",$home_page->ID);
    update_option("show_on_front","page");
}

Displays all Pages in Home Page

Place this code in our single-page-theme.php file to display all the pages in the home page.

<?php
    /*
        Template Name: Single Page Theme Page
    */



get_header(); ?>

    <div id="primary" class="site-content">
        <div id="content" role="main">
            <?php
                $args = array("post_type" => "page", "order" => "ASC", "orderby" => "menu_order");
                $the_query = new WP_Query($args);
            ?>
            <?php if(have_posts()):while($the_query->have_posts()):$the_query->the_post(); ?>
            <?php get_template_part("content", "page"); ?>
            <?php endwhile; endif; ?>
        </div><!-- #content -->
    </div><!-- #primary -->

<?php get_sidebar(); ?>
<?php get_footer(); ?>

?>

Here is a screenshot of how the home page of the site looks now.

Screen Shot 2014-10-21 at 1.07.49 pm

To change the order of the pages you need to change the value of the Order field in the Edit Page Attributes box in the admin panel.

Linking Menu Items to Internal Parts of Page

In a single page theme all menu items point to a page thats there in the home page. You shouldn’t link to a post as this will take user to another page which breaks the laws of sinle page theme.

This code automatically creates the menu items for internal linking. Put this code in functions.php file.

<?php

function new_nav_menu_items($items)
{
    $items = "";

    $args = array("post_type" => "page", "order" => "ASC", "orderby" => "menu_order");
    $the_query = new WP_Query($args);

    if($the_query->have_posts()):
        while($the_query->have_posts()):
            $the_query->the_post();
                $items .= '<li><a href="#post-'. get_the_ID() .'">' . get_the_title() . '</a></li>';           
        endwhile;
    else:
        echo "";
    endif;
    return $items;
}
add_filter("wp_nav_menu_items", "new_nav_menu_items");

This code automatically filters the menu items and adds the pages to the menu. Here the menu items are internally linking to the pages id #post-{ID}. In the content-page.php file you can see in line number 11 that every page content has a ID of format post-{ID}. When you click on the menu items the page scrolls to that WordPress page.

When you are creating a single page theme from scratch make sure you are flushing the page ID in to the id attribute of the page content block. So that clicking on menu items scrolls to the page.

In the below image you can see how the internal linking has been done
Screen Shot 2014-10-21 at 2.34.02 pm

Posts Shortcode

Now we want one of the pages to display posts. So we can create a shortcode for it.

Put this shortcode code in functions.php file and then use the shortcode in any page you like to.

<?php

function posts_callback($atts=null, $content=null)
{
    $args = array("post_type" => "post", "orderby" => "date", "order" => "DESC", "post_status" => "publish");
    $posts = new WP_Query($args);
    ?>
        <div style="text-align: center">
    <?php
    if($posts->have_posts()):
        while($posts->have_posts()):
            $posts->the_post();
            ?>
                <div style="display: inline-block; width: 300px; border-color: #333; border-style: solid; border-width: 2px; margin-top: 15px;">
                    <a href="javascript:post_popup('<?php echo get_the_ID(); ?>')"><?php echo get_the_title(); ?></a>
                </div>
            <?php
            $post_array = array(get_the_title(), get_the_permalink(), get_the_date(), wp_get_attachment_url(get_post_thumbnail_id()));
            array_push($posts_array, $post_array);
        endwhile;
        else:
            echo "";
            die();
    endif;

    ?>
        </div>
    <?php
}
add_shortcode("posts", "posts_callback");

Here you can see when post title is clicked a JavaScript function post_popup is called up. This functions retrieve the post content and displays as popup.

I place the shortcode [posts][/posts] in by Blog Posts page. This is how it looks in frontend

Screen Shot 2014-10-21 at 4.25.26 pm

Creating AJAX API to Retrieve Post Content

We need to create use WordPress AJAX API to create REST API for retrieving post content via AJAX.

Put this code in functions.php file. It takes a post id and returns its content.

<?php

function post_content()
{
    $post_id = $_GET["post_id"];
    $content_post = get_post($post_id);
    $content = $content_post->post_content;
    $content = apply_filters('the_content', $content);
    $content = str_replace(']]>', ']]&gt;', $content);
    echo $content;

    die();
}

add_action("wp_ajax_post_content", "post_content");
add_action("wp_ajax_nopriv_post_content", "post_content");

Retrieving Post Content and Displaying as Popup

This JavaScript code make a request to WordPress from frontend using AJAX and displays the post content as popup. Here for simplicity I used a alert box to display the content. For a real commercial theme you need to design your own popup.

Put this code in your functions.php file

<?php

function posts_popup()
{
    ?>
        <script>
            function post_popup(id)
            {
                var xhr = new XMLHttpRequest();
                xhr.open("GET", "<?php echo get_site_url(); ?>/wp-admin/admin-ajax.php?action=post_content&post_id="+id);
                xhr.onload = function(){
                    var content = xhr.responseText;
                    alert(content);
                }
                xhr.send();
            }
        </script>
    <?php
}
add_action("wp_head", "posts_popup");

One Page Twenty Twelve Theme Download

Download Now

Conclusion

In this tutorial I show the basic code snippets required for creating a one page WordPress theme and also I showed what a one page theme is and how it works.

Oct 21, 2014Narayan Prusty
Javascript Create File Object From URLFull Screen Scrolling with Page Piling Effect
Comments: 19
  1. Pawel Mansfeld
    5 years ago

    Amazing work! Tutorial perfectly done.

    ReplyCancel
  2. Raphael Erick Marcial
    5 years ago

    Using your new_nav_menu_items, I cannot view the custom links??? How can I display the custom links in my navbar??? Thank you.

    ReplyCancel
  3. User
    5 years ago

    Hello Narayan

    When you mention the part “Creating AJAX API to Retrieve Post Content” is that still up to date with the latest version of WordPress having an REST API backed into it?

    https://developer.wordpress.org/rest-api/

    I did a few themes, am a total performance nerd, love my critical CSS and async font loading etc, love to score 100 on PageSpeed and so on and would love to use this tutorial to build a single page app on top of WP, though I am wondering if that “Creating AJAX API to Retrieve Post Content” is not creating double the API with the function in functions.php.

    If this part is out of date would you mind sharing what it would look like these days?
    Happy to shoot you a few bucks as well for an in-depth singe page development procedure using the latest WP version.

    Hit me up on email and let’s discuss if you find the time. Basically looking for an up to date guide on how to get the best possible code for making single page websites with WP.

    Thanks and Peace :)

    ReplyCancel
  4. Cirocki
    6 years ago

    Well done. I personally use Onepress free theme and edit that theme, but this is not bad too.

    ReplyCancel
  5. Pierre-Yves
    7 years ago

    Hi there,

    I try to use this tutorial with twentysixtenn but it doesn’t works.
    Home page doesn’t display any content.

    Turn code to :

    <?php
    // Start the loop.
    $args = array("post_type" => "page", "order" => "ASC", "orderby" => "menu_order");
    $the_query = new WP_Query($args);

    while ($the_query->have_posts() ) : $the_query->the_post();

    // Include the page content template.
    get_template_part( 'template-parts/content', 'page' );

    }

    // End of the loop.
    endwhile;
    ?>

    It works with the twenty twelve template.

    Any ideas ?
    Thanks for helping.

    ReplyCancel
  6. Orèli
    7 years ago

    Thank you for this great tutorial.

    How when you have two menus on the home page. I can not seem to apply only to the primary menu.
    I know the solution is here: function new_nav_menu_items($items) {} but …

    Do you have the solution?

    Thank you in advance !

    ReplyCancel
  7. Paul
    7 years ago

    Thanks for nice tutorial.
    How do I style the pop up because the pop up displays the content with html tags

    ReplyCancel
  8. alex
    7 years ago

    Hello and thanks for this tutorial. I have a few problems though. First is with the menu, in wordpress admin even if I create a custom menu and put it as primary, or i try to delete some menu items, on the website all the pages created appear in the navigation menu (I can’t remove some pages from the navigation menu). Second problem is with the [posts][/posts] shortcut, I get the following error:
    WARNING: ARRAY_PUSH() EXPECTS PARAMETER 1 TO BE ARRAY, NULL GIVEN IN C:\WAMP\WWW...\WP-CONTENT\THEMES\TWENTYTWELVE\FUNCTIONS.PHP ON LINE 554 . Thank you again for this great tutorial.

    ReplyCancel
  9. emanuele
    7 years ago

    Hi,
    thanks and congratulations for your article.
    I want ask you if possible to exclude a page from the vertical order , and make it static.
    thank you
    best regards

    Emanuele

    ReplyCancel
    • Melanie
      7 years ago

      Do you already have an answer on your quation? I have the same question :)

      ReplyCancel
      • emanuele
        7 years ago

        No, but you can check this post…
        https://wordpress.org/support/topic/one-page-template-list-all-pages-content-how

        ReplyCancel
  10. Catfish
    7 years ago

    Hi!
    Its a very good article, thanks! Unfortunately, I have a problem with this tutorial, please help me find the right way for the solution.
    So, i use the bones wordpres starter theme. So, I use your singel-page-theme.php but dont apper nothings. I make som page with some test content, but the page title show in the nav bar, the content not show in the Home page!
    What do you think about my problem?

    ReplyCancel
  11. Jørgen
    7 years ago

    I’ll just second Patrick. Great tutorial! Right to the point, and just what I needed to go on. Thanks.

    ReplyCancel
  12. Zubaer
    7 years ago

    Thanks Narayan, your article helped me. However, maxero has given solution to Nav Menu. I faced another problem with array_push() and eventually managed to solve it.
    It will be array_push($post_array, $post_array); instead of array_push($posts_array, $post_array);
    because $posts_array isn’t actually defined.

    ReplyCancel
    • Philipp
      7 years ago

      Thanks Zubaer for your comment. I run in same issue and fixed it also with using:

      array_push($post_array, $post_array);

      ReplyCancel
  13. Zubaer
    7 years ago

    Thanks man! I have learned many things.

    ReplyCancel
  14. Maxero
    7 years ago

    Your process seems totally logic and is very much appreciated, however it doesn’t work for me. :/
    The one page is there yes but as soon as you want to go to one of the “page” (let’s take portfolio for exemple) you actually land in a new page rather than internal home page.
    I tried your technique on my own theme then tryied the twenty twelve you kindly uploaded but still have the same problem.
    Beside, thanks a lot for taking time to create this tuto, even if it doesn’t work for me there is a lot to take :)

    ReplyCancel
    • maxero
      7 years ago

      Ok so, I kept searching why it wasn’t working and found (what I think is the solution).
      If you’re using twenty twelve theme:
      1. Create pages
      2. Go to menu options
      3. Save the actual menu
      4. Then choose that menu as your main menu.

      I dunno maybe I skipped one step of the tutorial and didn’t see this had to be done.
      Anywy, many thanks to you NARAYAN, I was really looking for a quick one page solution and there is everything here.
      Thanks a lot

      ReplyCancel
  15. Patrick
    8 years ago

    Lightweight and understandable tutorial. Thank you for your work and best regards from Germany, Patrick

    ReplyCancel

Leave a Reply to Raphael Erick Marcial Cancel reply

To create code blocks or other preformatted text, indent by four spaces:

    This will be displayed in a monospaced font. The first four
    spaces will be stripped off, but all other whitespace
    will be preserved.
    
    Markdown is turned off in code blocks:
     [This is not a link](http://example.com)

To create not a block, but an inline code span, use backticks:

Here is some inline `code`.

For more help see http://daringfireball.net/projects/markdown/syntax

Narayan Prusty

I am a software engineer specialising in Blockchain, DevOps and Go/JavaScript. This is my personal blog where I write about things that I learn and feel interesting to share.

Image8 years ago 23 Comments WordPress
Share this
0
GooglePlus
0
Facebook
0
Twitter
0
Linkedin
  • DW Page Modern Single Page WordPress Theme
  • Functionality of DW Page Theme
  • Create a One Page WordPress Theme
  • Create a Template file for Home Page
  • Programmatically Creating and Setting Home Page
  • Displays all Pages in Home Page
  • Linking Menu Items to Internal Parts of Page
  • Posts Shortcode
  • Creating AJAX API to Retrieve Post Content
  • Retrieving Post Content and Displaying as Popup
  • One Page Twenty Twelve Theme Download
  • Conclusion
Related Articles
  • WordPress Frontend Twitter OAuth Login
  • WordPress Frontend Facebook Login
  • Multi-language WordPress Theme and Site
  • Intel XDK App using WordPress Backend
  • Advanced Guidelines To WordPress Theme Development
Our Sponsor
My Books

2014 - 2015 © QNimate
All tutorials MIT license