Maybe this is already answered somewhere else, but I couldn't find it after researching for 5 days.
I've a custom WP Query that returns products for JavaScript AJAX client. My client wants to handle the "number of rows" and "columns" through wooCommerce config that is available through customization of shop page.
Here's my basic implementation for custom WP Query:
function loadProducts(){
// Access the number of rows and columns input here from customization page??
}
add_action("wp_ajax_loadprods","loadProducts");
add_action("wp_ajax_nopriv_loadprods","loadProducts")
From the ref: /wp-content/plugins/woocommerce/includes/wc-template-functions.php
function loadProducts(){
$columns = get_option('woocommerce_catalog_columns', 4);
$rows = absint(get_option('woocommerce_catalog_rows', 4));
echo json_encode(array('columns' => $columns, 'rows' => $rows));
wp_die();
}
add_action("wp_ajax_loadprods","loadProducts");
add_action("wp_ajax_nopriv_loadprods","loadProducts")
Related
I am building a self-test project which can give 10 questions at one time from a question list. I want the 10 questions should be different every time I start the test. The front-end is React and the back-end is WordPress by using WordPress API.
Previously I used orderby=rand in the query by implementing a plug-in
<?php
/**
* Plugin Name: REST API - Post list randomize
* Description: Randomize the content list in REST API passing `orderby=rand` as parameter.
* Version: 1.0.0
* Author: Felipe Elia | Codeable
* Author URI: https://codeable.io/developers/felipe-elia?ref=qGTOJ
*/
/**
* Add `rand` as an option for orderby param in REST API.
* Hook to `rest_{$this->post_type}_collection_params` filter.
*
* #param array $query_params Accepted parameters.
* #return array
*/
function add_rand_orderby_rest_post_collection_params( $query_params ) {
$query_params['orderby']['enum'][] = 'rand';
return $query_params;
}
add_filter( 'rest_post_collection_params', 'add_rand_orderby_rest_post_collection_params' );
It worked perfectly until 2 weeks ago. Without modifying any code, it was just broken. I used Postman to test, such as http://localhost/wp/wp-json/wp/v2/questions?per_page=10&orderby=rand. The response is
"code": "rest_invalid_param",
"message": "Invalid parameter(s): orderby",
"data": {
"status": 400,
"params": {
"orderby": "orderby is not one of author, date, id, include, modified, parent, relevance, slug, include_slugs, title."
}
}
Two weeks ago if I used the same query, it could give me 10 random questions. It looks like the plug-in cannot add rand successfully as a parameter for orderby in WordPress like before.
BTW, the functionality of orderby=rand in WP isn't broken because if I manually add rand as a parameter in WP core code, the above query can work again.
Does anybody know what's wrong with the plug-in or some latest updates in WP causing the problem?
Another thing is I saw some articles mentioning ORDERBY = RAND() in MySQL will affect the performance severely when the database is large. So I wonder whether I should use orderby=rand in the query to get random questions or think about other ways to do the job. Does anybody have any suggestions for this performance issue? Thanks!
Found the answer. I need to make the first parameter rest_post_collection_params of add_filter function to the correspondent post type.
The original rest_post_collection_params is for the WP default posts type. Because I use ACF(Advanced Custom Fields, another plug-in to create customized post types) to create my own post types, such as books, I need to change the first parameter to rest_books_collection_params. If you have more customized post types, just create as many as add_filter functions for each of them.
Just have no ideas why I could use rest_post_collection_params for all my customized post types 3 weeks ago but not now. Anyway, since it is solved, don't bother. My project is more front-end oriented. WP is just storage.
BTW, probably someone has noticed that rest_post_collection_params is for the WP default post type posts. In the parameter it uses single form post for the plural form posts. This only works for the WP default post type. For customized types, if it is books, the parameter should be rest_books_collection_param; if questions, then rest_questions_collection_param. Keep the parameter exactly the same as the post type.
For Getting Unique Questions:
table: wp_question_filter_list
id ip_address question_list
1 1.21.23 1,2,3,4,5
2 1.21.24 1,4,6,7,8
3 1.21.25 4,5,6,8,9
function get_unique_questions($ip_address){
global $wpdb;
$table_name = $wpdb->prefix . 'question_filter_list';
$unique_id_list=$wpdb->get_results($wpdb->prepare("SELECT * FROM $table_name WHERE ip_address=%d",$ip_address), ARRAY_A);
if (count($unique_id_list) > 0) {
$question_data=$unique_id_list[0];
$arr_question=array();
if(isset($question_data['question_list']) && $question_data['question_list']!=''){
$arr_old_question_id_list=explode(",",$question_data['question_list']);
}
$excludes = implode(',', $arr_old_question_id_list);
$arr_question_id_list=$wpdb->get_results($wpdb->prepare("SELECT * FROM $table_name WHERE ip_address='".$ip_address."' AND id NOT IN('".$excludes."') "), ARRAY_A);
set_unique_questions($ip_address,$arr_question_id_list);
}
function set_unique_questions($ip_address,$arr_question_id_list){
global $wpdb;
$table_name = $wpdb->prefix . 'question_filter_list';
$unique_id_list=$wpdb->get_results($wpdb->prepare("SELECT * FROM $table_name WHERE ip_address=%d",$ip_address), ARRAY_A);
if (count($unique_id_list) > 0) {
$question_data=$unique_id_list[0];
$arr_question=array();
if(isset($question_data['question_list']) && $question_data['question_list']!=''){
$arr_old_question_id_list=explode(",",$question_data['question_list']);
}
if(is_array($arr_question_id_list) && !empty($arr_question_id_list)){
foreach($arr_question_id_list as $single_question){
array_push($arr_question,$single_question);
}
}
$str_question_id_list=implode(",",$arr_question);
$wpdb->update($table_name, array(
'question_list' => $str_question_id_list
), array(
'ip_address' => $ip_address
));
}else{
$str_question_id_list=implode(",",$arr_question_id_list);
$data = array(
'ip_address' => $ip_address,
'question_list' => $str_question_id_list,
);
$wpdb->insert($table_name, $data);
}
$result = $wpdb->insert($table_name, $item);
}
$ip_address=$_SERVER['REMOTE_ADDR'];
$arr_question_list=get_unique_questions($ip_address);
echo "<pre>";
print_r($arr_question_list);
Is there a way to create/update form poll fields based on a content type? For example, I've got a post type called Candidate and I'd like like to dynamically update a poll list when a new Candidate is added, or when one is removed.
The reason I'm looking for this is because I'm creating a voting mechanism for this client and they have requested that users see an image, the name, and brief Bio of who they are voting for. My idea is to tie in the names so that I can target a hidden Gravity Form poll on page so when the voter clicks, it updates the corresponding named checkbox.
I can of course add each Candidate one by one, and then add each candidate one by one in the form, but was hoping there was a way to do that in code. So far I haven't found much other than filters in the Gravity Forms Documentation.
To reiterate, my question here is not the frontend connection, rather how to dynamically update/add an option in a poll field in a form when content is created for a Candidate post type.
Any help would be appreciated.
I believe the solution you're after is documented here:
http://www.gravityhelp.com/documentation/gravity-forms/extending-gravity-forms/hooks/filters/gform_pre_render/
Probably a combination of solution examples #1 and #2 on that page will fit your needs? So -
Create a category of standard Wordpress pages (category name: "Candidates"), and the pages would contain the candidate information (bio, photo, etc).
In your functions.php file for your current theme, you'd add something like the following to pull out that category's worth of posts:
// modify form output for the public page
add_filter("gform_pre_render", "populate_checkbox");
// modify form in admin
add_filter("gform_admin_pre_render", "populate_checkbox");
function populate_dropdown($form) {
// some kind of logic / code to limit what form you're editing
if ($form["id"] != 1) { return $form; }
//Reading posts for "Business" category;
$posts = get_posts("category=" . get_cat_ID("Candidates"));
foreach ($form['fields'] as &$field) {
// assuming field #1, if this is a voting form that uses checkboxes
$target_field = 1;
if ($field['id'] != $target_field) { break; }
// init the counting var for how many checkboxes we'll be outputting
// there's some kind of error with checkboxes and multiples of 10?
$input_id = 1;
foreach ($posts as $post) {
//skipping index that are multiples of 10 (multiples of 10 create problems as the input IDs)
if($input_id % 10 == 0) { $input_id++; }
// here's where you format your field inputs as you need
$choices[] = array('text' => $post->post_title, 'value' => $post->post_title);
$inputs[] = array("label" => $post->post_title, "id" => "{$field_id}.{$input_id}");
// increment the number of checkboxes for ID handling
$input_id++;
}
$field['choices'] = $choices;
$field['inputs'] = $inputs;
}
// return the updated form
return $form;
}
Im building an e-commerce site for wholesale foods and the pricing for products change depending on the user logged in. Ive looked at member pricing and basically every module i could find to do with altering the price but they are either for drupal 6 or not really what im after. Im using Drupal 7 with ubercart 3.
Ive found this module http://drupal.org/project/uc_custom_price. It adds a field within product creation that allows custom php code to be added to each individual product which is exactly what im after. however im not that good with php which is why ive been hunting modules instead of changing code.
What ive got at the moment is:
if ([roles] == 'test company') {
$item->price = $item->price*0.8;
}
Except the [roles] part is the wrong thing to use there and it just throws errors. Ive tried using things like $users->uid =='1' to try to hook onto a user like that but that didnt work either.
what would be the correct variable to put there?
thanks
try this Drupal 7 global $user object
global $user; // access the global user object
if(in_array("administrator",$user->roles)){ // if its administrator
$item->price = $item->price*0.8;
}elseif(in_array("vip",$user->roles)){ // if its a vip
//..
}elseif(in_array("UserCompanyX",$user->roles)){ // if its a user from company X
//..
}
or
if($user->roles[OFFSET] == "ROLE"){
// price calculation
}
$user->roles is an array of the roles assigned to the user.
hope it helped
Make your own module with UC Price API:
http://www.ubercart.org/docs/developer/11375/price_api
function example_uc_price_handler() {
return array(
'alter' => array(
'title' => t('Reseller price handler'),
'description' => t('Handles price markups by customer roles.'),
'callback' => 'example_price_alterer',
),
);
}
function example_price_alterer(&$price_info, $context, $options = array()){
global $user;
if (in_array("reseller", $user->roles)) { //Apply 30% reseller discount
$price_info["price"] = $context["subject"]["node"]->sell_price - (
$context["subject"]["node"]->sell_price * 0.30) ;
}
return;
}
See also: http://www.ubercart.org/forum/development/14381/price_alteration_hook
I’m using a cart library to get orders in my web bookstore. But when I call a addCart function on one of my book it’s works, but not all the time. Please, help
There is my model function:
function get_books_by_ID($id)
{
$this->db->where('BOOK_ID', $id);
$query = $this->db->get('books');
return $query;
echo vardump($query);
}
Controller:
function addCards($id=1)
{
$query = $this->Kategorie_model->get_books_by_ID($id);
if($query->num_rows() > 0)
{
$item = $query->row();
$data = array(
'id' => $item->BOOK_ID,
'qty' => 1,
'price' => $item->BOOK_Price,
'name' => $item->BOOK_Title
);
$this->cart->insert($data);
}
}
View:
<tr>
<td class="color"><b>Cena: </b><?php echo $data->BOOK_Price;?>zł</td>
<td class="border" id="koszyk" ><?php echo anchor('ksiegarnia/addCards/'.$data->BOOK_ID, 'Koszyk'); ?></td>
</tr>
UPDATE:
vardump is nothing necessary. I want to use var_dump. But the problem is related with adding items to the session with carts library. I have a bookstore, and when I call a addCarts function, sometimes items is added to Carts, and cart function total() and total_items displaying it, but sometimes when I call function, nothing is happened. The items not add into carts. I don't now why this thing have a place. Why the carts library works randomly?
I just ran into this issue and it seems that in the codeigniter cart library the insert function checks the product(s) id and name against a regex only allow alpha-numeric, dashes, underscores and periods
Adjust the regex to what may come up:
$this->cart->product_id_rules = '.a-z0-9_';
$this->cart->product_name_rules = '.\:-_ a-z0-9';
In my case it would randomly add thing to carts too. If you turn on logging and check you'll be able to see that the name or id may contain invalid chars
i am doing as you did, and like you said, the cart is randomly works,
it seems can only contain 3 product in cart when i add another product, the product i added wont get into cart..
i am so hopeless, i get mind to change cart libraries with 3rd party
it is because i did not setting session to save to database, like in the tutorial (cart & session) the cart need session to write to database in order to work.
when i set session write to database, the problem solved
you can try...
I am modifying an already contributed drupal module (Inline Ajax Search) to handle searching of a specific content type with some search filters (i.e. when searching for help documentation, you filter out your search results by selecting for which product and version of the product you want help with).
I have modified the module some what to handle all the search filters.
I also added in similar functionality from the standard core search module to handle the presenting of the search form and search results on the actual search page ( not the block form ).
The problem is that when i submit the form, i discovered that I'd lose all my post data on that submit because somewhere, and i don't know where, drupal is either redirecting me or something else is happening that is causing me to lose everything in the $_POST array.
here's the hook_menu() implementation:
<?php
function inline_ajax_search_menu() {
$items = array();
$items['search/inline_ajax_search'] = array(
'title' => t('Learning Center Search'),
'description' => t(''),
'page callback' => 'inline_ajax_search_view',
'access arguments' => array('search with inline_ajax_search'),
'type' => MENU_LOCAL_TASK,
'file' => 'inline_ajax_search.pages.inc',
);
}
?>
the page callback is defined as such (very similar to the core search module's search_view function):
<?php
function inline_ajax_search_view() {
drupal_add_css(drupal_get_path('module', 'inline_ajax_search') . '/css/inline_ajax_search.css', 'module', 'all', FALSE );
if (isset($_POST['form_id'])) {
$keys = $_POST['keys'];
// Only perform search if there is non-whitespace search term:
$results = '';
if(trim($keys)) {
require_once( drupal_get_path( 'module', 'inline_ajax_search' ) . '/includes/inline_ajax_search.inc' );
// Collect the search results:
$results = _inline_ajax_search($keys, inline_ajax_search_get_filters(), "page" );
if ($results) {
$results = theme('box', t('Search results'), $results);
}
else {
$results = theme('box', t('Your search yielded no results'), inline_ajax_search_help('inline_ajax_search#noresults', drupal_help_arg()));
}
}
// Construct the search form.
$output = drupal_get_form('inline_ajax_search_search_form', inline_ajax_search_build_filters( variable_get( 'inline_ajax_search_filters', array() ) ) );
$output .= $results;
return $output;
}
return drupal_get_form('inline_ajax_search_search_form', inline_ajax_search_build_filters( variable_get( 'inline_ajax_search_filters', array() ) ) );
}
?>
from my understanding, things should work like this: A user goes to www.mysite.com/search/inline_ajax_search and drupal will process the path given in my url and provide me with a page that holds the themed form for my search module. When i submit the form, whose action is the same url (www.mysite.com/search/inline_ajax_search), then we go thru the same function calls, but we now have data in the $_POST array and one of them is indeed $_POST['form_id'] which is the name of the form "inline_ajax_search_search_form". so we should be able to enter into that if block and put out the search results.
but that's not what happens...somewhere from when i submit the form and get my results and theme it all up, i get redirected some how and lose all my post data.
if anybody can help me, it'd make me so happy lol.
drupal_get_form actually wipes out the $_POST array and so that's why I lose all my post data.
according to this: http://drupal.org/node/748830 $_POST should really be ignored when doing things in drupal. It's better to find a way around using it. One way is the way described in the link, making ur form data persist using the $_SESSION array. I'm sure there are various other and better ways to do this, but yeah, drupal_get_form was the culprit here...