Jump to content

WordPress custom obtaining user ID.


LazyDragon

Recommended Posts

Hello!I'm having trouble with getting an user id on wordpress. I'd appreciate if anyone can take a look what could be wrong with methods I'm trying?getuserid.php - file in which I'm trying to make functions to obtain current user id

including: user.php and pluggable.php from wp-includes

 

 

The function reference:https://codex.wordpress.org/Function_Reference/get_current_user_id

I'm adding code to my getuserid.php

$user_ID = get_current_user_id();

and getting:

Uncaught ReferenceError: get_current_user_id is not defined

 

 

What's wrong? I'm having user.php included

Edited by LazyDragon
Link to comment
Share on other sites

Is getuserid.php a copy of page.php that include access to pages to use get_current_user_id()? Custom pages uzually begin page-slugname.php so yours would be page-getuserid.php, and don't understand 'trying to MAKE functions to obtain current user id' is it not what get_current_user_id(); DOES? you are making functions that already exist to do just that?

Link to comment
Share on other sites

Well as you've said already it's surely my mistake of directory locations etc. I just couldn't get this user id on my custom form which was made by interface (add page) and is handled by included files handler of php and js...Trying make this function is a result of hardcore web farming about how to do this anyways as it just didn't want to work...I don't understand this slug system and where is the place I can add result this function (like user id) to the result of form user filled in.

 

editCould you please provide any lecture that will clarify the problem of mine?

Edited by LazyDragon
Link to comment
Share on other sites

copy page.php and rename, add template name and code for retrieving current user id like below.

<?php/** * The template for displaying all pages. * * This is the template that displays all pages by default. * Please note that this is the WordPress construct of pages * and that other 'pages' on your WordPress site will use a * different template. * * @package WordPress * @subpackage Twenty_Ten * @since Twenty Ten 1.0 *//* Template Name: Get UserId Page */ get_header(); ?>		<div id="container">			<div id="content" role="main">			<?php			/* Run the loop to output the page.			 * If you want to overload this in a child theme then include a file			 * called loop-page.php and that will be used instead.			 */			get_template_part( 'loop', 'page' );						$user_ID = get_current_user_id();			echo '<p>xxxx User ID:'.$user_ID.' xxxx</p>'; //show user id			?>			</div><!-- #content -->		</div><!-- #container --><?php get_sidebar(); //remove if not required?><?php get_footer(); ?>

Go to dashboard -> Pages -> create new page, select from dropdown your new template page 'Get UserId Page', save an preview, now you should see your id number appear similar to 'xxxx User ID:1 xxxx' 1 being the admin user id

Link to comment
Share on other sites

I've change template1 code to

<?php// =============================================================================// PAGE.PHP// -----------------------------------------------------------------------------// Handles output of individual pages.//// Content is output based on which Stack has been selected in the Customizer.// To view and/or edit the markup of your Stack's pages, first go to "views"// inside the "framework" subdirectory. Once inside, find your Stack's folder// and look for a file called "wp-page.php," where you'll be able to find the// appropriate output.// =============================================================================?>		<div id="container">			<div id="content" role="main"><?phpx_get_view( x_get_stack(), 'wp', 'page' ); $user_ID = get_current_user_id();echo '<p>xxxx User ID:'.$user_ID.' xxxx</p>'; ?>			</div><!-- #content -->		</div><!-- #container -->

Used this template to create new page but nothing happened...

Link to comment
Share on other sites

It is. It's just the X Theme from Themeco and I guess it works just a little different then standar template. Anyways support of themeco refuses help in obtaining user id :(

 

edit: or not. It's even the same thing - mine is just very blank template without sidebars or footers but its the same function type that loads content

get_template_part( 'loop', 'page' ); and x_get_view( x_get_stack(), 'wp', 'page' );

 

Anyways it doesn't work

Edited by LazyDragon
Link to comment
Share on other sites

It needs to be included in handler php file or hook it to the page I need with new theme function like this:

function nameOfFunction() {   if(is_page(940)){      wp_enqueue_script( 'attachingHeader', 'PATHTOFILE');   }}add_action( 'wp_enqueue_scripts', 'nameOfFunction' );

?

 

edit

I've included wpLoad as in example above, after adding $user_ID = get_current_user_id(); to php handler file - it just doesn't work without any visible errors - I mean the form, doesn't proceed on final step (it's jQuery custom step form) anyways usually was error like user_ID is not defined or so..

Edited by LazyDragon
Link to comment
Share on other sites

I have enqueued js steps and validation libraries, js handler and php handler.

 

 

So my (simplified) custom form page looks pretty much like:

<form id="example-form" action="#">  <div>    <h3>Verification</h3>    <section>      <p>Please upload following documents:</p>      <div id="dynamicInput" style="float: left; padding: 0px; margin: 0px;">        <label for="idpass">Scan or photo of your ID or passport</label>        <input type="file" name="idpass" id="idpass" class="required" style="width:250px;" />      </div>      <div style="clear:both;">        <label for="adrprf">Proof of Adress</label>        <input type="file" name="adrprf" id="adrprf" class="required" style="width:250px;" />      </div>    </section>...etc

