Using $_GET and $_POST in custom WordPress plugin - php

I'm new to developing plugins for WordPress, I've been doing it for Magento 2 and thought it would be similar, so here I am.
I'm consuming a RESTful API to display information about some courses, it retrieves me the info on all courses so now I have to filter some attributes, for example "city", for this my user has an HTML form to select which city he is in, but when I try to use the "city" field from the form it returns as null, it doesn't matter if I use post or get method.
Which one is the correct form of getting this attributes in WordPress?
this is an example of the form page:
<?php
/*
* Formulario de filtros
*/
// create curl resource
require_once('../../../../wp-config.php');
$ciudad = $_POST['ciudad'];
var_dump($ciudad);
$accessToken = '---';
$apiUrl = 'url';
$curl = curl_init($apiUrl);
curl_setopt($curl, CURLOPT_HTTPHEADER, ['Authorization: Bearer '.$accessToken]);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
$json = curl_exec($curl);
$cursos = json_decode($json);
$arr = 0;
foreach($cursos as $k => $cur)
{
$sede = $cur->Sede;
if($sede === 'MEDELLIN' ){
$codigo[] = substr($cur->Programa, 0, 4);
$programa[] = $cur->Programa;
$precio[] = $cur->Valor_Contado;
}
}
$cod = array_unique($codigo);
var_dump($cod);
foreach ($cod as $c){
echo "Programa: ".$c."<br>";
}
?>
<div class="filtrosContainer">
<form class="filtro-cursos" method="post">
<div class="vc_row wpb_row vc_row-fluid edgtf-section edgtf-content-aligment-left"><div class="clearfix edgtf-full-section-inner"><div class="wpb_column vc_column_container vc_col-sm-6"><div class="vc_column-inner "><div class="wpb_wrapper">
<div class="wpb_text_column wpb_content_element ">
<div class="wpb_wrapper">
<label>Metodología</label>
<select name="metodologia" id="metodologia" class="metodologia">
<option selected>--Seleccione--</option>
<option value="PRESENCIAL" required>Presencial</option>
<option value="VIRTUAL">Virtual</option>
</select>
<div id="ciudadDiv">
<label>Ciudad</label>
<select name="ciudad" id="ciudad">
<option value="none" selected>--Seleccione--</option>
<option value="MEDELLIN" required>Medellín</option>
<option value="BOGOTA">Bogotá</option>
<option value="BARRANQUILLA">Barranquilla</option>
<option value="BUCARAMANGA">Bucaramanga</option>
<option value="MANIZALES">Manizales</option>
<option value="CALI">Cali</option>
</select></div>
<label>Programa</label>
<select name="programa" id="programa">
<?php
if($ciudad === "MEDELLIN"){ ?>
<option value="none" selected>--Seleccione--</option>
<option value="none" selected>PreUdeA</option>
<option value="none" selected>PreUnal</option>
<option value="none" selected>PreICFES Saber 11°</option>
<option value="none" selected>PreMédico</option>
<option value="none" selected>PreUdeA</option>
<?php }else{
echo $ciudad;
}
?>
</select>
</div>
</div>
</div></div></div><div class="wpb_column vc_column_container vc_col-sm-6"><div class="vc_column-inner "><div class="wpb_wrapper">
<div class="wpb_text_column wpb_content_element ">
<div class="wpb_wrapper">
<label>¿Cuando presentarás el examen?</label>
<select name="semestre" id="semestre">
<option value="none" selected>--Seleccione--</option>
<option value="2019-1" selected>2019-1</option>
<option value="2019-2" selected>2019-2</option>
</select>
<div id="jornadaDiv">
<label>Jornada</label>
<select name="jornada" id="jornada">
<option value="none" selected>--Seleccione--</option>
<option value="SEMANA" selected>Semana</option>
<option value="FINDE" selected>Fin de semana</option>
</select>
</div>
<button type="submit" name="submit" value="Filtrar">Filtra tu programa</button>
</div>
</div>
</div></div></div></div></div>
</form>
</div>

After some research and trying several ways I tryed out the code all together in the main PHP file of my custom plugin instead of using the require_once.
I had the next estructure:
wp-content>>plugins>>myplugin>>myplugin.php
and in said php file had a require_once for:
wp-content>>plugins>>myplugin>>php>>form.php
it seems you can't use $_POST, $_GET, not evev cookies in the files outside the main php file so I had to work all my code in there and forget about mu php folder and eny MVC structure.

