Cody King
Cody King

Reputation: 11

Why won't this form display properly from Wordpress shortcode?

<?php
/**
 * Plugin Name: Display UserID
 * Plugin URI: http://www.sitecrafters.pro/plugins/measurement-tracker.zip
 * Description: The very seventh plugin that I have ever created.
 * Version: 1.10
 * Author: Cody King
 * Author URI: http://sitecrafters.pro
 */

/**
 * @snippet       Display UserID
 * @author        Cody King
 * @compatible    Wordpress 6.0
 */

function show_form(){
    $user_id = get_current_user_id();
    echo '<form method="GET">'; // printing form tag
    echo '<input type="text" name="inches">';
    echo '<input type="submit" name="send_btn" value="Submit">';
    echo '</form>';
    if (isset($_GET['send_btn'])) { // checking is form was submitted  then accessing to value
        $bicep = $_GET['inches'];
        if ($user_id == 0) {
        // The user ID is 0, therefore the current user is not logged in
                return; // escape this function, without making any changes to database
            }
        update_user_meta($user_id,'_bicep_measurement',$bicep);
        return "Today your bicep is: $bicep inches!";
    }
}
add_shortcode('show_form','show_form');

function checkBiceps(){
        $user_id = get_current_user_id();
        $bicep = get_user_meta($user_id,'_bicep_measurement',true);
        return "Your bicep was: $bicep inches last time";
}
add_shortcode('check_biceps','checkBiceps');
?>

This is a plugin I'm making to track body part measurements for WordPress users. I have gotten the shortcode to work, and it makes a functional input box... Up in the top corner.

For some reason, this form is being displayed in the upper left corner instead of inline, where I put the shortcode. What am I doing wrong here?

I admit, I'm new to this programming language and making Wordpress plugins but I want to learn.

Upvotes: 0

Views: 94

Answers (1)

IT goldman
IT goldman

Reputation: 19485

Like this:

<?php
function show_form()
{
    $user_id = get_current_user_id();
    $str = "";
    $str .= '<form method="GET">'; // printing form tag
    $str .= '<input type="text" name="inches">';
    $str .= '<input type="submit" name="send_btn" value="Submit">';
    $str .= '</form>';
    if (isset($_GET['send_btn'])) { // checking is form was submitted  then accessing to value
        $bicep = $_GET['inches'];
        if ($user_id == 0) {
            // The user ID is 0, therefore the current user is not logged in
            return; // escape this function, without making any changes to database
        }
        update_user_meta($user_id, '_bicep_measurement', $bicep);
        return "Today your bicep is: $bicep inches!";
    }
    return $str;
}
add_shortcode('show_form', 'show_form');


Upvotes: 1

Related Questions