0

I created a page template and put it as the theme for a page. After that i have chosen this page as a page section in the twenty seventeen theme options but the content of this page is not shown just if you access the page directly and not as a page section.

<?php
/*
Template Name: Contact
*/
?>

<?php
if(isset($_POST['submitted'])) {
    if(trim($_POST['contactName']) === '') {
        $nameError = 'Please enter your name.';
        $hasError = true;
    } else {
        $name = trim($_POST['contactName']);
    }

    if(trim($_POST['email']) === '')  {
        $emailError = 'Please enter your email address.';
        $hasError = true;
    } else if (!preg_match("/^[[:alnum:]][a-z0-9_.-]*@[a-z0-9.-]+\.[a-z]{2,4}$/i", trim($_POST['email']))) {
        $emailError = 'You entered an invalid email address.';
        $hasError = true;
    } else {
        $email = trim($_POST['email']);
    }

    if(trim($_POST['comments']) === '') {
        $commentError = 'Please enter a message.';
        $hasError = true;
    } else {
        if(function_exists('stripslashes')) {
            $comments = stripslashes(trim($_POST['comments']));
        } else {
            $comments = trim($_POST['comments']);
        }
    }

    if(!isset($hasError)) {
        $emailTo = get_option('tz_email');
        if (!isset($emailTo) || ($emailTo == '') ){
            $emailTo = get_option('admin_email');
        }
        $subject = '[PHP Snippets] From '.$name;
        $body = "Name: $name \n\nEmail: $email \n\nComments: $comments";
        $headers = 'From: '.$name.' <'.$emailTo.'>' . "\r\n" . 'Reply-To: ' . $email;

        wp_mail($emailTo, $subject, $body, $headers);
        $emailSent = true;
    }

} ?>
<?php get_header(); ?>
    <div id="container">
        <div id="content">

            <?php if (have_posts()) : while (have_posts()) : the_post(); ?>
            <div <?php post_class() ?> id="post-<?php the_ID(); ?>">
                <h1 class="entry-title"><?php the_title(); ?></h1>
                    <div class="entry-content">
                        <?php if(isset($emailSent) && $emailSent == true) { ?>
                            <div class="thanks">
                                <p>Thanks, your email was sent successfully.</p>
                            </div>
                        <?php } else { ?>
                            <?php the_content(); ?>
                            <?php if(isset($hasError) || isset($captchaError)) { ?>
                                <p class="error">Sorry, an error occured.<p>
                            <?php } ?>

                        <form action="<?php the_permalink(); ?>" id="contactForm" method="post">
                            <ul class="contactform">
                            <li>
                                <label for="contactName">Name:</label>
                                <input type="text" name="contactName" id="contactName" value="<?php if(isset($_POST['contactName'])) echo $_POST['contactName'];?>" class="required requiredField" />
                                <?php if($nameError != '') { ?>
                                    <span class="error"><?=$nameError;?></span>
                                <?php } ?>
                            </li>

                            <li>
                                <label for="email">Email</label>
                                <input type="text" name="email" id="email" value="<?php if(isset($_POST['email']))  echo $_POST['email'];?>" class="required requiredField email" />
                                <?php if($emailError != '') { ?>
                                    <span class="error"><?=$emailError;?></span>
                                <?php } ?>
                            </li>

                            <li><label for="commentsText">Message:</label>
                                <textarea name="comments" id="commentsText" rows="20" cols="30" class="required requiredField"><?php if(isset($_POST['comments'])) { if(function_exists('stripslashes')) { echo stripslashes($_POST['comments']); } else { echo $_POST['comments']; } } ?></textarea>
                                <?php if($commentError != '') { ?>
                                    <span class="error"><?=$commentError;?></span>
                                <?php } ?>
                            </li>

                            <li>
                                <input type="submit">Send email</input>
                            </li>
                        </ul>
                        <input type="hidden" name="submitted" id="submitted" value="true" />
                    </form>
                <?php } ?>
                </div><!-- .entry-content -->
            </div><!-- .post -->

                <?php endwhile; endif; ?>
        </div><!-- #content -->
    </div><!-- #container -->

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

I hope you can help me guys. Thanks in advance! :)

Edit:

The website with the custom page template is displayed when you access the page directly like for example http://example.com/testing.

