WordPress change search results - php

I have got the problem that my WordPress theme ("Sydney") is displaying the search results wrong. Instead of just listing posts I want to display WooCommerce products only.
Those should be ordered in a nice grid as shown in this picture:
.
At the moment the results are listed like this
.
How can I change the way the search results are displayed?
At the moment my search.php is looking like this:
<?php get_header(); ?>
<div id="primary" class="content-area col-md-9">
<main id="main" class="post-wrap" role="main">
<?php if ( have_posts() ) : ?>
<header class="page-header">
<h3><?php printf( __( 'Search Results for: %s', 'sydney' ), '<span>' . get_search_query() . '</span>' ); ?></h31>
</h3>
</header><!-- .page-header -->
<?php /* Start the Loop */ ?>
<?php while ( have_posts() ) : the_post(); ?>
<?php
/**
* Run the loop for the search to output the results.
* If you want to overload this in a child theme then include a file
* called content-search.php and that will be used instead.
*/
get_template_part( 'content', 'search' );
?>
<?php endwhile; ?>
<?php the_posts_navigation(); ?>
<?php else : ?>
<?php get_template_part( 'content', 'none' ); ?>
<?php endif; ?>
</main><!-- #main -->
</div><!-- #primary -->
Thank you guys a lot!
** UPDATE
The solution provided by kashalo partly worked, but search results still look slightly different from the product page and are listed in only one column instead of a grid.
** UPDATE
The solution suggested by Alexander Wigmore looks almost the way I wanted it so look like. The only Problem with copying the page.phpin the search.phpis that the products are still getting displayed wheird, but not when they are displayed in the category they fit in. For example: When searching for saat the results are displaying the products at first with text only, but normaly under the Saatgut category.

my advise is not to directly modify the search file of wp or theme template but is a good practice to work with the child theme. For the design display of the result you can play a little with css to customize it as you want, instead for the results to show only the products you can use any filter builded on the theme you are using (if it have) or create yourself a function to filter the results (also called hooks).
An example for filtering results is like the above code:
add_action( 'pre_get_posts', 'filter_woocommerce_products' ); // the hook
function filter_woocommerce_products( $query ) { // the function
if( ! is_admin() && is_search() && $query->is_main_query() ) {
// verify if can use the search function and the search string is from the search call
$query->set( 'post_type', 'product' ); // filter the posts with type products that corrispond to woocommerce products.
}
}
and this function must be saved on the function.php file of your theme or the child theme.
For more information i suggest you to read more about child theme and the pre_get_posts documentation on the wp page.
Hope it helps and feel free to ask.

You'll want to modify the way search is handled by Wordpress.
This can easily be done by adding an "action", add the below code to your functions.php file.
function searchfilter($query) {
if ($query->is_search && !is_admin() ) {
$query->set('post_type',array('product'));
}
return $query;
}
add_filter('pre_get_posts','searchfilter');
This will then make the search page only show products. It's worth noting that you can add other post types back in via the array in this line: $query->set('post_type',array('product'));.

Related

Wordpress - Display only pages with specific template in search results

I want to display in my WP search results ONLY pages with specific template beceuse I trying to build product catalog without any plugins. Pure WP code. Some pages are my products, and they have product.php template file. This is my search.php:
<?php
if ( have_posts() ) :
while ( have_posts() ) :
the_post();
get_template_part( 'template-parts/post/content', 'excerpt' );
endwhile;
the_posts_pagination();
else :
?>
<p><?php _e( 'No results.' ); ?></p>
<?php
get_search_form();
endif;
?>
And the question is, how to display only my product pages without any other pages?
Try this out!
This function will interrupt the search query and add some condition fo the query to returns specific pages.
//Filter the search for only posts and parts
function SearchFilter($query)
{
// Now filter the posts
if ($query->is_main_query() & $query->is_search && $search_template) {
$query->set('post_type', 'page');
$query->set('meta_key' => '_wp_page_template',);
$query->set('meta_value' => 'product.php');
}
// Returning the query after it has been modified
return $query;
}
add_action('pre_get_posts', 'SearchFilter');
Explaining the code:
The "post_type" will limit this filter for page post type only.
The condition Will limit this filter to only work on the search queries and not every time the posts query is called.
$query->is_search && $search_template
These parameters will filter the returned posts by the meta_key "_wp_page_template" which contains the page template, so we only return the pages with the page template "product.php".
$query->set('meta_key' => '_wp_page_template',);
$query->set('meta_value' => 'product.php');

How to add a custom block as a usual "product" to shop page / archive-product.php

