How can I add IP address to my post?

After completing the form, the following information should be displayed: Product price [product name], is: [calculated gross amount] PLN gross, tax amount is [calculated tax amount] PLN. ” Data from the form are to be saved to a separate CPT. In addition to the data from the form should also sign up IP and date of completing the form. - thats my task


if(!empty($_SERVER[HTTP_CLIENT_IP]))
{
    $ip = $_SERVER[HTTP_CLIENT_IP];
}

elseif(!empty($_SERVER[HTTP_X_FORWARDED_FOR]))
{
    $ip = $_SERVER[HTTP_X_FORWARDED_FOR];
}

else
{
    $ip=$_SERVER[REMOTE_ADDR];
}


function cptpost()
{
    //create post object
    $userid=get_current_user_id();
    $my_post=array(
        'post_title' = wp_strip_all_tags ($_POST['name']),
        'post_content' = PRODUCT:  .$_POST['name']. . PRICE:  .$_POST['price'].  VAT:  .$_POST['vat'].   %. ,
        'post_status' = 'publish',
        'post_author' = 1,
        
        
        
);


wp_insert_post($my_post);
}
add_action('wp_head', 'cptpost');

I don't know how to add the ip address to the 'post_content' I want in my post something like PRODUCT: [product], PRICE: [price], VAT: [vat], IP: [ip]

Topic ip plugin-development plugins Wordpress

Category Web


I've modified your code and moved $ip inside the function. That way the variable is easily accessible from the function itself.

function cptpost() {
    if (!empty($_SERVER["HTTP_CLIENT_IP"])) {
        $ip = $_SERVER["HTTP_CLIENT_IP"];
    } elseif (!empty($_SERVER["HTTP_X_FORWARDED_FOR"])) {
        $ip = $_SERVER["HTTP_X_FORWARDED_FOR"];
    } else {
        $ip = $_SERVER["REMOTE_ADDR"];
    }
    $dateTime = date("Y/m/d g:i:sa")


    //create post object
    $userid = get_current_user_id();
    $my_post = array(
        'post_title' => wp_strip_all_tags($_POST['name']),
        'post_content' => "PRODUCT: " . $_POST['name'] . ". PRICE: " . $_POST['price'] . " VAT: " . $_POST['vat'] .  " %. IP:".$ip." Date:".$dateTime,
        'post_status' => 'publish',
        'post_author' => 1,
    );
    wp_insert_post($my_post);
}
add_action('wp_head', 'cptpost');

Note: I assume your existing code was working for the post insert part. I just rearranged the code to make sure IP is included.

About

Geeks Mental is a community that publishes articles and tutorials about Web, Android, Data Science, new techniques and Linux security.