My jQuery handler

jQuery(function ($) {var form = $("#example-form");form.validate({    errorPlacement: function errorPlacement(error, element) { element.before(error); },    rules: {        confirm: {            equalTo: "#password"        }    }});$("input[name='idpass']").each(function () {    $(this).rules('add', {        required: true,        accept: "image/jpeg, image/pjpeg, image/png, image/bmp"    })});$("input[name='idpass2']").each(function () {    $(this).rules('add', {        accept: "image/jpeg, image/pjpeg, image/png, image/bmp"    })});$("input[name='adrprf']").each(function () {    $(this).rules('add', {        required: true,        accept: "image/jpeg, image/pjpeg, image/png, image/bmp"    })});form.children("div").steps({    headerTag: "h3",    bodyTag: "section",    transitionEffect: "slideLeft",    onStepChanging: function (event, currentIndex, newIndex)    {        form.validate().settings.ignore = ":disabled,:hidden";        return form.valid();    },    onFinishing: function (event, currentIndex)    {        form.validate().settings.ignore = ":disabled";        return form.valid();    },    onFinished: function (event, currentIndex)    {		var proceed = true;				var m_data = new FormData();    		m_data.append( 'idpass', $('input[name=idpass]')[0].files[0]);		m_data.append( 'adrprf', $('input[name=adrprf]')[0].files[0]);		m_data.append( 'fb', $('input[name=fb]').val());		if ($("#idpass2").val()) { 		m_data.append( 'idpass2', $('input[name=idpass2]')[0].files[0]);		};									$.ajax({			url: '../wp-content/themes/x/anewpartner.php',				data: m_data,				processData: false,				contentType: false,				type: 'POST',				dataType:'json',				success: function(response){				 //load json data from server and output message     				if(response.type == 'error'){  					output = '<div class="error">'+response.text+'</div>';				}else{					window.location.href = "www.redirectionplace.com";				}				$("#example-form #contact_results").hide().html(output).slideDown();			  }		});             }});});

and PHP

<?php if($_POST){    $to_email       = "email@email.com";    $from_email     = "email@email.com";        //check if its an ajax request, exit if not    if(!isset($_SERVER['HTTP_X_REQUESTED_WITH']) AND strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) != 'xmlhttprequest') {        $output = json_encode(array( //create JSON data            'type'=>'error',            'text' => 'Sorry Request must be Ajax POST'        ));        die($output); //exit script outputting json data    }       //Sanitize input data using PHP filter_var().    $fb     = filter_var($_POST["fb"], FILTER_SANITIZE_STRING);	$id     = filter_var($_POST["id"], FILTER_SANITIZE_STRING);	$subject = "Subject";									    //additional php validation    if(strlen($fb)<1){ // If length is less than 4 it will output JSON error.        $output = json_encode(array('type'=>'error', 'text' => 'Add facebook profile'));        die($output);    }	else {	       //email body    $message_body = "Facebook: ".$fb."n UserID: ".$id;    ### Attachment Preparation ###    $file_attached = false;    $file2_attached = false;	$file3_attached = false;    if(isset($_FILES['idpass'])) //check uploaded file    {        //get file details we need        $file_tmp_name    = $_FILES['idpass']['tmp_name'];        $file_name        = $_FILES['idpass']['name'];        $file_size        = $_FILES['idpass']['size'];        $file_type        = $_FILES['idpass']['type'];        $file_error       = $_FILES['idpass']['error'];        //exit script and output error if we encounter any        if($file_error>0)        {            $mymsg = array(             1=>"The uploaded file exceeds the upload_max_filesize directive in php.ini",             2=>"The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form",             3=>"The uploaded file was only partially uploaded",             4=>"No file was uploaded",             6=>"Missing a temporary folder" );                         $output = json_encode(array('type'=>'error', 'text' => $mymsg[$file_error]));            die($output);         }                //read from the uploaded file & base64_encode content for the mail        $handle = fopen($file_tmp_name, "r");        $content = fread($handle, $file_size);        fclose($handle);        $encoded_content = chunk_split(base64_encode($content));        //now we know we have the file for attachment, set $file_attached to true        $file_attached = true;    }		if(isset($_FILES['adrprf'])) //check uploaded file    {        //get file details we need        $file2_tmp_name    = $_FILES['adrprf']['tmp_name'];        $file2_name        = $_FILES['adrprf']['name'];        $file2_size        = $_FILES['adrprf']['size'];        $file2_type        = $_FILES['adrprf']['type'];        $file_error       = $_FILES['adrprf']['error'];        //exit script and output error if we encounter any        if($file_error>0)        {            $mymsg = array(             1=>"The uploaded file exceeds the upload_max_filesize directive in php.ini",             2=>"The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form",             3=>"The uploaded file was only partially uploaded",             4=>"No file was uploaded",             6=>"Missing a temporary folder" );                         $output = json_encode(array('type'=>'error', 'text' => $mymsg[$file_error]));            die($output);         }                //read from the uploaded file & base64_encode content for the mail        $handle = fopen($file2_tmp_name, "r");        $content = fread($handle, $file2_size);        fclose($handle);        $encoded_content2 = chunk_split(base64_encode($content));        //now we know we have the file for attachment, set $file_attached to true        $file2_attached = true;    }		if(isset($_FILES['idpass2'])) //check uploaded file    {        //get file details we need        $file3_tmp_name    = $_FILES['idpass2']['tmp_name'];        $file3_name        = $_FILES['idpass2']['name'];        $file3_size        = $_FILES['idpass2']['size'];        $file3_type        = $_FILES['idpass2']['type'];        $file_error       = $_FILES['idpass2']['error'];        //exit script and output error if we encounter any        if($file_error>0)        {            $mymsg = array(             1=>"The uploaded file exceeds the upload_max_filesize directive in php.ini",             2=>"The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form",             3=>"The uploaded file was only partially uploaded",             4=>"No file was uploaded",             6=>"Missing a temporary folder" );                         $output = json_encode(array('type'=>'error', 'text' => $mymsg[$file_error]));            die($output);         }                //read from the uploaded file & base64_encode content for the mail        $handle = fopen($file3_tmp_name, "r");        $content = fread($handle, $file3_size);        fclose($handle);        $encoded_content3 = chunk_split(base64_encode($content));        //now we know we have the file for attachment, set $file_attached to true        $file3_attached = true;    }			    if($file_attached && $file2_attached) //continue if we have the file    {        $boundary = md5("sanwebe");         //header        $headers = "MIME-Version: 1.0rn";         $headers .= "From:".$from_email."rn";         $headers .= "Content-Type: multipart/mixed; boundary = $boundaryrnrn";                 //plain text         $body = "--$boundaryrn";        $body .= "Content-Type: text/plain; charset=ISO-8859-1rn";        $body .= "Content-Transfer-Encoding: base64rnrn";         $body .= chunk_split(base64_encode($message_body));                 //attachment        $body .= "--$boundaryrn";        $body .="Content-Type: $file_type; name="$file_name"rn";        $body .="Content-Disposition: attachment; filename="$file_name"rn";        $body .="Content-Transfer-Encoding: base64rn";        $body .="X-Attachment-Id: ".rand(1000,99999)."rnrn";         $body .= $encoded_content; 		        //attachment        $body .= "--$boundaryrn";        $body .="Content-Type: $file2_type; name="$file2_name"rn";        $body .="Content-Disposition: attachment; filename="$file2_name"rn";        $body .="Content-Transfer-Encoding: base64rn";        $body .="X-Attachment-Id: ".rand(1000,99999)."rnrn";         $body .= $encoded_content2; 	        //attachment        $body .= "--$boundaryrn";        $body .="Content-Type: $file2_type; name="$file3_name"rn";        $body .="Content-Disposition: attachment; filename="$file3_name"rn";        $body .="Content-Transfer-Encoding: base64rn";        $body .="X-Attachment-Id: ".rand(1000,99999)."rnrn";         $body .= $encoded_content3; 			    }else{        //proceed with PHP email.        $headers = "From:".$from_email."rn".        'X-Mailer: PHP/' . phpversion();        $body = $message_body;    }	    $send_mail = mail($to_email, $subject, $body, $headers);       if(!$send_mail)    {        //If mail couldn't be sent output error. Check your PHP email configuration (if it ever happens)        $output = json_encode(array('type'=>'error', 'text' => 'Could not send mail! Please check your PHP mail configuration.'));        die($output);    }else{        $output = json_encode(array('type'=>'message', 'text' => 'Hey! Your application has been sent and it's waiting for approve.'));        die($output);    }	}}

I just want to get user Id with this form also xD

Link to comment
Share on other sites

So want to allow a logged in user to upload using form, and attach user id from user database table and using require('../../../wp-load.php'); at domain_name/wp-load.phpAt top of page and adding$user_ID = get_current_user_id();echo '<p>xxxx User ID:'.$user_ID.' xxxx</p>';And this php form page is in your theme directory as in domain_name/wp-content/themes/your_theme/form.pageDoes not show anything? If not the framework mvc has probably taken control from wordpresses normal operation, so it would have to be setup fron that using a default template page to gain access to all required wordpress resources.

Link to comment
Share on other sites

Oh my dear friend I get user_ID result in mail!!! Thank u very much!!!One more thing is my step form is not getting after submit to redirection and idk whyI mean the line in jQuery handler:

window.location.href = "www.redirectionplace.com";

it should be executed

 

 

edit:Sorry it was just code freeze!THANK YOU ONCE AGAIN! YOU ARE BIG :)

Edited by LazyDragon
Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
×
×
  • Create New...