1

How to create a function in a custom page and use it in single.php?

I have the custom page mypage.php

<?php
/* Template Name: Form */   

...

$myname = add_post_meta( $date, 'My Name', $name, true );

function name(){
if ($myname != ''){
    echo ="Hello World! ";
 }
}

get_header(); ?>

...
?>

Single page

<? php name(); ?>
brasofilo
  • 25,496
  • 15
  • 91
  • 179
golaz
  • 71
  • 7

1 Answers1

2

To have functions available in all theme template files, you need to put them inside the file /wp-content/themes/your-theme/functions.php.

Just move your function to it, and call it in any template (single, page, archives, category). Check the documentation: Functions File Explained.

And to make the logic of your code work, you'd need to use get_post_meta in the function:

function name(){
    $myname = get_post_meta('My Name');
    if ($myname != ''){
        echo "Hello World! ";
    }
}

PS: it's a bit strange that you're setting a post meta everytime the mypage.php template is loaded...

brasofilo
  • 25,496
  • 15
  • 91
  • 179
  • Thx, but why not work this code: if ($myname != ' '){ echo $myname; } – golaz Mar 02 '14 at 21:31
  • 1
    You need to learn debugging techniques in [WordPress](https://codex.wordpress.org/Debugging_in_WordPress) and [PHP](http://stackoverflow.com/questions/888/how-do-you-debug-php-scripts). Suggestions: try to use post meta names in low case and no spaces, ie, `*_post_meta('my_name')`; try to check for `isset($myname)`; and do a `var_dump($myname)`. Look in PHP manual to know more about this functions. Also, look in your HTML source code, you're echoing this before the ``. – brasofilo Mar 02 '14 at 21:36