Woocommerce - overriding the template through a plugin - php

I have a question: is there a way to override WooCommerce's default template through a plugin the same way you'd do it with a theme?
I have this code:
Class WoocommerceOverride {
public function woocommerce_locate_template( $template, $template_name, $template_path ) {
$plugin_path = SPSL_PLUGIN_PATH;
global $woocommerce;
$_template = $template;
if ( ! $template_path ) $template_path = $woocommerce->template_url;
$plugin_path .= '/woocommerce/';
// Look within passed path within the theme - this is priority
$template = locate_template(
array(
$template_path . $template_name,
$template_name
)
);
// Modification: Get the template from this plugin, if it exists
if ( ! $template && file_exists( $plugin_path . $template_name ) )
$template = $plugin_path . $template_name;
// Use default template
if ( ! $template )
$template = $_template;
//echo $template."<br>";
// Return what we found
return $template;
}
}
add_filter( 'woocommerce_locate_template', array('WoocommerceOverride', 'woocommerce_locate_template'), 10, 3 );
The problem with this code is that it works only partially. On some parts it works, on other parts it does not. For example, I can't customize archive-product.php at all. Whatever I write in there, whether code or plain text, I just don't get any results.
I copied the exact same template files from my plugin folder into my theme folder and it works. However, as I need this as a plugin, I can't go the theme route.
Many thanks.

Using filters wc_get_template_part we can override default WooCommerce template part's.
Using filters woocommerce_locate_template we can override default WooCommerce template's.
Try below example code snippet.
<?php
/**
* Override default WooCommerce templates and template parts from plugin.
*
* E.g.
* Override template 'woocommerce/loop/result-count.php' with 'my-plugin/woocommerce/loop/result-count.php'.
* Override template part 'woocommerce/content-product.php' with 'my-plugin/woocommerce/content-product.php'.
*
* Note: We used folder name 'woocommerce' in plugin to override all woocommerce templates and template parts.
* You can change it as per your requirement.
*/
// Override Template Part's.
add_filter( 'wc_get_template_part', 'override_woocommerce_template_part', 10, 3 );
// Override Template's.
add_filter( 'woocommerce_locate_template', 'override_woocommerce_template', 10, 3 );
/**
* Template Part's
*
* #param string $template Default template file path.
* #param string $slug Template file slug.
* #param string $name Template file name.
* #return string Return the template part from plugin.
*/
function override_woocommerce_template_part( $template, $slug, $name ) {
// UNCOMMENT FOR #DEBUGGING
// echo '<pre>';
// echo 'template: ' . $template . '<br/>';
// echo 'slug: ' . $slug . '<br/>';
// echo 'name: ' . $name . '<br/>';
// echo '</pre>';
// Template directory.
// E.g. /wp-content/plugins/my-plugin/woocommerce/
$template_directory = untrailingslashit( plugin_dir_path( __FILE__ ) ) . 'woocommerce/';
if ( $name ) {
$path = $template_directory . "{$slug}-{$name}.php";
} else {
$path = $template_directory . "{$slug}.php";
}
return file_exists( $path ) ? $path : $template;
}
/**
* Template File
*
* #param string $template Default template file path.
* #param string $template_name Template file name.
* #param string $template_path Template file directory file path.
* #return string Return the template file from plugin.
*/
function override_woocommerce_template( $template, $template_name, $template_path ) {
// UNCOMMENT FOR #DEBUGGING
// echo '<pre>';
// echo 'template: ' . $template . '<br/>';
// echo 'template_name: ' . $template_name . '<br/>';
// echo 'template_path: ' . $template_path . '<br/>';
// echo '</pre>';
// Template directory.
// E.g. /wp-content/plugins/my-plugin/woocommerce/
$template_directory = untrailingslashit( plugin_dir_path( __FILE__ ) ) . 'woocommerce/';
$path = $template_directory . $template_name;
return file_exists( $path ) ? $path : $template;
}

Few months ago the i had the same requirements. So searched a bit more on the net and found useful code which helped me(with a little more customization as per my requirements).
For a detailed code with explanation check this and this link. The approach might be different than what you currently using but it results in overriding woocommerce templates in plugin

