0

I am editing the archives template of my wordpress archive pages for specific post types and taxonomies only and I want to package it all in one plugin instead of adding it on my functions folder and adding all files inside my themes folder. Is there a way to do this on wordpress? I am not sure I looked in the documentation.

2 Answers 2

3

You should create a filter to the archive_template template hook.

function use_custom_template($tpl){
  if ( is_post_type_archive ( 'books' ) ) {
    $tpl = plugin_dir_path( __FILE__ ) . '/tpl/dir/books-archive.php';
  }
  return $tpl;
}

add_filter( 'archive_template', 'use_custom_template' ) ;
-1

It is an old question that I'm answering but I didn't found an ultimate solution on the web. Here is what I came up with:

<?php

namespace Itoll\Core\Includes\WooCommerce;

defined( 'ABSPATH' ) || die();

class WC_Templates {
    private $overwritten_templates = [
        'cart/cart.php',
        'cart/cart-shipping.php',
        'cart/proceed-to-checkout-button.php',
        'checkout/form-checkout.php',
        'checkout/form-coupon.php',
        'checkout/form-pay.php',
        'checkout/form-shipping.php',
        'checkout/payment.php',
        'checkout/payment-method.php',
        'checkout/review-order.php',
        'loop/orderby.php',
        'archive-product.php',
    ];

    public function __construct() {
        add_filter( 'template_include', [ $this, 'woocommerce_locate_template' ], 99, 1 );
    }

    public function woocommerce_locate_template( $template ) {
        // Get the template from this plugin, if it exists.
        preg_match( '/.*woocommerce\/(templates\/)?(.*)/', $template, $_path );
        $relative_path = $_path[2];
        if (
            in_array( $relative_path, $this->overwritten_templates )
             && file_exists( ITOLL_CORE_WC_TPL_DIR . $relative_path )
        ) {
            $template = ITOLL_CORE_WC_TPL_DIR . $relative_path;
        }

        return $template;
    }
}

In this way, I added the overwritten files in the /wp-content/plugins/my-custom-plugin/woocommerce/ and defined ITOLL_CORE_WC_TPL_DIR constant for it.

Using regex you can get the template path like what I wrote in the $overwritten_templates.

Just check if you overwrite the template and if so return the new path from your plugin.

If you don't know what ITOLL_CORE_WC_TPL_DIR exactly is:

trailingslashit( plugin_dir_path( __FILE__ ) . 'woocommerce' )

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.