• Resolved GarrettB

    (@garrettb)


    I would like to know how/where to include my PHP code, within WordPress, so that it is not processed too early.

    I find it hard to write the question properly because I don’t know enough to know what to ask!
    So I have detailed the setup I have right now, and what is wrong with it – so then maybe someone can understand what I need to do and enlighten me.
    Thanks in advance for any help / suggestions.

    Current setup:
    I have defined a function, my_function() in a new php file, my_file.
    This file is located in the wp-content folder.
    To register this folder, I added the following line in functions.php:
    include(WP_CONTENT_DIR.'/my_file.php');
    The my_function() runs a MySQL query, and outputs the result.
    I added a shortcode for this function in functions.php:
    add_shortcode('my_function_sc', 'my_function');
    When I add this short code to a page, and navigate to the page, all is well – the query results are displayed.

    However, I notice that this short code seems to be processed before any other content that I add to the page.
    For example, if I type the following in to the text field for a new page:

    Hello 1 2 3
    [my_function_sc]
    Goodbye 4 5 6

    And then open the page in a browser, I see the following
    Results from query
    Hello 1 2 3
    Goodbye 4 5 6

    Question:
    What is the preferred way to organise my PHP code so that I can call a shortcode ‘inline’, from the text field of a page?
    Using the above example, I want the output to be:
    Hello 1 2 3
    Results from query
    Goodbye 4 5 6

    If you just tell me in a few sentences what the best way to do this is, I can then research it etc.
    Because I am new to WordPress. I find it difficult knowing what terms to search for etc.
    I have read a little about ‘hooks’ and it seems that I need to hook the code to the right part of WordPress so that it is run while the content of the text field is being processed.

    Thanks

    Garrett

Viewing 5 replies - 1 through 5 (of 5 total)
  • Moderator Steven Stern (sterndata)

    (@sterndata)

    Volunteer Forum Moderator

    My bet is that your code echoes its output rather than returning it as a string. Shortcodes must not echo — they return a string.

    Thread Starter GarrettB

    (@garrettb)

    Thanks for the quick response – yes you are right 🙂

    Then maybe I am using a shortcode for the wrong purpose?
    I wanted to add a search field and button to a page, where the user types in a search term, and then clicks the button. Then the results are output.
    The original code started off as a HTML form, then was added into a PHP function, where each line of HTML was encased in an echo command – pretty messy stuff!!!
    Here’s an example to give you an idea – excuse the formatting (lack of etc).

    Garrett

    function my_function()
    {
      global $wpdb;
      
      echo '<div class="wrap">';
      echo '<form action="" method="post">';
      echo 'Search for: <input type="text" name="search_txt" value="" /><br/>';
      echo '<input name="Submit" type="submit" value="Submit">';
      echo '</form>';
      echo '<form method="post">';
      $search_text = filter_input(INPUT_POST, 'search_txt');
                      
      if (empty($search_text)) {
        echo 'Nothing to look for yet...';
      } else {
        $search_table = $wpdb->prefix."table1";
        $search_text = '%'.$search_text.'%';
        $retrieve_data = $wpdb->get_results( 
                          $wpdb->prepare("SELECT * FROM $search_table WHERE <code>field1</code> LIKE %s ORDER BY <code>name</code> ASC ", $search_text) 
                         );
        echo '<ul>';
          foreach ($retrieve_data as $retrieved_data){ 
            echo '<li>';
             echo $retrieved_data->name;
               echo '<ul>';
                 echo '<li>Name: ';
                 echo $retrieved_data->name;
                 echo '</li>';
                 echo '<li>Address: ';
                 echo $retrieved_data->address;
                 echo '</li>';
               echo '</ul>';
             echo '</li>';
           }
         echo '</ul>';                 
        }                  
        echo '</form>';
       echo '</div>';
    }
    Moderator Steven Stern (sterndata)

    (@sterndata)

    Volunteer Forum Moderator

    If you use an ob_start() at the top and then return ob_get_clean(); at the end, you can work around all those echoes.

    As to whether your code will do what you want… I’m not sure of that. 🙂

    Moderator bcworkz

    (@bcworkz)

    Shortcodes are great for elements you want in your post or page content. If you want your search field/button elsewhere, not so much. If you’d rather they be in one of your theme’s widget areas, then a widget is a better solution. If not content or widget area, then altering or creating a template via a child_theme is the solution.

    Thread Starter GarrettB

    (@garrettb)

    Thank you Steve Stern and bcworkz for your replies.

    Steve, I did as you suggested, and after a few tries I got it working exactly how I wanted to!
    Essentially, I put the following wrapper around the code in my function:

    ob_start();
    	.
    	.
    	PHP and HTML code
    	.
    	.
    	.
     
    $outputString = ob_get_contents();
    ob_end_clean();
         
    return $outputString;

    For anyone else who stumbles across this, this is how it seems to work:
    ob_start(); starts buffering all output until further notice (or until the end of the PHP script), so that the echo commands or any other output commands are not actually output there and then – but just stored in the output buffer (hence the ‘ob’)..
    $outputString = ob_get_contents();copies the buffered content into a string.
    ob_end_clean();flushes the buffer (I am finished with it now, after copying the contents to a string).
    return $outputString; returns (in a string) the complete output of my function at run-time, so I get the following:

    Hello 1 2 3
    <em>Results from query</em>
    Goodbye 4 5 6

    bcworkz – thanks for the advice.
    Now that I have my shortcode working, and learnt a nice lesson, I will start looking at plugins and widgets.

    Thanks again!

    Garrett

Viewing 5 replies - 1 through 5 (of 5 total)

The topic ‘Where to locate my PHP code’ is closed to new replies.