Related

Run an SQL Script from a drop down menu

I'm trying to create a drop down menu and run specific SQL scripts depending to each option value.
Part of the php code is this (I've made labels more easy for you to understand what i want):
<div class="form-group RunningSQLScripts">
<label for="inputStatus">Running My Scripts</label>
<select id="inputStatus" name="RunningSQLScripts" class="form-control">
<option selected disabled>--</option>
<option value="RunScript1">Delete Whole Table</option>
<option value="RunScript2">Run Script 3</option>
</select>
</div>
Lets say the RunScript1 is supposed to run the SQL command
truncate table table_name1. How can i do that from inside php menu ?
The easiest way is to use onclick= and then the name_of_function ();
for example:
<div class="form-group RunningSQLScripts">
<label for="inputStatus">Running My Scripts</label>
<select id="inputStatus" name="RunningSQLScripts" class="form-control">
<option selected disabled>--</option>
<option onclick="RunScript1()">Delete Whole Table</option>
<option onclick="RunScript2()">Run Script 3</option>
</select>
</div>
And then according to the function's name.
Create the appropriate functions to run on click.
You can submit the form to the server and execute the request you need.
<?php
$db = new mysqli('localhost', 'db_user', '1234', 'db_name');
if($db->connect_errno)die('Error: '.$db->connect_error);
?>
<form name="runSQL" method="get">
<div class="form-group RunningSQLScripts">
<label for="inputStatus">Running My Scripts</label>
<select id="inputStatus" name="RunningSQLScripts" class="form-control">
<option selected disabled>--</option>
<option value="RunScript1">Delete Whole Table</option>
<option value="RunScript2">Run Script 3</option>
</select>
<input type="submit" value="Run">
</div>
</form>
<?php
$runSQL = $_GET['RunningSQLScripts'];
switch($runSQL){
case 'RunScript1':
$db->query("truncate table `name`");
echo '* Successfully deleted *';
break;
case 'RunScript2':
$db->query("SQL");
echo '* Successfully run *';
break;
}
?>
Easiest way to do it: fully working,
Just add
onchange='this.form.submit();'
<form id="companyForm" name="companyForm" class="form-horizontal" type=get>
<div class="form-group RunningSQLScripts">
<label for="inputStatus">Running My Scripts</label>
<select id="inputStatus" name="RunningSQLScripts" onchange='this.form.submit();' class="form-control">
<option selected disabled>--</option>
<option value="RunScript1">Delete Whole Table</option>
<option value="RunScript2">Run Script 3</option>
</select>
</div>
</form>
<?php
$RunningSQLScripts = $_GET['RunningSQLScripts'];
$con = mysqli_connect('host','username','password','db');
if (!$con) {
die('Could not connect: ' . mysqli_error($con));
}
mysqli_select_db($con,"db");
if ($RunningSQLScripts == "RunScript1")
{
$sql="truncate TABLE `table_name1`;"; // truncate table table_name1
$result = mysqli_query($con,$sql);
}
mysqli_close($con);
?>

Laravel Sort shoplist front end

Hi i'm doing a shop for a university project. This is my first course in web development and I don't understand how to sort a shoplist page by an html dropdown select in laravel.
Frontend Blade
<div class="toolbar-sorter">
<span>Sort By</span>
<select name="sorter" class="sorter-options" style="width:150px; "data-role="sorter">
<option selected="selected" value='comic_name'>Titolo: A-Z </option>
<option value='comic_name'> Titolo: Z-A </option>
<option value='price'> Prezzo: Crescente </option>
<option value='price'> Prezzo: Decrescente </option>
<option value='created_at'> Ultimi Arrivati </option>
</select>
</div>
Route.php (This is not the only route of shoplist)
Route::get('/shoplist', 'ComicController#shoplistBase');
ComicController
public function shoplistBase()
{
$genres = Genre::all();
$comics = Comic::paginate(9);
return view('shoplist')->with(compact('genres'))->with(compact('comics'));
}
Assuming that you are using the same route for your sorting:
Wrap your drop-down in a form
Make sure to use unique values for each options
<form action="/shoplist" method="GET">
<div class="toolbar-sorter">
<span>Sort By</span>
<select name="sorter" class="sorter-options" style="width:150px; " data-role="sorter">
<option selected="selected" value='comic_name_asc'>Titolo: A-Z</option>
<option value='comic_name_desc'> Titolo: Z-A</option>
<option value='price_asc'> Prezzo: Crescente</option>
<option value='price_desc'> Prezzo: Decrescente</option>
<option value='created_at'> Ultimi Arrivati</option>
</select>
</div>
<button type="submit">Filter</button>
</form>
Handle the filter request in your Controller
public function shoplistBase(Request $request)
{
$genres = Genre::all();
if ($request->has('sorter')){
switch($request->get('sorter')){
case `comic_name_asc`:
$comics = Comic::orderBy('name', 'desc')->paginate(9);
break;
case `comic_name_desc`:
//..
break;
}
} else {
$comics = Comic::paginate(9);
}
return view('shoplist')->with(compact('genres'))->with(compact('comics'));
}

About Using Multi Select?

Hi I'm working on the code now and the ticket system sending a notification to a user that selects him about.
I want a notification to select more than one user and more than one user.
I tried to use this for Multi Select more than one user selection, again when I say save too, a single user is registering on this can you help me ?
<div class="form-group select-placeholder">
<label for="assigned" class="control-label">
<?php echo _l('ticket_settings_assign_to'); ?>
</label>
<select name="assigned" id="assigned" class="form-control selectpicker" data-live-search="true" data-none-selected-text="<?php echo _l('dropdown_non_selected_tex'); ?>" data-width="100%">
<option value=""><?php echo _l('ticket_settings_none_assigned'); ?></option>
<?php foreach($staff as $member){ ?>
<option value="<?php echo $member['staffid']; ?>" <?php if($member['staffid'] == get_staff_user_id()){echo '';} ?>>
<?php echo $member['firstname'] . ' ' . $member['lastname'] ; ?>
</option>
<?php } ?>
</select>
</div>
If you want to be able to select multiple you have to add the multiple attribute to the box.
<select multiple>
To receive the values in your code as an array you should change the name from name="assigned" to name="assigned[]"
This will send the multi selected data back as an array to PHP or whichever language you are using
<select multiple name="assigned[]" id="assigned" class="form-control selectpicker" data-live-search="true" data-none-selected-text="<?php echo _l('dropdown_non_selected_tex'); ?>" data-width="100%">
You have to put the multiple attribute in your <select> tag.
Note: The javascript there is used to avoid holding the ctrl-key while selecting multiple options.
window.onmousedown = function (e) {
var el = e.target;
if (el.tagName.toLowerCase() == 'option' && el.parentNode.hasAttribute('multiple')) {
e.preventDefault();
// toggle selection
if (el.hasAttribute('selected')) el.removeAttribute('selected');
else el.setAttribute('selected', '');
// hack to correct buggy behavior
var select = el.parentNode.cloneNode(true);
el.parentNode.parentNode.replaceChild(select, el.parentNode);
}
}
<select name="option-list" size="5" multiple>
<option value="option-1">Option</option>
<option value="option-2">Option</option>
<option value="option-3">Option</option>
<option value="option-4">Option</option>
<option value="option-5">Option</option>
<option value="option-6">Option</option>
<option value="option-7">Option</option>
<option value="option-8">Option</option>
<option value="option-9">Option</option>
</select>
I organized the code this way. But I couldn't get a successful result.
<div class="form-group select-placeholder">
<label for="assigned" class="control-label">
<?php echo _l('ticket_settings_assign_to'); ?>
</label>
<select multiple name="assigned[]" id="assigned" class="form-control selectpicker" data-live-search="true" data-none-selected-text="<?php echo _l('dropdown_non_selected_tex'); ?>" data-width="100%">
<option value=""><?php echo _l('ticket_settings_none_assigned'); ?></option>
<?php foreach($staff as $member){ ?>
<option value="<?php echo $member['staffid']; ?>" <?php if($member['staffid'] == get_staff_user_id()){echo '';} ?>>
<?php echo $member['firstname'] . ' ' . $member['lastname'] ; ?>
</option>
<?php } ?>
</select>
</div>

Working with session in PHP

I have a form from which i take some datas and using session i want to keep that datas as a history on my page, and also when i click on one line from my history i want my datas to be autocomplete in my form. I saw an example on one page and i tried doing it to apply to what i want but it's not quite functional.
This is my code for the form:
<form method="get">
Create:<br><br>
Name:<br> <input type="text" id="name" value="" /><br>
surname:<br> <input type="text" id="surname" value="" /><br>
Sex:<br> <div class="select-wrapper">
<select name="sex" id="sex">
<option value="">- Sex -</option>
<option value="woman">Woman</option>
<option value="male">Male</option>
</select>
</div>
Role: <div class="select-wrapper">
<select name="rol" id="rol">
<option value="">- Role -</option>
<option value="visitor">Visitor</option>
<option value="Professor">Professor</option>
<option value="Student">Student</option>
</select>
</div>
Text color: <div class="select-wrapper">
<select name="cul" id="cul">
<option value="">- Text color -</option>
<option value="red">Red</option>
<option value="blue">Blue</option>
<option value="black">Black</option>
</select>
</div>
Font text: <div class="select-wrapper">
<select name="font" id="font">
<option value="">- Font text -</option>
<option value="15px Arial">Arial</option>
<option value="15px Times New Roman">Times New Roman</option>
<option value="15px Georgia">Georgia</option>
<option value="15px Comic Sans MS">Comic Sans MS</option>
<option value="15px Lucida Sans Unicode">Lucida Sans Unicode</option>
<option value="15px Courier New">Courier New</option>
</select>
</div>
Format : <div class="select-wrapper">
<select name="format" id="format">
<option value="">- Format -</option>
<option value="portrait">Portrait</option>
<option value="landscape">Landscape</option>
</select>
</div>
Style text: <div class="select-wrapper">
<select name="stil" id="stil">
<option value="">- Style text -</option>
<option value="stil1">Stil1</option>
<option value="stil2">Stil2</option>
<option value="stil3">Stil3</option>
<option value="stil4">Stil4</option>
<option value="stil5">Stil5</option>
<option value="stil6">Stil6</option>
</select>
</div>
</form>
And this is where i tried to use session:
<?php
session_start();
$createpas = parseRequest();
storecreatepas($createpas);
include "form.php";
$createpases = $_SESSION['createpases'];
include "history.php";
function storecreatepas($createpas) {
if (!isset($_SESSION['createpases'])) {
$_SESSION['createpases'] = [];
}
if (!$createpas->isEmpty()) {
$_SESSION['createpases'][] = $createpas;
}
}
function parseRequest() {
$createpas = new createpasRequest;
$createpas->cul = !empty($_GET['cul']) ? $_GET['cul'] : "";
$createpas->font = !empty($_GET['font']) ? $_GET['font'] : "";
$createpas->format = !empty($_GET['format']) ? $_GET['format'] : "";
$createpas->stil = !empty($_GET['stil']) ? $_GET['stil'] : "";
return $createpas;
}
/**
* createpas request
*/
class createpasRequest
{
public $cul = "";
public $font = "";
public $format = "";
public $stil = "";
function toQueryString() {
$params = [
'cul' => $this->cul,
'font' => $this->font,
'format' => $this->format,
'stil' => $this->stil
];
return http_build_query($params);
}
function isEmpty() {
return !$this->cul || !$this->font || !$this->format || !$this->stil;
}
function culAsObject() {
return new DateTime($this->cul);
}
function fontAsObject() {
return new DateTime($this->font);
}
function formatAsObject() {
return new DateTime($this->format);
}
function stilAsObject() {
return new DateTime($this->stil);
}
}
And the display code:
<ul>
<?php
foreach ($createpases as $s) {
?>
<li><a href="search.php?<?php echo $s->toQueryString() ?>">
<?php echo $s->cul?> - <?php echo $s->font?> - <?php echo $s->format?> - <?php echo $s->stil?>
</a></li>
<?php
}
?>
</ul>
It works just fine until some point. It gets my datas from my form posts them on the page but when i click on them they don't autocomplete in in my form. And also if i want the options to be unique in the list how can i do that? Right now if i complete the same datas 2 or 3 times they appear multiple times in my list.
Thank you for your help!
You need to start the session in the Form page and then check if the SESSION array contains the values to be echoed.
So your code will become:
<?php session_start();
if(!isset($_SESSION['name']){$_SESSION['name']=''}
if(!isset($_SESSION['sex']){$_SESSION['sex']=''}
if(!isset($_SESSION['rol']){$_SESSION['rol']=''}
?>
//this way you will not have issues on page first load before the user fills in the form
<form method="get">
Create:<br><br>
Name:<br> <input type="text" id="name" value="<?php echo $_SESSION['name']; ?>" /><br>
surname:<br> <input type="text" id="surname" value="" /><br>
Sex:<br> <div class="select-wrapper">
<select name="sex" id="sex">
<option value="" <?php if($_SESSION['rol']==''){echo 'selected'} ?>>- Sex -</option>
<option value="woman" <?php if($_SESSION['rol']=='woman'){echo 'selected'} ?>>Woman</option>
<option value="male" <?php if($_SESSION['rol']=='visitor'){echo 'selected'} ?>>Male</option>
</select>
</div>
Role: <div class="select-wrapper">
<select name="rol" id="rol">
<option value="" <?php if($_SESSION['rol']==''){echo 'selected'} ?>>- Role -</option>
<option value="visitor" <?php if($_SESSION['rol']=='visitor'){echo 'selected'} ?>>Visitor</option>
<option value="Professor"<?php if($_SESSION['rol']=='Professor'){echo 'selected'} ?>>Professor</option>
<option value="Student"<?php if($_SESSION['rol']=='student'){echo 'selected'} ?>>Student</option>
</select>
</div>
and so on.
It appears that your form does not auto-fill with the data because you do not have such a functionality implemented. This auto-complete functionality is not automatic, as in, the server does not do it for you.
Here is an example of what you need to do in order to get the autocomplete to work:
Name:<br> <input type="text" id="name" value="<?= $_SESSION['name'] ?>" /><br>
For the select to auto-complete, you'll need to do something like this:
<select name="cul" id="cul">
<option value="">- Text color -</option>
<option value="red" <? echo ($_SESSION['cul']==="red")?"selected='selected'":""; ?>>Red</option>
<option value="blue" <? echo ($_SESSION['cul']==="blue")?"selected='selected'":""; ?>>Blue</option>
<option value="black" <? echo ($_SESSION['cul']==="black")?"selected='selected'":""; ?>>Black</option>
</select>
This sets the value for each form element by directly setting the value / selected item using the $_GET data from a previous submission, or if there is no data, everything will be empty / default values.
Per a suggestion from one of the comments to this answer, I would like to point out that you must include "session_start()" to the top of the document if you wish to use the session variables on the document (if you have not done so already).
One question about the original question: is that first code block procedurally generated, or hand-typed?

Magento custom search form

I am trying to create custom search functionality in Magento 1.9. Instead of writing it from scratch, I want to piggy back the default search functionality and add in custom filters. First I copied the form.min template and replaced with drop downs that I want to use.
form.custom.phtml:
<?php
$catalogSearchHelper = $this->helper('catalogsearch');
$_helper = Mage::helper('catalog/category');
$_categories = $_helper->getStoreCategories();
?>
<form id="search_custom_form" action="<?php echo $catalogSearchHelper->getResultUrl() ?>" method="get">
<div class="select-box item">
<label for="finder">GIFT FINDER</label>
<select id="customS" name="finder">
<option value="">Please select</option>
<?php
foreach ($_categories as $key => $value) {
echo("<option value='" . $value["name"] . "'>" . $value["name"] . "</option>");
}
?>
</select>
</div>
<div class="item">
<label for="for">FOR</label>
<select id="for">
<option value="">Please select</option>
<option value="him">HIM</option>
<option value="her">HER</option>
</select>
</div>
<div classs="item">
<label for="delivery">DELIVERY OPTION</label>
<select id="delivery">
<option value="express">EXPRESS DELIVERY</option>
<option value="standard">STANDARD POST</option>
</select>
</div>
<div classs="item">
<label for="price">DELIVERY OPTION</label>
<select id="price">
<option value="<250">LESS THAN £250</option>
<option value=">250">MORE THAN £250</option>
</select>
</div>
<button type="submit" title="<?php echo $this->__('Find') ?>" class="button search-button"><span><span><?php echo $this->__('Find') ?></span></span></button>
<script type="text/javascript">
//<![CDATA[
var searchForm = new Varien.searchForm('search_custom_form', '', '');
//]]>
</script>
</form>
I have included the above template on my home page using {{block type="core/template" name="custom-search" as="custom-search" template="catalogsearch/form.custom.phtml"}}, I have copied the core files into my own template folder and now I find myself stuck.
Can anyone offer a better alternative or solution as to what I should do?
Thanks
Found a much easier option here. I copied the catalogsearch folder to my theme, copied the advanced search form and placed it on my home page. Now I can customise the form and the query as I see fit.

Categories