direct link

But if you want to set it as a page section in the twentyseventeen theme under the theme options the space, where the custom template should appear, is blank. This is the case if you access it via http://example.com. The site is a onepager and the testing page with the custom page template is a section of it.

front page

2nd Edit:

I set the custom page as a page section by just setting it in the theme options.

theme options of twentyseventeen theme

1 Answers1

0

You're trying to use wordpress functions out of wordpress. Place this code require_once($_SERVER['DOCUMENT_ROOT'] . '/wp-load.php'); directly to next line of opening php tag <?php at 8th line of your code.

This may not work if your wordpress installation is on some folder of your main server directory. Then you can try this one:

//place this at the same position, as I mentioned above
$needPath = realpath(__DIR__ . '/../../..');
require_once($needPath . '/wp-load.php');

Used solution from here to go several levels up in the filesystem. Because we need to go to main wordpress installation folder from {wp-main-folder}/wp-content/themes/twentyseventeen/{your-file}, we should to go 3 levels up for reaching wp-load.php file.

EDIT

Also, it will be useful to check, if your page is called from/out of your wordpress installation. So, you can use this solution for it:

//place this to the same place as described above
if(!defined(ABSPATH)) {
    $needPath = realpath(__DIR__ . '/../../..');
    require_once($needPath . '/wp-load.php');
}

Tested and working

Edit: more detailed

<?php
/*
Template Name: Contact
*/
if(!defined(ABSPATH)) {
    $needPath = realpath(__DIR__ . '/../../..');
    require_once($needPath . '/wp-load.php');
}

if(isset($_POST['submitted'])) {
    if(trim($_POST['contactName']) === '') {
        $nameError = 'Please enter your name.';
        $hasError = true;
    } else {
        $name = trim($_POST['contactName']);
    }

    if(trim($_POST['email']) === '')  {
        $emailError = 'Please enter your email address.';
        $hasError = true;
    } else if (!preg_match("/^[[:alnum:]][a-z0-9_.-]*@[a-z0-9.-]+\.[a-z]{2,4}$/i", trim($_POST['email']))) {
        $emailError = 'You entered an invalid email address.';
        $hasError = true;
    } else {
        $email = trim($_POST['email']);
    }

    if(trim($_POST['comments']) === '') {
        $commentError = 'Please enter a message.';
        $hasError = true;
    } else {
        if(function_exists('stripslashes')) {
            $comments = stripslashes(trim($_POST['comments']));
        } else {
            $comments = trim($_POST['comments']);
        }
    }

    if(!isset($hasError)) {
        $emailTo = get_option('tz_email');
        if (!isset($emailTo) || ($emailTo == '') ){
            $emailTo = get_option('admin_email');
        }
        $subject = '[PHP Snippets] From '.$name;
        $body = "Name: $name \n\nEmail: $email \n\nComments: $comments";
        $headers = 'From: '.$name.' <'.$emailTo.'>' . "\r\n" . 'Reply-To: ' . $email;

        wp_mail($emailTo, $subject, $body, $headers);
        $emailSent = true;
    }

} ?>
<?php get_header(); ?>
    <div id="container">
        <div id="content">

            <?php if (have_posts()) : while (have_posts()) : the_post(); ?>
                <div <?php post_class() ?> id="post-<?php the_ID(); ?>">
                    <h1 class="entry-title"><?php the_title(); ?></h1>
                    <div class="entry-content">
                        <?php if(isset($emailSent) && $emailSent == true) { ?>
                            <div class="thanks">
                                <p>Thanks, your email was sent successfully.</p>
                            </div>
                        <?php } else { ?>
                            <?php the_content(); ?>
                            <?php if(isset($hasError) || isset($captchaError)) { ?>
                                <p class="error">Sorry, an error occured.<p>
                            <?php } ?>

                            <form action="<?php the_permalink(); ?>" id="contactForm" method="post">
                                <ul class="contactform">
                                    <li>
                                        <label for="contactName">Name:</label>
                                        <input type="text" name="contactName" id="contactName" value="<?php if(isset($_POST['contactName'])) echo $_POST['contactName'];?>" class="required requiredField" />
                                        <?php if($nameError != '') { ?>
                                            <span class="error"><?=$nameError;?></span>
                                        <?php } ?>
                                    </li>

                                    <li>
                                        <label for="email">Email</label>
                                        <input type="text" name="email" id="email" value="<?php if(isset($_POST['email']))  echo $_POST['email'];?>" class="required requiredField email" />
                                        <?php if($emailError != '') { ?>
                                            <span class="error"><?=$emailError;?></span>
                                        <?php } ?>
                                    </li>

                                    <li><label for="commentsText">Message:</label>
                                        <textarea name="comments" id="commentsText" rows="20" cols="30" class="required requiredField"><?php if(isset($_POST['comments'])) { if(function_exists('stripslashes')) { echo stripslashes($_POST['comments']); } else { echo $_POST['comments']; } } ?></textarea>
                                        <?php if($commentError != '') { ?>
                                            <span class="error"><?=$commentError;?></span>
                                        <?php } ?>
                                    </li>

                                    <li>
                                        <input type="submit">Send email</input>
                                    </li>
                                </ul>
                                <input type="hidden" name="submitted" id="submitted" value="true" />
                            </form>
                        <?php } ?>
                    </div><!-- .entry-content -->
                </div><!-- .post -->

            <?php endwhile; endif; ?>
        </div><!-- #content -->
    </div><!-- #container -->

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

