I'm currently building a site for a client and they want a search feature that will search all of the products they supply.
I have created a new table in the database called sc_products and then tried the below code in a wordpress template page but I don't appear to be getting anywhere. If anyone knows how I can get this working that would be awesome!
<?php
/*
Template Name: myTemp
*/
function search_it() {
if ( is_search() && isset($_GET['s'])) {
global $wpdb;
$address_table = $wpdb->prefix . "sc_products";
$myrows = $wpdb->get_results( 'SELECT product FROM ' . $sc_products );
foreach ( $myrows as $single_row ) {
global $single_row;
}
$product = $single_row->product;
}
return $product;
}
$city = search_it();
echo $city;
get_search_form();
?>
There's a couple of things going on here, let's see if we can work them out.
Here's your modified function which should perform a search, with comments throughout to help explain what's going on.
NOTES:
1. You declare $address_table, but then use $sc_products. That can't be correct, as $sc_products is not defined.
2. This answer is based on the column names you provided in comments - IF they are not an exact match, you'll need to update them, INCLUDING matching case. If it's not Application, but instead application, you'll need to make that change.
function search_it() {
// If this is a search, and the search variable is set
if ( is_search() && isset( $_GET['s'] ) ) {
// Global in $wpdb so we can run a query
global $wpdb;
// Build the table name - glue the table prefix onto the front of the table name of "sc_products"
$address_table = $wpdb->prefix . "sc_products";
// Get the search term into a variable for convenience
$search = $_GET['s'];
// To use "LIKE" with the wildcards (%), we have to do some funny business:
$search = "%{$search}%";
// Build the where clause using $wpdb->prepare to prevent SQL injection attacks
// Searching ALL THREE of our columns: Product, Application, Sector
$where = $wpdb->prepare( 'WHERE Product LIKE %s OR Application LIKE %s OR Sector LIKE %s', $search, $search, $search );
// Execute the query with our WHERE clause
// NOTE: Your code originally used "$sc_products", but that variable was not defined - so have replaced to the proper $address_table here.
$results = $wpdb->get_results( "SELECT product FROM {$address_table} {$where}" );
// return the results. No need to put into an array, it's already an array
return $product;
}
// For consistency, return an empty array if not a search / no search term
return array();
}
// USAGE:
// Run the query
$cities = search_it();
// You can't echo an array!
// echo $city;
// var_dump to see the whole array
var_dump( $cities );
// More useful USAGE:
$cities = search_it();
// If there's any results
if ( ! empty( $cities ) ) {
// Output a title
echo '<h1>Product Search Results:</h1>';
// Loop over the results
foreach( $cities AS $city ) {
// $wpdb returns an array of objects, so output the object properties
echo '<h2>' . $city->Product . '</h2>';
echo '<p>' . $city->Application . '</p>';
echo '<p>' . $city->Sector . '</p>';
}
}
get_search_form();
Related
I want to change the layout of table present in orders.php. Specifically, instead of having rows containing the data (name, date, status, etc.), I want separate horizontal cards for each product.
Example: https://i.stack.imgur.com/itdGU.png. I'm trying to do this with a shortcode, but I'm not sure if that's the right way. Can anyone give me directions ?
For now I'm trying this way: The code below works and returns all order numbers correctly. However I am getting all the order numbers side by side as a simple line of text: https://i.stack.imgur.com/RqdVC.png. I don't know how to insert div, or css classes to change the layout.
Even if I add css classes, the question that remains is how to add other elements such as name, price, status etc. Not sure it can all be done in one shortcode. Advice ?
// GET ALL ORDERS NUMBER OF CURRENT USER
// Give the callback function a clear and descriptive name.
add_shortcode( 'prcsed_order_numbers' , 'prcsed_order_1' );
function prcsed_order_1() {
// Get all orders for the current user.
$customer_orders = wc_get_orders([
'customer_id' => get_current_user_id(),
]);
// Transform the array of order objects into an array of order names.
$order_numbers = array_map( function( $order ) {
return $order->get_order_number();
}, $customer_orders );
// Return as a string, ready for output,
return implode( ', ', $order_numbers );
}
Expanding on what I was typing before. You can access more order variables using what you were already doing in $order_numbers. Here is what I have tested on standalone WooCommerce test site. You will need to input your customer ID function and modify the return HTML structure for styling and editing simplicity. What I have is not clean but does work.
$results = wc_get_orders([ 'cutomer_id'=>1 ]);
foreach ( $results as $order ) {
$first_name = $order->get_billing_first_name();
$last_name = $order->get_billing_last_name();
$status = $order->get_status();
echo '<h1>' . $first_name . ' ' . $last_name . '</h1><p>' . $status . '</p>';
}
The following link gives you the functions/hooks for the order object that you will need accessing to. https://www.businessbloomer.com/woocommerce-easily-get-order-info-total-items-etc-from-order-object/
GOAL
I currently have an acf field group with some fields for generic data like phonenumber, email, etc. (all simple text fields).
My goal is to have one function that will loop over all the fields and create a shortcode based on their respective name/label.
EDIT: PROGRESS
I think I am getting closer, simplified the whole thing and I believe I am on the right path..
I attached the field group to a post and if I log them like so:
$testing = get_field_objects(22);
do_action( 'php_console_log', $testing );
I get all the names, values etc. With the help of another snippet I found the shortcodes seem to be at least dynamic since they all stop showing just that there is no value somehow so it all stays blank.
This is the function now:
$hlfields = get_field_objects( 22 );
foreach ( $hlfields as ['name' => $name, 'value' => $value] ) {
${"{$name}_fn"} = function() {
$field = get_field($name, 22);
return $field;
};
add_shortcode($name, ${"{$name}_fn"});
}
Original attempt, not working and over complicated:
I currently have an acf field group with some fields for generic data like phonenumber, email, etc. (all simple text fields).
To be able to insert them all easily using a shortcode, I create one for each field like so:
function adresse_shortcode( $adresse ) {
$adresse = get_field( "adresse", 'option' );
return $adresse;
}
add_shortcode('adresse', 'adresse_shortcode');
While this works fine, I feel like I am repeating myself unnecessarily and also I need to add a function whenever I add a new field.
My goal is to have one function that will loop over all the fields and create a shortcode based on their respective name/label.
I found this snippet to get all fields of a field group by ID:
function get_specifications_fields() {
global $post;
$specifications_group_id = 13; // Post ID of the specifications field group.
$specifications_fields = array();
$fields = acf_get_fields( $specifications_group_id );
foreach ( $fields as $field ) {
$field_value = get_field( $field['name'] );
if ( $field_value && !empty( $field_value ) ) {
$specifications_fields[$field['name']] = $field;
$specifications_fields[$field['name']]['value'] = $field_value;
}
}
return $specifications_fields;
}
But I can't figure out how to create the shortcodes now, I have been trying everything I could think of along these lines:
function adresse_shortcode( $value ) {
$specifications_fields = get_specifications_fields();
foreach ( $specifications_fields as $name => $field ) {
$value = $field['value'];
$label = $field['label'];
$name = $field['name'];
return $name;
}
add_shortcode($value, 'adresse_shortcode');
}
I am not well versed in PHP so I am sure it's all sorts of wrong but I have been trying to figure it out for hours and was hoping someone might be able point me in the right direction.
Here's an example using anonymous functions that should do the trick
$hlfields = get_field_objects( 22 );
foreach ( $hlfields as ['name' => $name, 'value' => $value] ) {
$cb = function() use ($name) {
$field = get_field($name, 22);
return $field;
};
add_shortcode( $name, $cb );
}
Here's the sources i referred to while answering: Dynamic function name in php, Dynamic shortcodes and functions in WordPress, PHP: Variable functions
I have a section on my wordpress website that currently displays the child and parent categories of a listing. I would like for only the child categories to be displayed. I wasn't able to figure out the solution on my own, your help is appreciated.
Here is the current code I'm using for this (which also displays parent categories):
<?php
//NEW
$permalink = get_permalink( $id );
//NEW
$seo = get_the_title()." : ";
$Category_links = ' Found in the ';
$term_list_category = wp_get_post_terms(get_the_ID(), 'listings_categories', array("fields" => "ids"));
//THIS CODE REMOVES PARENTS FROM BEING DISPLAYED IN THE LISTING CATEGORIES
foreach ($term_list_category as $k=>$term) {
$children = get_term_children( $term, 'listings_categories');
if ($children)
unset($term_list_category[$k]);
}
$i = 0;
$count = count($term_list_category);
if ( $count > 0 ){
foreach ( $term_list_category as $term_category ) {
$thisCat = get_term_by( 'id', $term_category, 'listings_categories');
//NEW
$url = '<a id="'.$term_category.'" slug="'.$thisCat->{'slug'}.'" class="listing-links-cat" href="#" title="'.$thisCat->{'name'}.'" >'.$thisCat->{'name'}.'</a>';
$i ++;
$seo .= " " . $thisCat->{'name'} . "";
$Category_links .= " " . $url . "";
if($count-1 == $i){
$Category_links .= " and "; $seo .= ", ";
}elseif($count > 1 && $count !== $i){
$Category_links .= ", "; $seo .= ", ";
}
}
$Category_links .= " Categories";
?>
<? echo $Category_links; ?>
But I feel that the overall code can be improved for performance, so it doesn't search the database as much?
Your code is quite ineffecient and also have unnecessary parts to it. Your additional part makes your code even more ineffecient and causes you to hit the db hard.
FLAWS
You get plus 1 for only getting the term id's from the post terms, but unfortunately in this specific case, this tampers your code and this is the starting point of your ineffeciency as you then need to use get_term_by() on every iteration of your foreach loop. This means extra db calls on every iteration for something that should have already been there
The use of get_term_children() adds to the amount of db calls made on every iteration of your foreach loop. Again, you are making unnecessary db calls for something that should have been there in the first place
It is totally unnecessary to count the amount of terms returned by wp_get_post_terms. This adds extra ineffeciency to your code. wp_get_post_terms returns an empty array if no terms exists or a WP_Error object if the taxonomy does not exist. Keep this in mind for later on
SPEEDING IT UP AND STREAMLINING THE CODE
Lets look at what we can do to make your code more effecient
Remove the fields parameter from wp_get_post_terms. As we need more than just the ids of the terms, we need to return the complete term object. You might think that this is ineffecient, but this will save you a lot of db hits and most importantly, time, as you are getting rid of get_term_by() and get_term_children()
There is no proper way to remove parents from wp_get_post_terms(), so the best way will be to just loop over them and ignore/skip them with continue. I assume you are talking about top level terms which have 0 assigned to its $parent property, so you just need to check that the parent value is not 0
Always do proper failure checks. If you don't do that, and your code fails, php error and notices are returned, which is known as bugs. You would want to avoid that. Also, you would always want your code to fail in a controlled, expected manner without bugs. As I stated before, wp_get_post_terms() returns an empty array or a WP_Error object, so this is what you need to check for. If any of these cases occur, immediately halt execution and return the function to avoid bugs and unexpected output
PUTTING THE ABOVE IN CODE
I like to keep my template files short and sweet. For that reason, bulky code the above always goes into a function and I then just call the function in my template files where necessary. Also, just a tip, I have function specific functions files to keep my code organised and not to overload functions.php. my functions.php file is usually not more than 100 lines of code.
For example, this is part of your post's meta, so this will go into a file with other meta functions like displaying the autor name and post date.
function get_post_child_terms( $taxonomy = '' )
{
$current_post = get_queried_object_id();
$terms = wp_get_post_terms( $current_post, $taxonomy );
/*
* Check if $taxonomy has a value, also check for WP_Error or empty $terms. If any of these conditions
* are met, halt execution and return false
*/
if ( !$taxonomy || is_wp_error( $terms ) || empty( $terms ) )
return false;
/*
* We have made it to here safely, now iterate over the terms
*/
foreach ( $terms as $term ) {
/*
* Check for parent terms and ignore them
*/
if ( $term->parent == 0 )
continue;
/*
* Get an array of term names
*/
$term_names[] = $term->name;
}
/*
* Build our string of names
*/
if ( !isset( $term_names ) )
return false;
$string = 'Some text here maybe to start of: ' . implode( ',', $term_names ) . 'Maybe something at the end';
return $string;
}
USAGE
You can now simply call the function in your template as follow:
echo get_post_child_terms( 'listings_category' );
This will produce a list like this
Some text here maybe to start of: Term name 1, Term name 2, Term name 3 Maybe something at the end
FINAL NOTES
The code above is untested and might be a bit buggy.
The code above is the very least that you need. You can extend and misuse it as you see fit to fit your exact needs. A few ideas for extension might be to work in some arguments to where you can choose to display the parent terms or not, and whether the function should return a string of term names or an array of term names. The sky is the limit here
You can build in a cache system to cache your results to optimize these even further.
EDIT
The above code is now tested and is working as expected
I'll start by throwing myself on the mercy of you fine people as a complete newb to php and stackoverflow. I've searched for the answer here and elsewhere and I'm having trouble piecing it all together.
Here's my problem-
I've set up a form (using gravity forms) where logged in users can log "flight hours" after every flight. I'm using gravity forms to post this data to a custom post called "my-flight-record" where I've mapped all the fields from the form. Now, I simply want to show the user a running total of one field, wpcf-total-flight-time, but i only want to show the user their own total time.
Here's the code i'm currently using, but it sums ALL entries. I only want to sum the entry for the current user (who should also be logged in before they can even see this page).
<?php
//get current user
global $current_user;
get_currentuserinfo();
$userPosts = get_posts(array('author' => $current_user->ID, 'post_type'=> 'my-flight-record'));
// loop to create array of ids by user
foreach ($userPosts as $post) {
setup_postdata($post);
$ids[] = get_the_ID();
}
$idList = implode(",", $ids);
$meta_key = 'wpcf-total-flight-time';//set this to your custom field meta key
$allflighthours = $wpdb->get_col($wpdb->prepare("
SELECT meta_value
FROM $wpdb->postmeta
WHERE meta_key = %s
AND post_id in (" . $idList . ")", $meta_key));
echo 'My total flight hours logged = ' . array_sum( $allflighthours) . ''; ?>
This code results in a total, but for everyone, not just logged in user. Also, the '$idList = implode(",", $ids);' line results in an error for me.
Please help me help myself! I'm sure I've left out vital info - let me know what i'm missing!
Why do you need two separate database queries? Try this:
<?php
//get current user
global $current_user;
get_currentuserinfo();
$userPosts = get_posts(array('author' => $current_user->ID,
'post_type'=> 'my-flight-record'));
//initialize an empty array
$flight_hours = array();
// loop to create array of ids by user
foreach ($userPosts as $post) {
setup_postdata($post);
$flight_hours[] = get_post_meta(get_the_ID(), 'wpcf-total-flight-time', true);
}
printf('My total flight hours logged = %s ', array_sum( $flight_hours) ); ?>
As ipauler notes in his answer, you should implement some error checking to make sure there is a logged in user, and the wpcf-total-flight-time data is both present and valid.
First you need to check if user is logged in
Some example from wordpress documentation
if(!is_user_logged_in()) {
//no user logged in
}
http://codex.wordpress.org/Function_Reference/get_currentuserinfo#Parameters
//get current user
global $current_user;
if(is_user_logged_in()) {
get_currentuserinfo();
$userPosts = get_posts(array('author' => $current_user->ID, 'post_type'=> 'my-flight-record'));
// loop to create array of ids by user
foreach ($userPosts as $post) {
setup_postdata($post);
$ids[] = get_the_ID();
}
$idList = implode(",", $ids);
$meta_key = 'wpcf-total-flight-time';//set this to your custom field meta key
$allflighthours = $wpdb->get_col($wpdb->prepare("
SELECT meta_value
FROM $wpdb->postmeta
WHERE meta_key = %s
AND post_id in (" . $idList . ")", $meta_key));
echo 'My total flight hours logged = ' . array_sum( $allflighthours) . '';
}
I am having a problem for a while now and I can´t seem to solve it on my own.
I have made a website, this website is multilingual and it was made in wordpress.
In my "photo album" page when I sort the items in the default language (English) everything works fine, however if I change to another translation (ex.french), the name of the category changes and the tagged items don't appear anymore.
http://madebysylvie.be/collection
In my database I manage to find the table and the rows of each category, I want to be able access it in a different language, each one has an unique ID.
I know I have to grab the ID from the database of each category and return it to my PHP script.
This is my code,
<ul class="filter_portfolio">
<?php
// Get the taxonomy
$terms = get_terms('filter', $args);
// set a count to the amount of categories in our taxonomy
$count = count($terms);
// set a count value to 0
$i=0;
// test if the count has any categories
if ($count > 0) {
// break each of the categories into individual elements
foreach ($terms as $term) {
// increase the count by 1
$i++;
// rewrite the output for each category
$term_list .= '<li class="segment-'.$i.'">' . $term->name . '</li>';
// if count is equal to i then output blank
if ($count != $i)
{
$term_list .= '';
}
else
{
$term_list .= '';
}
}
// print out each of the categories in our new format
echo $term_list;
}
?>
</ul>
However I am not good enough to do this on my own, and I would be very happy if someone could help me out on this one.
I don't know how to query my database, and I am not shore how to modify the php in order to print it in the other languages.
Thanks
Please refer to the Wordpress documentation, the "Codex":
Class Reference/wpdb – Interfacing With the Database
Displaying Posts Using a Custom Select Query
Class Reference/WP Query –
Custom Queries – how to modify queries using hooks
But remember »Most of the time you can find the information you want without actually dealing with the class internals and globals variables. There are a whole bunch of functions that you can call from anywhere that will enable you to get the information you need.«
WP_Query example from the docs:
<?php
// The Query
$the_query = new WP_Query( $args );
// The Loop
if ( $the_query->have_posts() ) {
while ( $the_query->have_posts() ) {
$the_query->the_post();
echo '<li>' . get_the_title() . '</li>';
}
} else {
// no posts found
}
/* Restore original Post Data */
wp_reset_postdata();