Proper way to make function calls in WordPress - php

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

Related

WordPress change search results

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

Enabling Wordpress Events Plus Plugin shortcodes in custom template

I've recently purchased the events plus Wordpress plugin from http://wpeventsplus.com/ and am trying to get the calendar to show up on a template page. However, the shortcode [PLUS_CALENDAR] is not working on the template page I wrote. Here's my entire code for that page:
<?php
/*
Template Name: page-registration
*/
?>
<?php get_header(); ?>
<?php if ( have_posts() ) {
while ( have_posts() ) {
the_post();
//
// Post Content here
//
} // end while
} // end if
?>
<?php get_footer(); ?>
My background is in HTML and CSS, and I'm not familiar with php much at all. I should also mention that my site is WP Theme converted from a normal HTML site, making it a little harder to work with plugins, as the code was not converted in a very clean way to php. I'm guessing I have a mistake, or a few, in my code, but I have no idea where to start looking, I'd appreciate any help. Thanks.
You can execute a shortcode in a WordPress PHP file this way:
<?php echo do_shortcode('[PLUS_CALENDAR]'); ?>
Details: https://developer.wordpress.org/reference/functions/do_shortcode/
So your code becomes:
<?php
/*
Template Name: page-registration
*/
?>
<?php get_header(); ?>
<?php if ( have_posts() ) {
while ( have_posts() ) {
the_post();
//
// Post Content here
echo do_shortcode('[PLUS_CALENDAR]');
//
} // end while
} // end if
?>
<?php get_footer(); ?>

wordpress: is_front_page() for static page not working

I know this question is already asked a lot, but every time I read an answer on those questions it looks like I've implemented it like I should've. My problem is as follows:
I have added the following statement to my index.php to load a different header (saved in header-frontpage.php) for my static home page (called page-home.php).
if(is_front_page())
{
get_header('frontpage');
}
else
{
get_header();
}
I have also set page-home as my static front page in the wordpress settings->read.
Shouldn't this result in my homepage loading the header-frontpage.php? Now it just retreives my header.php for my frontpage as well. A live preview can be found at www.koencuijpers.com (wrong loading of header.php) and www.koencuijpers.com/spot-map (right loading of header.php).
My complete code for my index.php is:
<?php
/**
* The main template file.
*
* This is the most generic template file in a WordPress theme
* and one of the two required files for a theme (the other being style.css).
* It is used to display a page when nothing more specific matches a query.
* E.g., it puts together the home page when no home.php file exists.
*
* #link https://codex.wordpress.org/Template_Hierarchy
*
* #package Spot_Utrecht
*/
if(is_front_page())
{
get_header('frontpage');
}
else
{
get_header();
}
?>
<div id="primary" class="content-area">
<main id="main" class="site-main" role="main">
<?php
if ( have_posts() ) :
if ( is_home() && ! is_front_page() ) : ?>
<header>
<h1 class="page-title screen-reader-text"><?php single_post_title(); ?></h1>
</header>
<?php
endif;
/* Start the Loop */
while ( have_posts() ) : the_post();
/*
* Include the Post-Format-specific template for the content.
* If you want to override this in a child theme, then include a file
* called content-___.php (where ___ is the Post Format name) and that will be used instead.
*/
get_template_part( 'template-parts/content', get_post_format() );
endwhile;
the_posts_navigation();
else :
get_template_part( 'template-parts/content', 'none' );
endif; ?>
</main><!-- #main -->
</div><!-- #primary -->
<?php
get_sidebar();
get_footer();
?>
If you've set your homepage as a static page, then WordPress will be following its template hierarchy to decide what template to use:
https://developer.wordpress.org/themes/basics/template-hierarchy/#front-page-display
This means WordPress will not be using index.php as the template for your front page, so whatever changes you make there will have no effect.
Therefore you need to include your if statement in the appropriate template (probably front-page.php, depending on your theme setup).

Hook pages by id on static front-page

