Wordpress PHP query is pulling the wrong database entry - php

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.

Related

Drupal "You are not authorized to access this page"

I've taken over managing our site from MIA developers and have spent the day trying to find this answer.
After upgrading to v 7.56 there's just ONE specific page in a list of pages that I am unable to access as an admin. (and unfortunately it's probably the most needed report in our admin panel).
Here's what I know:
Drupal Version 7.56
PHP 7.0.20
No errors when status report is run
Chron - no errors
Here's what I've done:
added $cookie_domain = '.example.com'; to settings.php
cleared browser cache and cookies
ensured admin has access to everything
cleared site cache
made sure code on page(s) was exactly the same as it was before I did the update
Not sure what to do or where to go from here. Any help is much appreciated.
UPDATE: When logged in as super admin, received HTTP 500 error. After more research, I updated the php.ini to include memory_limit = 64M ;
Now I can view the page as the superadmin, but it still isn't available for other admins.
Image 1: viewing page as admin
Image 2: viewing page as superadmin
function custom_reports_menu() {
$items['administration/upcoming-classes'] = array(
'title' => 'Upcoming Classes',
'page callback' => 'custom_reports_upcoming_classes_page',
'access callback' => 'user_access',
'access arguments' => array('admin wdcc reports'),
'file' => 'includes/custom_reports.upcoming-classes.inc',
'type' => MENU_CALLBACK,
);
$items['administration/class-details'] = array(
'title' => 'Class Details',
'page callback' => 'custom_reports_class_details_page',
'access callback' => 'user_access',
'access arguments' => array('admin wdcc reports'),
'file' => 'includes/custom_reports.class-details.inc',
'type' => MENU_CALLBACK,
);
return $items;
}
function custom_reports_upcoming_classes_page() {
drupal_add_css(base_path().path_to_theme().'/assets/css/outburst-accounts.css', array('type' => 'external'));
global $user;
$uid = $user->uid;
$output = '';
$upcoming_classes = custom_reports_get_upcoming_classes();
$attendee_count = custom_reports_get_attendee_count();
// upcoming classes
$output .= '<h2>Upcoming Classes</h2>';
$output .= custom_reports_format_upcoming_classes($upcoming_classes, $attendee_count);
return $output;
}
function custom_reports_permission() {
return array(
'admin wdcc reports' => array(
'title' => t('Admin WDCC Reports'),
'description' => t('Perform administration tasks for WDCC.'),
//'cache' => DRUPAL_NO_CACHE,
),
);
}
function custom_reports_get_upcoming_classes() {
$today = date('Y-m-d');
$x = 0;
$classes = '';
// get classes from new db tables
$today = date('Y-m-d H:i:s');
$result = db_query("SELECT n.nid FROM node n, field_data_field_date fdfd WHERE n.status = :status AND n.type = :type AND n.nid = fdfd.entity_id AND fdfd.field_date_value >= :today ORDER BY fdfd.field_date_value ASC", array(':status' => 1, ':type' => 'public_class_date', ':today' => $today));
if ($result->rowCount() > 0) {
foreach ($result as $row) {
$nid = $row->nid;
$node = node_load($nid);
$product_id = $nid;
$product_title = $node->title;
$product_type = 'public_class_date';
$product_date = $node->field_date[$node->language][0]['value'];
$product_datestamp = strtotime($product_date);
//$product_datestamp = strtotime($product_date);
// set vars
$classes[$x]['product_id'] = $product_id;
$classes[$x]['product_title'] = $product_title;
$classes[$x]['product_type'] = $product_type;
$classes[$x]['product_date'] = $product_date;
$classes[$x]['product_datestamp'] = $product_datestamp;
$x++;
}
}
return $classes;
}
function custom_reports_get_attendee_count() {
$attendees = array();
$old_attendees = array();
$new_attendees = array();
$result = db_query("SELECT itemID, attendeeID, attendeeName FROM wdcc_old_attendee");
if ($result->rowCount() > 0) {
foreach ($result as $row) {
$item_id = $row->itemID;
$attendee_id = 'B'.$row->attendeeID;
$attendee_name = $row->attendeeName;
$old_attendees[$item_id][$attendee_id]['old_attendee_id'] = $attendee_id;
if (strpos($attendee_name, '&') > 0 || strpos($attendee_name, ' and') > 0) { // couples
$old_attendees[$item_id][$attendee_id]['total_attendees'] = 2;
} else {
$old_attendees[$item_id][$attendee_id]['total_attendees'] = 1;
}
}
}
if (is_array($old_attendees)) {
$connect_class_ids = custom_accounts_connect_class_ids();
foreach ($old_attendees as $old_item_id => $attendee_list) {
if (isset($connect_class_ids[$old_item_id])) {
$product_id = $connect_class_ids[$old_item_id];
foreach ($attendee_list as $attendee_id => $attendee) {
$old_attendee_id = $attendee['old_attendee_id'];
$attendees[$product_id][$old_attendee_id]['total_attendees'] = $attendee['total_attendees'];
}
}
}
}
$result = db_query("SELECT id, product_id FROM wdcc_attendees WHERE transaction_id > 0");
if ($result->rowCount() > 0) {
foreach ($result as $row) {
$attendee_id = $row->id;
$product_id = $row->product_id;
$attendees[$product_id][$attendee_id]['total_attendees'] = 1;
}
}
$cancelled_attendees = array();
$result = db_query("SELECT * FROM wdcc_attendees_cancelled");
if ($result->rowCount() > 0) {
foreach ($result as $row) {
$attendee_id = $row->attendee_id;
$old_attendee_id = 'B'.$row->old_attendee_id;
if ($attendee_id > 0) {
$cancelled_attendees[] = $attendee_id;
} else {
$cancelled_attendees[] = $old_attendee_id;
}
}
}
foreach ($attendees as $product_id => $product_attendees) {
foreach ($product_attendees as $attendee_id => $attendee) {
if (in_array($attendee_id, $cancelled_attendees)) {
unset($attendees[$product_id][$attendee_id]);
}
}
}
$attendee_count = array();
foreach ($attendees as $product_id => $product_attendees) {
foreach ($product_attendees as $attendee_id => $attendee) {
if (!isset($attendee_count[$product_id])) {
$attendee_count[$product_id] = $attendee['total_attendees'];
} else {
$attendee_count[$product_id] = $attendee_count[$product_id] + $attendee['total_attendees'];
}
}
}
return $attendee_count;
}
function custom_reports_format_upcoming_classes($upcoming_classes, $attendee_count) {
$output = '';
if (is_array($upcoming_classes)) {
$output .= '<div class="table-responsive table-container">';
$output .= '<table class="table">';
$output .= '<tr><td>Class</td><td>Guests</td><td>Actions</td></tr>';
foreach ($upcoming_classes as $class) {
$nid = $class['product_id'];
$node_url = url('node/'.$nid, array('absolute' => TRUE));
$attendees = 0;
if (isset($attendee_count[$nid])) {
$attendees = $attendee_count[$nid];
}
$output .= '<tr><td>'.$class['product_title'].'<br />'.date('m/d/Y - g:i A', $class['product_datestamp']).'</td><td>'.$attendees.'</td><td>View roster</td></tr>';
}
$output .= '</table>';
$output .= '</div>';
} else {
$output .= '<p>No upcoming classes found.</p>';
}
return $output;
}
Probably would need more info, but it seems like a case of custom or hardcoded permissions.
Here's potential cases to explore:
Assign all the roles to the admin user
Search custom modules for this page URL. See if page is only certain users are allowed to access this page.
If report is Drupal View, find this view and check the permissions section.
In the current menu items you are using access callback attribute in a wrong way. Your menu items do not require to specify access callback. Only access argument is sufficient.
Please add an access argument to which only admin has access.
"access callback": A function returning TRUE if the user has access rights to this menu item, and FALSE if not. It can also be a boolean constant instead of a function, and you can also use numeric values (will be cast to boolean). Defaults to user_access() unless a value is inherited from the parent menu item; only MENU_DEFAULT_LOCAL_TASK items can inherit access callbacks. To use the user_access() default callback, you must specify the permission to check as 'access arguments' (see below).
Source: https://api.drupal.org/api/drupal/modules%21system%21system.api.php/function/hook_menu/7.x
Replace this below code in settings.php file
PHP variable name:
$cookie_domain = 'example.com'; (line 340)
I was getting this error while login Drupal. After lots of reacher I found that we mistakenly blocked some internal IP of Drupal which is trigger while login the Drupal. So my suggestion is here Your should have to check if you have block any IP at your end (index.php file or anywhere). And You can TRUNCATE the Table session and flood from DB it also help you out.

