Sort search results by meta_key value - php

I really need help with this. Below is a code of my wp page template for search results search.php and everything works just fine. Now, the website is about public events so it's very important that search results are displayed by event date. I've created a custom field called "date" and I'd like to display the results by "date" field value.
I spent a whole week to find a solution but unfortunately I couldn't. Please, help me :)
Here is a code:
<?php
global $query_string;
$query_args = explode("&", $query_string);
$search_query = array();
if( strlen($query_string) > 0 ) {
foreach($query_args as $key => $string) {
$query_split = explode("=", $string);
$search_query[$query_split[0]] = urldecode($query_split[1]);
}
}
$search = new WP_Query($search_query);
?>
<?php if ($search->have_posts()) : while ($search->have_posts() ) : $search->the_post(); ?>
<!-- loop goes here -->
<?php endwhile; else: ?>
<?php endif; ?>
Thank you!!!!

I'd try something else:
In your functions.php or my-plugin.php
add_filter( 'pre_get_posts', 'customize_search_page' );
function customize_search_page($query){
if(!is_admin() && $query->is_search && $query->is_main_query()){
$query->query_vars['meta_key'] = 'your_meta_key';
$query->query_vars['orderby'] = 'meta_value';
$query->query_vars['order'] = 'DESC';
}
return $query;
}
I did not tested it but the pre_get_posts filter will be called before the loop. If it's the right query (search and main) I changed the orderby to an order by meta value.

Related

Simple shortcode $id+$title with small html

I have a simple need to put a shortcode at the end of my articles on wordpress with the post id and post title.
I want to add a (ref:) in front of $id and enclose it all in h4
the desired result look like this
<h4 ref: 123 this is my first post <h4>
I'm having a hard time getting the logic of how to do it
my shortcode
function post_id_title( ){
$id = get_the_ID();
$title = get_the_title();
$result = $id . $title ;
return $result;
}
add_shortcode( 'page_title', 'post_id_title' );
Try this since you got the hardest part right.
function post_id_title( ){
$id = get_the_ID();
$title = get_the_title();
$result = "<h4>ref: $id $title</h4>";
return $result;
}
add_shortcode( 'page_title', 'post_id_title' );

Exclude Wordpress Category

I have a loop do display the different categories to go on the archive page.
How can y only display the categories one time ?
Currently, if two posts had the same category, there is two time the category
This is my code below
<div class="row ptb-20">
<?php
$args = array(
'category_name' => 'actualites',
);
// Custom query.
$query = new WP_Query( $args );
// Check that we have query results.
if ( $query->have_posts() ) {
// Start looping over the query results.
while ( $query->have_posts() ) {
$query->the_post();?>
<div class="category-filter">
<div class="single-filter">
<?php
$categories = get_the_category();
$separator = ", ";
$output = ' ';
if ($categories) {
foreach ($categories as $category) {
$output .= '<li>' . $category->cat_name . '</li>';
}
echo trim($output, $separator);
}
?>
</div>
</div>
<?php
} // End while
} // End if
else { echo '<p>Aucune actualité trouvée</p>'; } ?>
<?php wp_reset_postdata(); ?>
</div>
Method 1: Exclude a Category from WordPress Using Plugin
First thing you need to do is to install and activate the Ultimate Category Excluder plugin. For more details, you should follow our guide on how to install a WordPress plugin.
Upon activation, you’ll need to go to Settings » Category Excluder page. It will display all the categories that are available on your WordPress blog.
Method 2: Exclude a Category from WordPress Homepage Using Code
This method requires you to add code to your WordPress files. If you haven’t done this before, then see our guide on how to copy and paste code snippets in WordPress.
You will need to add following code to your theme’s functions.php file or a site-specific plugin.
function exclude_category_home( $query ) {
if ( $query->is_home ) {
$query->set( 'cat', '-5' );
}
return $query;
}
add_filter( 'pre_get_posts', 'exclude_category_home' );
Don’t forget to replace ID (-5) with your category ID. It will hide all blog posts from homepage belonging to the category that matches this ID.
Note: Make sure to add a minus (-) sign with the category ID.
Please refer: https://www.wpbeginner.com/wp-tutorials/how-to-exclude-a-category-from-your-wordpress-homepage/
If I understand your issue correctly, you can introduce a variable in which you would remember what categories has already been used, so you don't include them more than once.
<div class="row ptb-20">
<?php
$args = array(
'category_name' => 'actualites',
);
// Custom query.
$query = new WP_Query( $args );
// Check that we have query results.
if ( $query->have_posts() ) {
// Start looping over the query results.
while ( $query->have_posts() ) {
$query->the_post();?>
<div class="category-filter">
<div class="single-filter">
<?php
$categories = get_the_category();
$categories_displayed = [];
$separator = ", ";
$output = ' ';
if ($categories) {
foreach ($categories as $category) {
if (!in_array($category->cat_name, $categories_displayed)) {
$output .= '<li>' . $category->cat_name . '</li>';
$categories_displayed[] = $category->cat_name;
}
}
echo trim($output, $separator);
}
?>
</div>
</div>
<?php
} // End while
} // End if
else { echo '<p>Aucune actualité trouvée</p>'; } ?>
<?php wp_reset_postdata(); ?>
</div>

restrict product page with product category 'x' WooCommerce