For calling this template from wordpress. you need to call it like( if your website url is http://example.com ):

Create page from wordpress dashboard and choose from the list template on the right side of create page section instead of Default Template the one you want to use:

how it looks

After it( dont forget to add page title ) save page and go to the url, provided there. If page don't have parent, or permalinks are as ?p=123 then you should access that page like here: http://example.com/your-page-title.

If you're going to access that template directly, you should write url as http://example.com/wp-content/themes/twentyseventeen/your-template-filename.php. This example provided as your template is directly in your twentyseventeen theme folder.

Samvel Aleqsanyan
  • 2,812
  • 4
  • 20
  • 28
  • it still doesn't work :( i get this error message when i use the second code example Warning: realpath() [function.realpath]: open_basedir restriction in effect. File(/users/welcomedinner) is not within the allowed path(s): (/users/welcomedinner/www:/users/_temp/welcomedinner) in /users/welcomedinner/www/wp-content/themes/twentyseventeen/template.php on line 8 Warning: require_once(/wp-load.php) [function.require-once]: failed to open stream: No such file or directory in /users/welcomedinner/www/wp-content/themes/twentyseventeen/template.php on line 9 – user3455536 Jan 09 '18 at 19:34
  • Sorry for the late response but i was sick unfortunately. I tried it again but it still doesn't work and there are no error messages appearing. Perhaps you get me wrong because the site and the content of the page template is displayed correctly when i open it normally. It is just not shown at all if it is set as a page section in the one pager of twentyseventeen. Sorry for all the trouble and thanks for the help you were giving me so far. I really appreciate it. – user3455536 Jan 14 '18 at 15:31
  • the answer was updated. try again, or if you'll get white screen, make sure, that your debug mode is enabled. – Samvel Aleqsanyan Jan 14 '18 at 16:22
  • The front page section is still blank. "Create page from wordpress dashboard and choose from the list template on the right side of create page section instead of Default Template the one you want to use:" By the way what do you mean by right side of create page section because i just created a normal page in the backend of wordpress and then set "Contact" as the Page Template – user3455536 Jan 14 '18 at 22:11
  • yes I mean that which you done about template part, I don't know your wp knowledge. what you mean with `The front page section is still blank`? what front page? if you;re trying to access template directly, it won't be front page – Samvel Aleqsanyan Jan 14 '18 at 23:46
  • With front page i mean the starting page like for example http://example.com/. This front page is set up as a one pager with the twentyseventeen theme and the custom page is one page section of this onepager. Btw i updated my post with some pictures, hope they can help :) – user3455536 Jan 17 '18 at 11:02
  • @user3455536 so, this is another problem. the code I provided you can use throught direct access of file, and using as `template` for some page. how do tou trying to add this template in the front-page as section? – Samvel Aleqsanyan Jan 17 '18 at 11:27
  • Sorry i might have not been that clear about this. I updated my main post with a picture of where i set it. :) – user3455536 Jan 17 '18 at 11:47
  • any suggestions? :) – user3455536 Jan 18 '18 at 09:30