I would like to build a one page website upon the Wordpress CMS. I'm looking for a way too hook my pages on a static frontpage by id, since I have several page types.
I've tried:
$id=6;
$post = get_post($id);
$content = apply_filters('the_content', $post->post_content);
echo $content;
But this returns only the content and not the content with the HTML. Any tips on how to achieve this? or other ways to build a one-page website upon Wordpress?
Thanks in advance
To output the HTML properly, try using PHP's HTML entity encoding/decoding related functions to convert entities back to their applicable characters (e.g. < and >).
WordPress has an internal function called wpautop that converts double linefeeds (\n) into paragraph splits. wp_texturize (or something similarly named) converts some characters to proper variants, such as quote marks and similar.
Try this:
$content = apply_filters( 'the_content', wpautop( wp_texturize( html_entity_decode( $post -> post_content ) ) ) );
// Note: not properly tested, but should probably output properly "HTMLized" contents.
If you want to output something else than the HTML tags that are inside the post contents (and inserted using the post editor in wp-admin), you'll have to work with the theme templates.
EDIT:
To insert whole templates into the homepage to create a single-page website, you'll need to create each "page" as a template file. Assuming you have front-page.php, content-about.php, content-portfolio.php and so on. Additionally you most probably have header.php and footer.php.
In simplified form, each of the content templates that would be inserted to front-end.php could look something like this:
<?php
/**
* content-about.php
*/
// Get the wanted content as WP Post.
$page_obj = get_page_by_title( 'About' );
$page_content = wpautop( $page_obj -> post_content );
?>
<article id="about"> <!-- Begin a new section for the one-page template. -->
<h2><?php echo $page_obj -> post_title; ?></h2>
<?php echo $page_content; ?>
</article>
Additional templates (content-portfolio.php, content-contact.php and so on) should follow a similar structure.
Then in front-page.php you need to include your header.php and footer.php as you normally would. Then inbetween use get_template_part calls to fetch and display the content-abc.php templates within front-page.php:
<?php
/**
* front-page.php
*/
get_header(); ?>
<!-- Add some markup if you want to. -->
<?php get_template_part( 'content', 'about' ); // 'content-about.php' ?>
<?php get_template_part( 'content', 'portfolio' ); // 'content-portfolio.php' ?>
<?php get_template_part( 'awesometemplate' ); // 'awesometemplate.php' ?>
<!-- Add some markup if you want to. -->
<?php get_footer();
Now after WordPress and PHP parse the front-page.php template, the resulting output might look like this (depending on what you insert into each included template):
<!DOCTYPE html>
<html>
<head>
...
</head>
<body>
<!-- header.php visible contents here -->
<!-- content-about.php: -->
<article id="about">
<h2>About</h2>
<p>Well hello there! This is some <em>nice</em> content from content-about.php.</p>
</article>
<!-- content-portfolio.php: -->
<article id="portfolio">
<h2>Portfolio</h2>
<ul>
<li>
...
</li>
</ul>
</article>
<!-- awesometemplate.php: -->
<article id="awesome">
<h2>Awesome!</h2>
<table>
...
</table>
</article>
<!-- footer.php visible contents here -->
</body>
</html>
Now you've got separated templates that hold content and are embedded into front-page.php to create a single-page master template. The it's up to you to use CSS and JS to make it flashy if you want to.
Note: you can also use PHP's very own include or require functions to insert the sub-templates to front-page.php.
You can also use WP_Query to construct a custom query. You can use the Post and Page parameters to call your pages you need to display on your front page.
Inside the loop you'll have the ability to directly work with the template tags like the_content. You can also load template tags and HTML structures conditionally inside the loop on a per page basis with the use of is_page() or is_page_template()
Here is an example from the codec. Modify to suite your needs
$the_query = new WP_Query( array( 'post_type' => 'post', 'post__not_in' => array( 2, 5, 12, 14, 20 ) ) );
// The Query
$the_query = new WP_Query( $args );
// The Loop
if ( $the_query->have_posts() ) {
while ( $the_query->have_posts() ) {
$the_query->the_post();
the_content();
}
} else {
// no posts found
}
/* Restore original Post Data */
wp_reset_postdata();

Custom Pages with Wordpress 3.4.1

I am having some problems trying to get a custom page to display on my site. What I want is to create a page where the client can edit the content in Wordpress. When I add the page using the Wordpress "add new page" it doesn't show, but if I create a page in .php with the same content, it works fine. This is what I did:
First I created a blank .php template called lefthome.php using the following code:
<?php
/*
Template Name: Left Template
*/
?>
<?php get_template_part( 'loop', 'page' ); ?>
I then went into Wordpress, clicked on pages > add new. I gave my page a title and added the content I wanted to appear on the page. Then from the template option in the page attributes I choose the template I had earlier created (Left Template) and clicked update.
I wanted this template to appear on the homepage, so I tried to add it to the homepage template I had created using the following code:
<?php
/*
Template Name: Home
*/
get_header(); ?>
<?php include (TEMPLATEPATH . '/slider.php'); ?>
<div id="content">
<?php include (TEMPLATEPATH . '/lefthome.php'); ?>
</div>
<?php get_template_part( 'loop', 'page' ); ?>
<?php get_footer(); ?>
The header, slider.php and footer all show fine. The contents of the lefthome.php do not appear. I do not know how to get it to show. The only way I have got it to show is to paste the contents into the lefthome.php template. I don't want to do this though, as the client will not be able to edit the contents themselves.
I hope someone can help me.
Thanks
You won't be able to display the content of a page just by calling directly its template file. You need to query the page itself. In that matter it won't matter what template you've already assigned to it anymore.
<?php
/*
Template Name: Home
*/
get_header(); ?>
<?php include (TEMPLATEPATH . '/slider.php'); ?>
<div id="content">
<?php
global $post;
$page_id =5; // 5 is the id of the page we want to present with Left Template.
$post = get_post( $page_id );
setup_postdata( $post );
include locate_template( 'lefthome.php' );
wp_reset_postdata(); // we are done with that. reset the query so the rest don't mess up
?>
</div>
<?php get_template_part( 'loop', 'page' ); ?>
<?php get_footer(); ?>

Categories