I'm looking for a possibility to add a custom html block/post to the woocommerce "shop page" inside the products grid, as a product.
What I mean.. I have a grid of products on the "shop" page (archive-product) and I want to create a special post/page/html block with some text information, that will be inserted into the products grid as a one of "product", but with no price, with no title and unclickable. I've attached the screenshot of the final result I want to have, it's really self explaining - here it is exactly what I'm looking for.
As an idea probably I can create a special product with specific slug or title and the corresponding script with pre_get_posts hook will find this post/product and modify it to look like I need. I'm looking for some code/ideas how to insert this specific block/page/post into the archive-product page on some position in the grid. Thanks!
Thanks for help, guys! I've implemented the functionality I was looking for. I've found the corresponding loop in archive-product.php and as was suggested by JapanGuy, I've added a simple "if i equal let's say 5 then echo < li>[Custom block]< /li>" .
The original snippet from archive-product.php:
<?php woocommerce_product_loop_start(); ?>
<?php woocommerce_product_subcategories(); ?>
<?php while ( have_posts() ) : the_post(); ?>
<?php wc_get_template_part( 'content', 'product' ); ?>
<?php endwhile; // end of the loop. ?>
<?php woocommerce_product_loop_end(); ?>
Modified code with inserted custom block:
<?php woocommerce_product_loop_start(); ?>
<?php woocommerce_product_subcategories(); ?>
<?php while ( have_posts() ) : the_post(); ?>
<?php
if ($i == 5) {
echo "<li>[Custom block]</li>";
}
$i++;
?>
<?php wc_get_template_part( 'content', 'product' ); ?>
<?php endwhile; // end of the loop. ?>
<?php woocommerce_product_loop_end(); ?>
Im such simple way I can add any content to the created [Custom block] and have an usual products grid with extra custom designed block. I'm not very experienced programmer, so probably my code is not perfect, but it works. Thanks!
Edit: Previous code was wrong, changed it here
$i=0;
while ($row = mysqli_fetch_array($query))
{
if ($i == 2) {
echo "Cusom block";
}
echo "<p> Product block " . $row['column'] . " </p>";
$i++;
}
Creating WordPress Custom Post Archives : Hope this meets your requirement.
Custom Post Archives list your custom content. You probably already know the standard WordPress archives. So you can follow this to display both together .
Ref here : https://wp-types.com/documentation/user-guides/creating-wordpress-custom-post-archives/

Proper way to make function calls in WordPress

What is best practice for making a function call on a wordpress page?
For instance if you want to call my_special_function(); on the home page, where is the proper place to put the function call (ie home-page.php, /template-parts/content-page.php etc.).
<?php if( function_exists( my_special_function ) ) {
my_special_function();
} ?>
FYI Im using Underscores theme.
I've seen a few comments regarding shortcode. Would something like the below WP page template with the shortcode inserted be a best practice over just calling the function on that page?
So if I wanted the function to be called in the page template below I would just insert the shortcode wherever I want it on that page template or just is just calling the function is sufficient or best practice
<?php
/**
* Template Name: Home Page
*
* The template for displaying the home page.
*
* #link https://codex.wordpress.org/Template_Hierarchy
*
* #package Rollins_Ridge
*/
get_header(); ?>
<div id="primary" class="content-area">
<main id="main" class="site-main" role="main">
// insert Shortcode
<?php echo do_shortcode('[special_function_shortcode]') ;?>
// or just call the function
my_special_function();
// or something else im not aware of
code here;
<?php
while ( have_posts() ) : the_post();
get_template_part( 'template-parts/content', 'page' );
// If comments are open or we have at least one comment, load up the comment template.
if ( comments_open() || get_comments_number() ) :
comments_template();
endif;
endwhile; // End of the loop ?>
</main><!-- #main -->
</div><!-- #primary -->
<?php
get_footer();
Don't edit themes core files.
the proper way is using functions.php file in child theme directory.
you can add your function in this file and create shortocde using wordpress hook
like
my_special_function(){
//Your content goes here.
echo "This is proper way";
}
add_shortcode('special_function_shortcode','my_special_function');
and use following shortocde anywhere on site.
in wordpress page use [special_function_shortcode]
and in php use
<?php echo do_shortcode('[special_function_shortcode]') ;?>

Post in wrong category

