Wordpress WP_Query not using keyword from url query value? - php

I'm using a form to change the values in a WP_Query on a custom post type. I have 2 select fields using taxonomy values, and a keyword search. The select fields are working fine, however the keyword doesn't affect the query (although it shows up in the url query string).
The code for the keyword field is:
<input type="text" placeholder="Välj" name="referenser_keyword">
and the code for taking the query values is:
global $wp_query;
if (isset($wp_query->query_vars['referenser_material'])) {
$materialVal = $wp_query->query_vars['referenser_material'];
} else {
$materialVal = '';
}
if (isset($wp_query->query_vars['referenser_segment'])) {
$segmentVal = $wp_query->query_vars['referenser_segment'];
} else {
$segmentVal = '';
}
if (isset($wp_query->query_vars['referenser_keyword'])) {
$keywordVal = $wp_query->query_vars['referenser_keyword'];
} else {
$keywordVal = '';
}
$filteredLoop = new WP_Query(
array(
'post_type' => 'referenser',
'posts_per_page' => 4,
'referenser_material' => $materialVal,
'referenser_segment' => $segmentVal,
's' => $keywordVal,
'exact' => false,
'sentence' => true
)
);
If I change the $keywordVal value in the } else { from '' to a string, it works using the value I've entered, which makes me think it's always not set (and going through as empty in the query).

I hadn't defined the query variables correctly, adding the following to functions.php fixed it.
function referenser_query_vars_filter( $vars ){
$vars[] = "referenser_material";
$vars[] = "referenser_segment";
$vars[] = "referenser_keyword";
return $vars;
}
add_filter( 'query_vars', 'referenser_query_vars_filter' );

Related

Q: How to store the results of a calculation into a hidden field

We have a gravity form in 4 parts.
1. Input an Australian postcode
2. Select swimming pool dimensions
3. Select accessories
4. Show quotation, prompt for contact details.
In functions.php we have defined a few global symbols. $PostCode is set to the value of the postcode value that is entered on page 1. Once $PostCode is > 0 we include a php file. This file contains a large array of freight charges indexed by the postcode. The postcode-specific charges are transferred to hidden fields on page 2 of the form and are used for later calculations.
Along with the freight charges is a formula. This formula is evaluated using data from the hidden fields on page 2 and also from a number field on page 2 that calculates the pool area from entry fields of length and width.
The result of the evaluation of the formula should be entered into a field on page 3 for use in other calculations. It is at this point that a problem is encountered, namely that the receiving hidden field is not updated.
Code:
// global symbols
$Formula1 = '';
$TNTFreightPrices = array();
$FieldNumberContent = array();
$PostCode = '';
$Formula1Result = 0;
add_filter('gform_field_input_11', 'update_hidden', 10, 5);
function update_hidden($input, $field, $value, $lead_id, $form_id)
{
global $TNTFreightPrices, $FieldNumberContent, $Formula1, $PostCode, $Formula1Result;
$pgno = $field['pageNumber'];
$PostCode = rgpost("input_3");
if (!empty($PostCode)) {
$path = $_SERVER['DOCUMENT_ROOT'] . '/wp-content/uploads/tntfreightprices/TNTFreightPrices.php';
$tmp = include_once $path;
if (gettype($tmp) == "array") {
$TNTFreightPrices = $tmp['postcodes'];
$Formula1 = $tmp['Formula1'];
$f = $form_id;
$BasicChrg = $TNTFreightPrices[$PostCode]['BasicChrg'];
$KgChrg = $TNTFreightPrices[$PostCode]['KgChrg'];
$MinChrg = $TNTFreightPrices[$PostCode]['MinChrg'];
$RemotAreaChrg = $TNTFreightPrices[$PostCode]['RemotAreaChrg'];
$ResidChrg = $TNTFreightPrices[$PostCode]['ResidChrg'];
$_0to15Chrg = $TNTFreightPrices[$PostCode]['0to15Chrg'];
$_15to199Chrg = $TNTFreightPrices[$PostCode]['15to199Chrg'];
$_200to299Chrg = $TNTFreightPrices[$PostCode]['200to299Chrg'];
$_300to399Chrg = $TNTFreightPrices[$PostCode]['300to399Chrg'];
$_400to499Chrg = $TNTFreightPrices[$PostCode]['400to499Chrg'];
$_500to599Chrg = $TNTFreightPrices[$PostCode]['500to599Chrg'];
$_600plusChrg = $TNTFreightPrices[$PostCode]['600plusChrg'];
$FuelSurchrg = $TNTFreightPrices[$PostCode]['FuelSurchrg'];
$FieldNumberContent = array(
'85' => Content_tag(
"input", "",
array(
"id" => "input_{$f}_85",
"class" => "gform_hidden",
"name" => "input_85",
"aria-invalid" => "false",
"value" => "$BasicChrg",
"type" => "hidden")
),
// ...
The Content_tag function is not shown. It generates HTML to set the value of the hidden fields on page 2. An example of its output is
input id="input_11_85" class="gform_hidden" name="input_85" aria-invalid="false" value="9.33" type="hidden">
These values are stored in the $FieldNumberContent array and are returned to the caller depending on the field_id, viz
$fid = $field['id'];
if (array_key_exists($fid, $FieldNumberContent)) {
$input = $FieldNumberContent[$fid];
}
The update_hidden function ends with
return $input;
}
The next block of code takes the values of the hidden fields on page 2 and the result of the area calculation, also on page 2 and replaces the matching values in the formula stored in $Formula1, finally eval'ing the string and storing its result in the global $Formula1Result.
add_filter('gform_field_value', 'populate_fields_into_formula1', 10, 3);
function populate_fields_into_formula1( $value, $field, $name )
{
global $Formula1, $PostCode, $TNTFreightPrices, $Formula1Result;
if (array_key_exists($PostCode, $TNTFreightPrices) ) {
$fid = $field['id'];
if (strpos($Formula1, "[") !== false) {
$sym = "[{$field['label']}]";
$val = rgpost("input_{$fid}");
$Formula1 = str_replace($sym, $val, $Formula1);
} else {
$f1 = "return {$Formula1};";
$f1 = str_replace(",", "", $f1);
$Formula1Result = eval($f1);
}
}
return $value;
}
An example formula is
[AreaCalculator]/2 * [KgChrg] >= [MinChrg] ? [AreaCalculator]/2 * [KgChrg] : [MinChrg]
Finally here's the code that is supposed to updating the field hidden field on page 3. We clicked the checkbox allowing the field to be updated dynamically and gave the parameter name as formula1result.
add_filter('gform_field_value_formula1result', 'populate_formula1result', 10, 3);
function populate_formula1result($value, $field, $name)
{
global $Formula1Result;
if ($Formula1Result > 0) {
$value = $Formula1Result;
}
return $value;
}
Now I confess up front that I am not a particularly adept PHP programmer. Perhaps there is a better way of doing all this, and believe me I am all ears.
But I've been metaphorically hitting my head against this for a day or more. Everything else appears to be working. It's only this that's not Why?

Wordpress PHP query is pulling the wrong database entry

first question here!
I have a custom wordpress site in which I have a check out function that includes a discount/coupon code.
I have done the following to test the code:
- I have set-up three coupon codes in my database
- All three coupon codes are in the database with the correct information
When I try to input a coupon, the code is only applying the coupon rules of the last coupon entered. It should instead by pulling the coupon code that matches the user input of $couponcode
I know there is something wrong with the way I'm assigning the $couponID but I can't figure out how to do it correctly.
Note: I am aware of the mis-spelling of: cooupon_title. however it's set-up this way in the database, so that's not the error.
<?php
$couponCode = '';
$couponMessage = '';
$discountAmount = 0;
$couponId = 0;
if(isset($_POST['couponCode']) && !empty($_POST['couponCode'])) {
$couponCode = $_POST['couponCode']; }
if(!empty($couponCode)) {
$args = array('posts_per_page' => 1,'offset' => 0,'category' => '', 'category_name' => '', 'orderby' => 'date','order' => 'DESC','include' => '', 'exclude' => '','meta_key' => '','meta_value' => '','post_type' => 'coupons','post_mime_type' => '','title' => $couponCode,'post_status' => 'publish','suppress_filters' => 'true');
$couponDbData = get_posts($args);
$couponResultData = '';
if(isset($couponDbData[0]) && !empty($couponDbData[0])) {
$couponResultData = $couponDbData[0];
} else {
$couponMessage = 'Invalid coupon code';
}
if(isset($couponResultData->ID) && !empty($couponResultData->ID))
$couponId = $couponResultData->ID;
if(!empty($couponId)) {
$expiry_condition = get_post_meta($couponId,'expiry_condition',true);
$expiry_value = get_post_meta($couponId,'expiry_value',true);
$no_of_use = get_post_meta($couponId,'no_of_use',true);
$appyCoupon = false;
if($expiry_condition=='use') {
if($expiry_value > $no_of_use) {
$appyCoupon = true;
} else {
$couponMessage = 'Coupon has expired.';
}
} else {
$couponExpireTime = strtotime($expiry_value);
$currentTime = time();
if($couponExpireTime > $currentTime) {
$appyCoupon = true;
} else {
$couponMessage = 'Coupon has expired.';
}
}
if($appyCoupon) {
$cooupon_title = get_post_meta($couponId,'cooupon_title',true);
$coupon_type = get_post_meta($couponId,'coupon_type',true);
$coupon_value = get_post_meta($couponId,'coupon_value',true);
if($coupon_type=='$') {
$discountAmount = $coupon_value;
} else {
$discountAmount = ($orderAmount*$coupon_value)/100;
}
$grandTotal -= $discountAmount;
}
}
}
this is my test output:
if($appyCoupon) { ?>
<div class="col-sm-12 col-md-12 makeOrderDetailsrow">
<label class="col-sm-4 col-md-4">Discount <?php echo '( Apply coupon '.$couponCode.' from the following sources '.$couponId.' '.$cooupon_title.' '.$coupon_value.' '.$coupon_type.')'; ?></label>
<span class="col-sm-8 col-md-8">- $<?php echo (number_format($discountAmount,2)); ?></span>
</div>
The output after "from the following sources" shows the code is pulling the last entry in the DB rather than the one that matches the $couponCode. Any advice or suggestions? thank you
According to the codex, the args for get_posts does not include 'title', https://codex.wordpress.org/Template_Tags/get_posts.
Wordpress has a function to query the post by the title, get_page_by_title( $page_title, $output, $post_type );http://codex.wordpress.org/Function_Reference/get_page_by_title
By the way, you don't have to include the whole list of $args in the get_posts query, just those you want to change from the default. For example,
$args = array(
'post_type' => 'coupon',
);
Will override the default of 'post_type' => 'post', without changing 'posts_per_page' => 5.

php foreach multiple array timeout

There are two functions, one is init function to get some information from database and then transfer the account info to another function get the data from remote website, then test_function_save_data() get the correct data and check & insert them into the database.
Question is: if use the print_r($post) in test_function_save_data(), the function can work normally. but remove this print_r or replace it with sleep(), all of the data can be checked and inserted into dabase, but the current page is not redirected and blank page will be display.
so, where is wrong? how to solve it?
<?php
function test_function_get_account_init() {
if(test_function_get_sns_account('blog')) {
$b = 0;
foreach (test_function_get_sns_account('blog') as $team_id => $blog_account_name) {
$blog = test_theme_get_blog($team_id, $blog_account_name);
if($blog && is_array($blog['posts'])){
$b += test_function_save_data($blog['posts']);
}
}
echo '<h5successfuly!</h5>';
} else {
echo 'not found.';
}
}
function test_function_save_data($post_data) {
set_time_limit(720);
global $wpdb;
$i = 0;
foreach ($post_data as $post) {
// echo '<div style="display:none;">';
// print_r($post);
// echo '</div>';
if(test_function_check_post_unquine($post['social_origin_id']) && isset($post['social_origin_id'])) {
$social_post_data = array(
'post_title' => $post['post_title'],
'post_content' => $post['post_content'],
'post_status' => 'publish',
'post_author' => get_current_user_id(),
'post_type' => 'social_post'
);
$latest_post_id = wp_insert_post( $social_post_data );
if($post['social_origin_url']) {
add_post_meta($latest_post_id, 'social_origin_url', $post['social_origin_url']);
}
if($post['social_origin_id']) {
add_post_meta($latest_post_id, 'social_origin_id', $post['social_origin_id']);
}
if($post['user']) {
add_post_meta($latest_post_id, 'social_origin_user', $post['user']);
}
if($post['user']['team_account']) {
add_post_meta($latest_post_id, $post['user']['site_name'].'_social_user_id', $post['user']['team_account']);
}
if($post['media']) {
add_post_meta($latest_post_id, 'social_origin_thumbnail', $post['media']['url']);
}
$i++;
}
flush();
}
return $i;
}
This looks like a wordpress code? Have you tested print_r a single $post? In some frameworks, most of the objects are instance of a very complicated class. For ex. In laravel if you try to print_r a single model object it will result in a huge amount of data, so doing it in a loop can cause the timeout. Usually there is a way to get only the object's attributes. Hopefully this helps, maybe this should be in comment but my rep isn't enough for that

update checkbox value in CodeIgniter

I have an update query problem in CodeIgniter. I am trying to solve that problem but I can't. I have one array $arrpartnerId=([0=>1,[1]=>4,[3]=>5 like..) and my other array is $promotionData['promotion_id']. The inserting into checkbox value is correct, but the updating checkbox value is not working.
My model function is:
public function update_promotion($promotionData, $partnerData) {
// print_r( $promotionData['promotion_id']);
$arrPartnerId = $partnerData['partner_id'];
print_r($partnerData['partner_id']);
if (is_array($arrPartnerId) > 0) {
foreach ($arrPartnerId as $partnerId) {
$this->db->set('promotion_id', $promotionData['promotion_id']);
$this->db->where('partner_id', $partnerId);
$this->db->update('partner_promotion_relation');
}
}
}
If your array is like this,
$arrPartnerId = array(
0 => 1,
1 => 4,
2 => 5
);
And
$promotionData['promotion_id'] = 123; //assumption
Then try this,
if(sizeof($arrPartnerId) > 0 )
{
foreach( $arrPartnerId as $partnerId)
{
$this->db->set('partner_id', $partnerId );
$this->db->where('promotion_id', $promotionData['promotion_id'] );
$this->db->update('partner_promotion_relation');
}
}
It will resolve the problem.

Cant pass array value from codeigniter controller to view

Inside my controller, I have a line that needs to pass $content['pass_check'] to the view. It is inside an if statement that checks for validation. This I have found causes it to break. Once I move the $content['pass_check'] outside of any if statement, it works just fine passing to the view. All of the other values are passed (accounts, expense_accounts, vendors, terms). What must I do to get it to pass within this if statement. I've even tried moving it outside of the validation and it still wont set.
function create() {
require_permission("INVOICE_EDIT");
$this->load->library("form_validation");
$this->form_validation->set_rules("invoice_number", "Invoice Number", "required");
if($this->form_validation->run() !== false) {
$post = $this->input->post();
$this->session->set_userdata("create_invoice_vendor", $post['vendor_id']);
$this->session->set_userdata("create_invoice_date", $post['invoice_date']);
$invoice_number_exists = $this->invoices->count(array("invoice_number" => $post['invoice_number'])) > 0;
$post['invoice_date'] = date("Y-m-d", strtotime($post['invoice_date']));
$post['due_date'] = date("Y-m-d", strtotime($post['due_date']));
$post['date_entered'] = "now()";
$id = $this->invoices->insert_invoice($post);
$this->load->model("vendors");
if(isset($post['invoice_number'])){
$string_check= $post['invoice_number'];
$string_check= preg_replace('/\d/', '#', $string_check);
$string_check= preg_replace('/\w/', '#', $string_check);
$invoice_pattern=array();
$invoice_pattern = $this->db->select("invoice_pattern")->where("vendor_id",
$post['vendor_id'])->get("vendors")->result();
$invoice_pattern=$invoice_pattern[0]->invoice_pattern;
* //// THIS IS WHERE I NEED HELP ///////
if($invoice_pattern == $string_check){
***$content['post_check'] = 1;***
$this->invoices->flag_invoice($id);
};
};
$history = array(
"type" => "invoice_entered",
"comments" => "Invoice was entered",
"link" => $id,
"admin_id" => $this->user->admin_id,
"date" => "now()",
);
$this->vendors->insert_history($post['vendor_id'], $history);
if($post['flagged'] == 1) {
$this->invoices->flag_invoice($id);
}
if($invoice_number_exists) {
redirect("invoices/confirm_invoice/".$id);
} else {
// redirect("invoices/view/".$id);
redirect("invoices/create");
}
}
$content['accounts'] = $this->db->get("acct_chart_of_accounts")->result();
$content['expense_accounts'] = $this->db->get("invoice_expense_accounts")->result();
$content['vendors'] = $this->db->select("vendor_id, name, terms, override, invoice_pattern")
->order_by("name ASC")->get("vendors")->result();
$content['terms'] = $this->db->query("SELECT DISTINCT(terms) FROM vendors")->result();
}
}
$this->template['sub_heading'] = "Create";
$this->template['content'] = $this->load->view("invoices/create", $content, true);
$this->template['sidebar'] = $this->load->view("invoices/sidebar", array(), true);
$this->template['scripts'] = array("codeigniter/javascript/invoices/create.js");
$this->template['styles'][] = "codeigniter/styles/invoices/create.css";
$this->display();
}
Obviously it won't pass it to the view if the condition doesn't match, because you're only declaring the variable within the condition if it matches.
Just create $content['pass_check'] with an initial value of 0 or whatever before the conditional check first.
function create() {
...snip...
$content['pass_check'] = 0;
if($invoice_pattern == $string_check) {
$content['post_check'] = 1;
$this->invoices->flag_invoice($id);
};
...snip...
}
Let me know if this works or not please.

Categories