You should try adding this code before your // Use default template code:
if( $template_name == '{template part name}') {
$template = $plugin_path . $template_name;
}
In my case {template part name} was global/quantity-input.php
You can find out your exact template part names by temporary adding this line to your code:
print_r($template_name);
I know it's a bit late for answer here but maybe it will be useful for someone else. And keep in mind woocommerce_locate_template is depricated. So there is probably more 'up to date' solution somewhere out there.

Related

How to fix fatal PHP error on Wordpress login page?

I'm trying load my websites Wordpress page but get the error
Warning: require(__DIR__/wp-load.php) [function.require]: failed to open stream: No such file or directory in /home/content/39/4124639/html/wp-login.php on line 12
Fatal error: require() [function.require]: Failed opening required '__DIR__/wp-load.php' (include_path='.:/usr/local/php5/lib/php') in /home/content/39/4124639/html/wp-login.php on line 12
Inside the wp-login.php file on line 12 is: require __DIR__ . '/wp-load.php';
I confirmed the file wp-load.php is there. Can someone help?
I haven't changed my wp-blog-header.php file it is:
<?php
/**
* Loads the WordPress environment and template.
*
* #package WordPress
*/
if ( ! isset( $wp_did_header ) ) {
$wp_did_header = true;
// Load the WordPress library.
require_once __DIR__ . '/wp-load.php';
// Set up the WordPress query.
wp();
// Load the theme template.
require_once ABSPATH . WPINC . '/template-loader.php';
}
The wp-load.php file is (I haven't messed around with it either):
<?php
/**
* Bootstrap file for setting the ABSPATH constant
* and loading the wp-config.php file. The wp-config.php
* file will then load the wp-settings.php file, which
* will then set up the WordPress environment.
*
* If the wp-config.php file is not found then an error
* will be displayed asking the visitor to set up the
* wp-config.php file.
*
* Will also search for wp-config.php in WordPress' parent
* directory to allow the WordPress directory to remain
* untouched.
*
* #package WordPress
*/
/** Define ABSPATH as this file's directory */
if ( ! defined( 'ABSPATH' ) ) {
define( 'ABSPATH', __DIR__ . '/' );
}
error_reporting( E_CORE_ERROR | E_CORE_WARNING | E_COMPILE_ERROR | E_ERROR | E_WARNING | E_PARSE | E_USER_ERROR | E_USER_WARNING | E_RECOVERABLE_ERROR );
/*
* If wp-config.php exists in the WordPress root, or if it exists in the root and wp-settings.php
* doesn't, load wp-config.php. The secondary check for wp-settings.php has the added benefit
* of avoiding cases where the current directory is a nested installation, e.g. / is WordPress(a)
* and /blog/ is WordPress(b).
*
* If neither set of conditions is true, initiate loading the setup process.
*/
if ( file_exists( ABSPATH . 'wp-config.php' ) ) {
/** The config file resides in ABSPATH */
require_once ABSPATH . 'wp-config.php';
} elseif ( #file_exists( dirname( ABSPATH ) . '/wp-config.php' ) && ! #file_exists( dirname( ABSPATH ) . '/wp-settings.php' ) ) {
/** The config file resides one level above ABSPATH but is not part of another installation */
require_once dirname( ABSPATH ) . '/wp-config.php';
} else {
// A config file doesn't exist.
define( 'WPINC', 'wp-includes' );
require_once ABSPATH . WPINC . '/load.php';
// Standardize $_SERVER variables across setups.
wp_fix_server_vars();
require_once ABSPATH . WPINC . '/functions.php';
$path = wp_guess_url() . '/wp-admin/setup-config.php';
/*
* We're going to redirect to setup-config.php. While this shouldn't result
* in an infinite loop, that's a silly thing to assume, don't you think? If
* we're traveling in circles, our last-ditch effort is "Need more help?"
*/
if ( false === strpos( $_SERVER['REQUEST_URI'], 'setup-config' ) ) {
header( 'Location: ' . $path );
exit;
}
define( 'WP_CONTENT_DIR', ABSPATH . 'wp-content' );
require_once ABSPATH . WPINC . '/version.php';
wp_check_php_mysql_versions();
wp_load_translations_early();
// Die with an error message
$die = sprintf(
/* translators: %s: wp-config.php */
__( "There doesn't seem to be a %s file. I need this before we can get started." ),
'<code>wp-config.php</code>'
) . '</p>';
$die .= '<p>' . sprintf(
/* translators: %s: Documentation URL. */
__( "Need more help? <a href='%s'>We got it</a>." ),
__( 'https://wordpress.org/support/article/editing-wp-config-php/' )
) . '</p>';
$die .= '<p>' . sprintf(
/* translators: %s: wp-config.php */
__( "You can create a %s file through a web interface, but this doesn't work for all server setups. The safest way is to manually create the file." ),
'<code>wp-config.php</code>'
) . '</p>';
$die .= '<p>' . __( 'Create a Configuration File' ) . '';
wp_die( $die, __( 'WordPress › Error' ) );
}

wordpress get url of registered script

If I register a script or style (using wp_register_script() or wp_register_style()), is there a way I can get the URL of that script/style?
(If you must know why, I'm trying to put those URL's into another function that generates prefetch link tags so I can prefetch certain scripts/styles for a performance boost in my site.)
Just in case someone is still looking for this:
<?php
function invdr_get_script_uri_by_handler( $handler ){
//Get an instance of WP_Scripts or create new;
$wp_scripts = wp_scripts();
//Get the script by registered handler name
$script = $wp_scripts->registered[ $handler ];
if ( file_exists( ABSPATH . $script->src ) ){
return ABSPATH . $script->src;
}
return false;
}
add_action( 'wp_enqueue_scripts', 'invdr_get_script_uri_by_handler', PHP_INT_MAX );
Tested in wordpress 5.0
You can use wp_scripts() to get the instance of the WP_Scripts class which contains the registered scripts (this class extends WP_Dependencies).
Basically, try looking in:
$wp_scripts = wp_scripts();
var_dump( $wp_scripts->registered );
var_dump( $wp_scripts );
Here's how I've accomplished this in a self-authored plugin to help me enhance dependencies within WordPress:
// Convert relative URL to absolute?
$absolute = true;
$handle = 'your_stylesheet_handle';
$helper = wp_styles();
$object = $helper->registered[ $handle ];
$src = $object->src;
if (
$absolute
&& $helper->in_default_dir( $src )
) {
$src = $helper->base_url . $src;
}
$ver = $object->ver;
if ( ! is_null( $ver ) && empty( $ver ) ) {
$ver = $helper->default_version;
}
if ( isset( $helper->args[ $handle ] ) ) {
$ver = $ver ? $ver . '&' : '';
$ver .= $helper->args[ $handle ];
}
$src = add_query_arg( 'ver', $ver, $src );
$stylesheet_url = urldecode_deep( $src );
Note that the absolute URL conversion is directed towards handling assets registered by WordPress core, as they're typically relative URLs.

How to call thumbnail from image usign Types plugin in Wordpress

I am using Types plugin in Wordpress to create custom post type.
I have added custom filed "Image field" which is repeating field and in this way I want to create something like gallery in my post type
here is how I call the images in the front end
$images = get_post_meta(get_the_ID(), 'wpcf-application-image');
foreach ($images as $image) {
echo '<a rel="attachment" href="' . $image . '"><img src="' . $image . '" /></a>';
}
With that code I see the list with all images and link to the media file.
But how can I add a thumbnail instead of the exact image in the img tag?
Thank you!
If you only have the image url (not the id) then you can use a function like this to return the url (add it to functions.php etc):
/**
* Return an ID of an attachment by searching the database with the file URL.
*
* First checks to see if the $url is pointing to a file that exists in
* the wp-content directory. If so, then we search the database for a
* partial match consisting of the remaining path AFTER the wp-content
* directory. Finally, if a match is found the attachment ID will be
* returned.
*
* #param string $url The URL of the image (ex: http://example.com/wp-content/uploads/2013/05/test-image.jpg)
*
* #return int|null $attachment Returns an attachment ID, or null if no attachment is found
*/
function get_attachment_id_by_url( $url ) {
// Split the $url into two parts with the wp-content directory as the separator
$parsed_url = explode( parse_url( WP_CONTENT_URL, PHP_URL_PATH ), $url );
// Get the host of the current site and the host of the $url, ignoring www
$this_host = str_ireplace( 'www.', '', parse_url( home_url(), PHP_URL_HOST ) );
$file_host = str_ireplace( 'www.', '', parse_url( $url, PHP_URL_HOST ) );
// Return nothing if there aren't any $url parts or if the current host and $url host do not match
if ( ! isset( $parsed_url[1] ) || empty( $parsed_url[1] ) || ( $this_host != $file_host ) ) {
return;
}
// Now we're going to quickly search the DB for any attachment GUID with a partial path match
// Example: /uploads/2013/05/test-image.jpg
global $wpdb;
$attachment = $wpdb->get_col( $wpdb->prepare( "SELECT ID FROM {$wpdb->prefix}posts WHERE guid RLIKE %s;", $parsed_url[1] ) );
// Returns null if no attachment is found
if(isset($attachment[0])) {
return $attachment[0];
} else {
return null;
}
}
Then you can use that ID to display the thumbnail:
$images = get_post_meta(get_the_ID(), 'wpcf-application-image');
foreach ($images as $image) {
$image_id = get_attachment_id_by_url($image);
echo '<a rel="attachment" href="' . $image . '"><img src="' . wp_get_attachment_image_src($image_id,'thumbnail') . '" /></a>';
}
Hi Simon and thank you for your help!
I added the code you posted but the images doesn't show up and I had
<img src="Array">
but you showed the the right way I and modified my code and now its work!
here is what I have:
function get_attachment_id_from_src ($image_src) {
global $wpdb;
$query = "SELECT ID FROM {$wpdb->posts} WHERE guid='$image_src'";
$id = $wpdb->get_var($query);
return $id;
}
$images = get_post_meta(get_the_ID(), 'wpcf-application-image');
foreach ($images as $image) {
$image_src = get_attachment_id_from_src($image);
$image_thumb = wp_get_attachment_image ($image_src, 'medium');
echo '<a rel="attachment" href="' . $image . '">'. $image_thumb .'</a>';
}
Thanks again!

Enqueueing scripts if a file exists

I work with wordpress on my child theme.
My site is installed into mydomain.xx/install, but runs from mydomain.xx.
My functions.php works and looks like this:
<?php
/* Script in head */
function carica_scripts() {
/* Common scripts */
// insert scripts here, if some
/* Page-based script */
$pageId = get_the_ID();
$pageType = get_post_type();
$myBaseURL = get_stylesheet_directory_uri() . '/js/';
/* Page-type scripts */
if($pageType == "product") {
wp_enqueue_script('CondAll', $myBaseURL . 'CondAll.js', array('jquery'));
wp_enqueue_script('CondShipping', $myBaseURL . 'CondShipping.js', array('jquery'));
}
/* Page-id scripts */
if($pageId == "1") {
wp_enqueue_script('Cond1', $myBaseURL . 'Cond1.js', array('jquery'));
}
if($pageId == "294") {
wp_enqueue_script('Cond294', $myBaseURL . 'Cond294.js', array('jquery'));
}
if($pageId == "318") {
wp_enqueue_script('Cond318', $myBaseURL . 'Cond318.js', array('jquery'));
}
if($pageId == "232") {
wp_enqueue_script('Cond232', $myBaseURL . 'Cond232.js', array('jquery'));
}
/* END of page-based script */
}
add_action( 'wp_enqueue_scripts', 'carica_scripts' );
?>
What I want to achieve is avoiding all the ifs on $pageId, and to auto-enqueue jQuery script CodXXX.js on page id XXX if the relative file exists in the subdirectory /js/ of my child theme.
file_exists() expects an absolute path to a file rather than a URL.
Use get_stylesheet_directory() to get the path you need. Also get_the_ID() shouldn't be used outside of the loop.
Example:
/*
* Enqueue CondXXX.js on page XXX if file CondXXX.js exists
*/
function carica_scripts() {
global $post;
// Check we're on a page.
if ( ! is_page() ) {
return false;
}
// Build the filename to check.
$handle = 'Cond' . $post->ID;
$relpath = '/js/' . $handle . '.js';
// Get path + url to file.
$file_path = get_stylesheet_directory() . $relpath;
$file_url = get_stylesheet_directory_uri() . $relpath;
if ( file_exists( $file_path ) ) {
wp_enqueue_script( $handle, $file_url, array( 'jquery' ) );
}
}
add_action( 'wp_enqueue_scripts', 'carica_scripts' );
The answer given by Nathan Dawson does not work in my case, I had to do some workarounds. I ended up with the following code:
/* Load scripts in head */
function carica_scripts() {
/* Common scripts */
/* END of common scripts */
/* Page-based script */
$pageId = get_the_ID();
$pageType = get_post_type();
$handle = 'Cond' . $pageId;
$file = $handle .'.js';
$relPath = '/js/';
$styleSheet_path = get_stylesheet_directory();
$domain_base = 'mydomain.it/public_html/';
$start_pos = strpos ( $styleSheet_path, $domain_base) + strlen ($domain_base);
$basePath = substr ( $styleSheet_path, $start_pos); // I need everything after 'mydomain.it/public_html/'
$file_path = $basePath. $relPath . $file;
$enqueue_path = get_stylesheet_directory_uri() . $relPath;
$enqueue_file = $enqueue_path . $file;
/* if page-type is ... (product, in this case) */
if($pageType == "product") {
wp_enqueue_script('CondAll', $enqueue_path . 'CondAll.js', array('jquery'));
wp_enqueue_script('CondShipping', $enqueue_path . 'CondShipping.js', array('jquery'));
}
/* If page id is... (1, in this case - because page 1 is not product but I want CondAll here too) */
if($pageId == "1") {
wp_enqueue_script('CondAll', $enqueue_path . 'CondAll.js', array('jquery'));
}
/* auto load script CondXXX.js from subdir js/ if file exists */
if ( file_exists( $file_path ) ) {
wp_enqueue_script( $handle, $enqueue_file, array( 'jquery' ) );
}
/* END of page-based script */
}
add_action( 'wp_enqueue_scripts', 'carica_scripts' );
Now the the scripts load.

Wordpress - 'strpos() empty needle' and 'cannot modify header' warnings

Months ago, I have placed a 301 redirect rule in my .htaccess file to redirect all the www request to a non-www request.
The problem is two days ago, when I tried to access my example.net site using www.example.net I get the following warnings in the page and website is not loaded.
http://i.stack.imgur.com/nXBMF.png
Here are the corresponding lines:
1. Plugin.php Line 647 = if ( strpos( $file, $realdir ) === 0 ){
Full function:
/**
* Gets the basename of a plugin.
*
* This method extracts the name of a plugin from its filename.
*
* #since 1.5.0
*
* #param string $file The filename of plugin.
* #return string The name of a plugin.
*/
function plugin_basename( $file ) {
global $wp_plugin_paths;
foreach ( $wp_plugin_paths as $dir => $realdir ) {
if ( strpos( $file, $realdir ) === 0 ) { /** LINE 646 */
$file = $dir . substr( $file, strlen( $realdir ) );
}
}
$file = wp_normalize_path( $file );
$plugin_dir = wp_normalize_path( WP_PLUGIN_DIR );
$mu_plugin_dir = wp_normalize_path( WPMU_PLUGIN_DIR );
$file = preg_replace('#^' . preg_quote($plugin_dir, '#') . '/|^' . preg_quote($mu_plugin_dir, '#') . '/#','',$file); // get relative path from plugins dir
$file = trim($file, '/');
return $file;
}
2. Pluggable.php Line 1178 = header("Location: $location", true, $status);
Full file: http://pastebin.com/0zMJZxV0
I use WordPress only to write some articles. My PHP knowledge is very basic and limited only to locate errors.
Please help me figure out the problem with this. As I have read from the Codex FAQ, they say that empty strings may be a culprit for the pluggable.php error. But I have no idea how to locate it and I have attached the file for your reference.
Please provide your suggestions to avoid this error in the future. Thanks in advance.
3. EDIT - wp setting file: (the error line - include_once( $plugin ); )
// Load active plugins.
foreach ( wp_get_active_and_valid_plugins() as $plugin ) {
wp_register_plugin_realpath( $plugin );
include_once( $plugin );
}
unset( $plugin );
The issue with the header information has been discussed in here: Cannot modify header information error in Wordpress. Could you give this a try and see whether this solves this part of your problem?.
On the other issue:
try var_dump ($file) (for instance -- or echo $file ) to see what they actually contain.
Check your configuration path of plugins :
var_dump($wp_plugin_paths);
You've got an error because $realdir is empty.

Categories