I've a weird problem, some posts appears in categories where they are not in.
When I look in my backoffice and filter by categories, some post appears there but they are not checked in.
The resultat is that in the front office they appear too.
This is my category.php (but I don't think it's the matter)
<?php
get_header();
?>
<section id="wrapper" class="page <?php echo get_query_var('cat'); ?>">
<div id="container">
<?php
$category = get_category(get_query_var('cat'));
$cat_id = $category->cat_ID;
query_posts('showposts=1&cat='.$cat_id);
if ( have_posts() ) :
while ( have_posts() ) : the_post();
get_template_part( 'content', get_post_format() );
endwhile;
endif;
?>
</div>
</section>
<?php
get_footer();
?>
I looked in the table "_term_relationships" and everything is right, they're not in the wrong categories.
So maybe someone have a clue to find out ?
PS : I'm using WPML, but if I desactive it, it's the same problem
You should not use query_posts(),
see (https://wordpress.stackexchange.com/questions/1753/when-should-you-use-wp-query-vs-query-posts-vs-get-posts)
try this:
<?php
$category = get_category(get_query_var('cat'));
$cat_id = $category->cat_ID;
$args = array( 'category' => $cat_id );
$query2 = new WP_Query($args);
if ( $query2->have_posts() ) :
while ( $query2->have_posts() ) :
$query2->the_post();
get_template_part( 'content', get_post_format() );
endwhile;
endif;
?>
First of all, never use query_posts to construct any type of query
Note: This function isn't meant to be used by plugins or themes. As explained later, there are better, more performant options to alter the main query. query_posts() is overly simplistic and problematic way to modify main query of a page by replacing it with new instance of the query. It is inefficient (re-runs SQL queries) and will outright fail in some circumstances (especially often when dealing with posts pagination).
Secondly, never change the the main query for a custom query on any type of archive page or home page. The correct way is to use pre_get_posts to alter the query variables before the main query executes. Check out this post I've done a while ago
Thirdly, category pages in Wordpress does work in a strange way. When a category page is visited, it will display posts from the selected category and posts from the selected category's child categories. I bet this is what you are seeing. This is pretty normal behavior. If you need to change this, have a look at this answer on WPSE by #ialocin. For the benefit of this answer, here is the solution
add_filter(
'parse_tax_query',
'wpse163572_do_not_include_children_in_category_archive_parse_tax_query'
);
function wpse163572_do_not_include_children_in_category_archive_parse_tax_query( $query ) {
if (
! is_admin()
&& $query->is_main_query()
&& $query->is_category()
) {
// as seen here: https://wordpress.stackexchange.com/a/140952/22534
$query->tax_query->queries[0]['include_children'] = 0;
}
}

Wordpress Page of Posts

I am building a personal website to host my university work, personal projects and photos etc.
The menu is a hierarchical structure made up of pages and links. Take my university pages for example. What I would like to achieve is to display posts that are related to the module code which is the page's slug.
I've used the following link http://codex.wordpress.org/Page_Templates#A_Page_of_Posts and managed to get it working but I have hard coded the module code into the template, meaning for each module I will have to have a separate template and the only thing that will be different from one file to the next is 5 characters which isn't great for code re-use.
What I am asking, is, is there a way to get the slug from the page I'm looking at and use that for the WP_Query arguments.
If you go to http://michaelnorris.co.uk/ and look at the menu structure. Navigate to University -> Year Three -> Individual Project, you will notice the url is http://michaelnorris.co.uk/uni/three/ci301 where ci301 is the module code for the Individual Project. I want to have this system on each of the module pages so that I can tag posts and they are displayed in the relevant module.
Ok, I actually found the answer myself, but for others looking to do the same. Below is a solution.
Solution found here on the Wordpress.org Codex http://codex.wordpress.org/Page_Templates#A_Page_of_Posts
Name the file pageofposts.php and edit the Page within the Wordpress Dashboard and set the Template (in the dropdown) to 'Page of Posts'. Bingo!
<?php
/*
Template Name: Page Of Posts
*/
/* This example is for a child theme of Twenty Thirteen:
* You'll need to adapt it the HTML structure of your own theme.
*/
get_header(); ?>
<div id="primary" class="content-area">
<div id="content" class="site-content" role="main">
<?php
/* The loop: the_post retrieves the content
* of the new Page you created to list the posts,
* e.g., an intro describing the posts shown listed on this Page..
*/
global $post;
$slug = get_post( $post )->post_name;
if ( have_posts() ) :
while ( have_posts() ) : the_post();
// Display content of page
get_template_part( 'content', get_post_format() );
wp_reset_postdata();
endwhile;
endif;
$paged = (get_query_var('paged')) ? get_query_var('paged') : 1;
$args = array(
// Change these category SLUGS to suit your use. category_name is comma separated.
'tag' => $slug,
'paged' => $paged
);
$list_of_posts = new WP_Query( $args );
?>
<?php if ( $list_of_posts->have_posts() ) : ?>
<?php /* The loop */ ?>
<?php while ( $list_of_posts->have_posts() ) : $list_of_posts->the_post(); ?>
<?php // Display content of posts ?>
<?php get_template_part( 'content', get_post_format() ); ?>
<?php endwhile; ?>
<?php twentythirteen_paging_nav(); ?>
<?php else : ?>
<?php get_template_part( 'content', 'none' ); ?>
<?php endif; ?>
</div><!-- #content -->
</div><!-- #primary -->
<?php get_footer(); ?>

Categories