I wan't to restrict certain product pages from logged-out users or users with a specific role. The easiest way would probably be to check the category ID of the product page and if current_user_can('') than redirect to the main shop page.
However I don't really know where to start.. Should I add an action on init? And how do I check for the current page product ID?
I thought I could get some data with a var_dump() But that resulted in nothing.
I did this:
add_action('init', 'get_all_post_meta');
function get_all_post_meta() {
//$meta = get_post_meta( get_the_ID() );
global $post;
var_dump('$post');
$metavar = get_the_terms($post->ID);
var_dump('$metavar');
}
But no results in my console.
Edit: I found my var_dump() was incorrect as it should be like var_dump($post); Continuing my quest now.
This is my solution so far, now I need to figure out how to remove a single product instead of them all.
add_action('wp_head', 'get_all_post_meta', 1 );
function get_all_post_meta() {
global $post;
$banned_cid = array(8);
$current_cid = array();
$metavar = get_the_terms($post->ID, 'product_cat');
global $woocommerce;
$redirect_url = 'http://www.example.nl/';
if(current_user_can('subscriber') || current_user_can('manage_options')){}else if( is_product()){
foreach ( $metavar as $term ) {
$cat_id .= $term->term_id.',';
array_push($current_cid, $term->term_id);
}
var_dump($current_cid);
$c = array_intersect($banned_cid, $current_cid);
if (count($c) > 0) {
$woocommerce->cart->empty_cart();
wp_redirect( $redirect_url, 302 );
exit;
}
}
}

is_page() is not executed

I am making infinite scroll page. I created a page template where posts of certain category are loaded. Everything works fine with a single page and single category.
But I have three pages with this page template and each page should load articles from a specific category. I am using the is_page() if elseif block to determine on which page visitor is. But is_page() is not executed.
Here is the loop:
$cat = '';
if(is_page(703)){
$cat = 4;
} elseif (is_page(706)) {
$cat = 21;
}
$args = array(
'cat' => $cat,
'paged' => $paged
);
$infinite_news_query = new WP_Query($args);
if ( $infinite_news_query -> have_posts() ) : while ( $infinite_news_query -> have_posts() ) : $infinite_news_query -> the_post();
<?php endwhile; ?>
<?php else : ?>
<?php endif; ?>
<?php wp_reset_postdata();
?>
This code displays all the posts, regardless of category, and $cat is empty inside the loop.
What am I doing wrong?
Thanks!
Change the following:
$cat = '';
if(is_page(703)){
$cat = 4;
} elseif (is_page(706)) {
$cat = 21;
}
to:
if(is_page('703')){
$cat = 4;
} else { if(is_page('706')) {
$cat = 21;
}
Also removing $cat = '';
Look at it like this, at first you have the variable $cat set to empty value, respectively, to false , zero or 0.
Then you set a loop, with only two states, leaving out a default value.
So, what is going to happen, when your page ID is changed?
You get all the posts displayed.
In other words, I do not see anything bad in the code. I would rather recommend you to use is_page('slug') than with id.

Function output empty values in wordpress functions.php but works when called from another page

function get_people_cats($taxonomy) {
$output = '';
$terms = get_terms($taxonomy);
$count = count($terms);
if ( $count > 0 ):
foreach ( $terms as $term ):
$output .= "'". $term->name ."'". '=>';
$output .= "'". $term->term_id."',";
endforeach;
endif;
return $output;
}
This function returns a list of custom taxonomies and which words are found if the function is called in a template. But I want to assign the the function values to a variable in functions.php, and it's returning nothing.
If your Taxonomies are actually creaetd with a plugin instead of creating them with code in your functions.php the result of get_terms will be empty untill the taxonomies have initiated, which is on plugin level initiation better yet, most probably using the 'init' hook, so you would have to hook your function after the hook and use it only in your theme template files (not in functions.php) basicly you do something like:
add_action('init', 'get_people_cats', 9999);
Then you would call it normaly: $cats = get_people_cats('person_category');
Hope this solves your issue (I know it took me around an hour to solve this when I ran into it).
If you're not getting terms back it's probably due to where the taxonomy is being registered. If it's being registered in an init hook then you're likely trying to print them out before the taxonomy has actually been registered.
You can test it with the following:
function get_people_cats( $taxonomy ) {
$output = '';
$terms = get_terms('category');
$count = count( $terms );
if ( $count > 0 ):
foreach ( $terms as $term ):
$output .= $term->name.'=>'.$term->term_id;
endforeach;
endif;
return $output;
}
function echo_cats() {
echo get_people_cats('taxonomy_name', array('hide_empty' => 0) );
}
add_action('wp_footer', 'echo_cats');
By hooking into wp_footer it's not being called until well after any plugins that might have registered the taxonomy.
// UPDATE //
Got it. To create an array just do this:
$terms = get_terms($taxonomy, array('hide_empty' => false) );
if( !is_wp_error( $terms ) ) {
foreach( $terms as $term ) {
$types[$term->term_id] = $term->name;
}
}
return $types;
}
That will give you an array of $term->id => $term->name -- you may want to reverse that depending on how you're using the array.
Try this, works fine in my functions.php file on a local site:
function get_people_cats( $taxonomy ) {
$output = '';
$terms = get_terms( $taxonomy );
$count = count( $terms );
if ( $count > 0 ):
foreach ( $terms as $term ):
$output .= $term->name.'=>'.$term->term_id;
endforeach;
endif;
return $output;
}
echo get_people_cats('category');

Categories