Wordpress WP_Query not using keyword from url query value?

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' );

Cakephp pagination custom order

I need to set the pagination order of my register based on field ($results[$key]['Movimento']['status']) created in afterFind callback.
afterFind:
public function afterFind($results, $primary = false) {
foreach ($results as $key => $val) {
if(isset($val['Movimento']['data_vencimento'])) {
$data = $val['Movimento']['data_vencimento'];
$dtVc = strtotime($data);
$dtHj = strtotime(date('Y-m-d'));
$dtVencendo = strtotime("+7 day", $dtHj);
if ($dtVc < $dtHj) {
$results[$key]['Movimento']['status'] = 'vencido';
} elseif ($dtVc <= $dtVencendo) {
$results[$key]['Movimento']['status'] = 'vc15dias';
} else {
$results[$key]['Movimento']['status'] = 'aberto';
}
}
if(isset($val['Movimento']['data_pagamento'])) {
$results[$key]['Movimento']['status'] = 'quitado';
}
}
return $results;
Pagination:
$options = array(
...
'order' => array('Movimento.status' => 'ASC')
);
$this->controller->paginate = $options;
$movimentos = $this->controller->paginate('Movimento');
I know this does not work because the field is created after the paginator call.
Can I make it work?
as I understand, you want to sort by data_pagamento and than by data_vencimento (has it the mysql-type date?)
so you don't need your afterFind-function for ordering, simply use:
'order' => array(
'Movimento.data_pagamento DESC',//first all rows with not-empty data_pagamento
'Movimento.data_vencimento DESC',// first all dates in the furthest future
)

Adding html to t() in Drupal 6 template.php?

Hi I am trying to add html to the "t('Older Posts')" and "t('Newer Posts')" Is this possible ? I can figure it out ????
I am in a Drupal 6 template.php file.
This is the code I am trying to add as html -
<span>Newer Posts</span>
<span>Older Posts</span>
I need to replace the above in these spots located in the full function below ?
t('Older Posts')
t('Newer Posts')
I want to create something like this
t('<span>Older Posts</span>')
t('<span>Newer Posts</span>')
Full Function
function theme_views_mini_pager($tags = array(), $limit = 10,
$element = 0, $parameters = array(), $quantity = 9) {
global $pager_page_array, $pager_total;
// Calculate various markers within this pager piece:
// Middle is used to "center" pages around the current page.
$pager_middle = ceil($quantity / 2);
// current is the page we are currently paged to
$pager_current = $pager_page_array[$element] + 1;
// max is the maximum page number
$pager_max = $pager_total[$element];
// End of marker calculations.
$li_previous = theme('pager_previous', (isset($tags[1]) ? $tags[1] :
t('Older Posts')), $limit, $element, 1, $parameters);
if (empty($li_previous)) {
$li_previous = " ";
}
$li_next = theme('pager_next', (isset($tags[3]) ? $tags[3] : t('Newer Posts')),
$limit,$element, 1, $parameters);
if (empty($li_next)) {
$li_next = " ";
}
if ($pager_total[$element] > 5) {
$items[] = array(
'class' => 'action back pager-previous',
'data' => $li_previous,
);
$items[] = array(
'class' => 'action pager-next',
'data' => $li_next,
);
return theme('item_list', $items, NULL, 'ul', array('class' => 'pager'));
}
}
I am trying to figure out if this is possible I have tried many things and nothing has worked yet.
You can use
$link = '<span>' . t('Older Posts') . '</span>';
OR
$link = t('!link_startOlder Posts!link_end', array(
'!link_start' => '<a href="" class="action back"><span>',
'!link_end' => '</span></a>',
));

drupal 6 mini pager theming

I am trying to theme particular pagers on the site and no matter what id I try it doesn't seem to get picked up. This is what I am using to theme all pagers now.
function Subtle_Hightlights_views_mini_pager($tags = array(), $limit = 10, $element = 0, $parameters = array(), $quantity = 9) {
global $pager_page_array, $pager_total;
// Calculate various markers within this pager piece:
// Middle is used to "center" pages around the current page.
$pager_middle = ceil($quantity / 2);
// current is the page we are currently paged to
$pager_current = $pager_page_array[$element] + 1;
// max is the maximum page number
$pager_max = $quantity;
// End of marker calculations.
$li_previous = theme('pager_previous', (isset($tags[1]) ? $tags[1] : t('')), $limit, $element, 1, $parameters);
if (empty($li_previous)) {
$li_previous = "";
}
$li_next = theme('pager_next', (isset($tags[3]) ? $tags[3] : t('')), $limit, $element, 1, $parameters);
if (empty($li_next)) {
$li_next = "";
}
if ($pager_total[$element] > 1) {
$items[] = array(
'class' => 'pager-previous-mini',
'data' => $li_previous,
);
if ($pager_current == 9){
$li_next = "";
}
$items[] = array(
'class' => 'pager-current-mini',
'data' => t('#current of #max', array('#current' => $pager_current, '#max' => $pager_max)),
);
$items[] = array(
'class' => 'pager-next-mini',
'data' => $li_next,
);
return theme('item_list', $items, NULL, 'ul', array('class' => 'pager'));
}
}
now this works to theme all mini pagers but when I try to apply the name of the view and block like this.
function Subtle_Hightlights_views_mini_pager__news_items__block_2($tags = array(), $limit = ``10, $element = 0, $parameters = array(), $quantity = 9) {
does nothing acts as though the code isnt there anymore. Anyone else tried this and it actually worked?
There is a good step by step instructions on how you can overwrite the pager (mini or full). The only step that I would suggest that you do different is when you get to list of theme function names that you can use to override your views pager inside your template.php file, just use this module: Theme developer. Once it's enabled it will provide in a much easier way the suggestions. If that fails, then just try the article's methods.
Drupal 6 Override views pager theme function

Categories