I would like to have WooCommerce external/affiliate products open in a new tab. This would go for all aspects of a product: image, title, buy now button and archive pages(product category/tags). All I have been able to find is a way to change the "Buy Now" button but no other solutions to the other areas previously mentioned. Other solutions offer a the external link in all the right places(product image, title, buy now button, archive pages), but it can't open in a new tab.
I've tried a bunch of different codes, as mentioned above, all lead to partial solutions. I believe if these can be combined, it may work. But I haven't been successful.
add_action( 'template_redirect', 'redirect_external_products' );
function redirect_external_products() {
global $post;
if ( is_singular( 'product' ) && ! empty( $post ) && ( $product = wc_get_product( $post ) ) && $product->is_type( 'external' ) ) {
wp_redirect( $product->get_product_url() );
exit;
}
}
function custom_redirect() {
global $post;
if( is_single() ){
$external_link = get_post_meta( $post->ID, 'external_link', true );
if($external_link) {
echo "<script> window.open(".$external_link.", '_blank') </script>";
exit;
}
}
}
I would like all affiliate/external links to open in a new tab. This would include: product image, product title, buy now button, archive page listings(product category/tags).
All previous attempts will only open the Buy Now links in a new tab - but the image and title still direct to the single product page. The first code above from does the trick, but won't open in a new tab. My research tells me that when using the template_redirect function, link targeting is not possible.
remove the previous code and let's add this code in the theme's functions.php file.
add_filter( 'woocommerce_loop_product_link', 'filter_external_product_permalink', 10, 2 );
if ( ! function_exists( 'filter_external_product_permalink' ) ) {
/**
* Insert the external url for products in the loop.
*/
function filter_external_product_permalink( $the_permalink, $product ){
global $product;
if( $product->is_type( 'external' ) ) {
$external_link = $product->get_product_url();
return $external_link;
}
return $the_permalink;
}
}
if ( ! function_exists( 'woocommerce_template_loop_product_link_open' ) ) {
/**
* Insert the opening anchor tag for products in the loop.
*/
function woocommerce_template_loop_product_link_open() {
global $product;
$link = apply_filters( 'woocommerce_loop_product_link', get_the_permalink(), $product );
$link_target = $product->is_type( 'external' ) ? '_blank' : '_self';
echo '<a target="' . esc_attr( $link_target ).'" href="' . esc_url( $link ) . '" class="woocommerce-LoopProduct-link woocommerce-loop-product__link">';
}
}
add_filter( 'woocommerce_loop_add_to_cart_link', 'custom_external_add_product_link' , 10, 2 );
if ( ! function_exists( 'custom_external_add_product_link' ) ) {
function custom_external_add_product_link( $permalink ) {
global $product;
if ( $product->is_type( 'external' ) ) {
$permalink = sprintf( '<a rel="nofollow" href="%s" data-quantity="%s" data-product_id="%s" data-product_sku="%s" class="%s" target="_blank">%s</a>',
esc_url( $product->add_to_cart_url() ),
esc_attr( isset( $quantity ) ? $quantity : 1 ),
esc_attr( $product->id ),
esc_attr( $product->get_sku() ),
esc_attr( isset( $class ) ? $class : 'button product_type_external add_to_cart_button' ),
esc_html( $product->add_to_cart_text() )
);
}
return $permalink;
}
}
Related
First of all, I have no idea how old and / or deprecated (that's the word right?) this code is. My old developer (passed away) gave it to me well over two years ago, and now I am trying to make sense of it all.
Not being a programmer, I need help with two things, whereof the second part is the most important. When ALL products are removed from the checkout, redirect to the shop page.
This is the code I am using for adding qty and what not to the checkout.
add_filter( 'woocommerce_cart_item_name', 'jess_product_thumbnail_on_checkout_order_review', 20, 3 );
function jess_product_thumbnail_on_checkout_order_review( $product_name, $cart_item, $cart_item_key ) {
if ( is_checkout() ) {
$product = $cart_item['data'];
$thumbnail = $product->get_image(array(50, 50));
$image_html = '<div class="product-item-thumbnail">' . $thumbnail . '</div>';
$product_name_link = '' . $product_name . '';
$product_name = $image_html . $product_name_link;
}
return $product_name;
}
add_action( 'wp_footer', 'jess_product_image_css_checkout', 900 );
function jess_product_image_css_checkout(){
if (is_checkout()){ ?>
<style>
.product-item-thumbnail{float:left; padding-right:20px;}
.product-item-thumbnail img{margin:0!important;}
</style>
<?php
}}
add_filter('woocommerce_checkout_cart_item_quantity', 'jess_qty_change_remove_item_checkout_order_review', 1000, 3);
function jess_qty_change_remove_item_checkout_order_review( $quantity_html, $cart_item, $cart_item_key ) {
$_product = $cart_item['data'];
if ($_product->is_sold_individually()){
$product_quantity = sprintf('<input type="hidden" name="cart[%s][qty]" value="" />', $cart_item_key);
}else{
$product_quantity = woocommerce_quantity_input(
array(
'input_name' => "cart[{$cart_item_key}][qty]",
'input_value' => $cart_item['quantity'],
'max_value' => $_product->get_max_purchase_quantity(),
'min_value' => '1',
'class' => 'qtyinput',
'placeholder' => 'Qty',
'product_name' => $_product->get_name(),
),
$_product,
false
);
}
$cart = WC()->cart->get_cart();
foreach ($cart as $cart_key => $cart_value){
if ($cart_key == $cart_item_key){
$product_id = $cart_item['product_id'];
$_product = $cart_item['data'] ;
$remove_product = sprintf(
'Remove',
esc_url(wc_get_cart_remove_url($cart_key)),
__( 'Remove From My Order', 'woocommerce' ),
esc_attr( $product_id ),
esc_attr( $_product->get_sku() ),
esc_attr( $cart_item_key )
);
}}
return '<br><span class="product-quantity">' . sprintf( 'Qty: %s', $cart_item['quantity'] ) . ' / ' . $remove_product . '</span>'.$product_quantity.'';
}
add_action( 'wp_footer', 'refresh_checkout_on_quantity_change' );
function refresh_checkout_on_quantity_change() {
if (is_checkout()){ ?>
<script type="text/javascript">
<?php $admin_url = get_admin_url(); ?>
jQuery("form.checkout").on("change", "input.qty", function(){
var data = {
action: 'update_order_qty',
security: wc_checkout_params.update_order_review_nonce,
post_data: jQuery('form.checkout').serialize()
};
jQuery.post('<?php echo $admin_url; ?>' + 'admin-ajax.php', data, function(response){
jQuery('body').trigger('update_checkout');
});
});
</script>
<?php
}}
add_action( 'init', 'jess_load_ajax_checkout_qty_and_removal' );
function jess_load_ajax_checkout_qty_and_removal(){
if (!is_user_logged_in()){
add_action( 'wp_ajax_nopriv_update_order_qty', 'update_order_qty');
}else{
add_action( 'wp_ajax_update_order_qty', 'update_order_qty');
}}
function update_order_qty(){
$values = array();
parse_str($_POST['post_data'], $values);
$cart = $values['cart'];
foreach ($cart as $cart_key => $cart_value){
WC()->cart->set_quantity( $cart_key, $cart_value['qty'], false );
WC()->cart->calculate_totals();
woocommerce_cart_totals();
}
exit;
}
add_action( 'wp_footer', 'jess_remove_product_from_checkout_script' );
function jess_remove_product_from_checkout_script() { ?>
<script>
jQuery( function($){
if (typeof woocommerce_params === 'undefined')
return false;
console.log('defined');
$(document).on('click', 'tr.cart_item a.remove-product', function (e){
e.preventDefault();
var product_id = $(this).attr("data-product_id"),
cart_item_key = $(this).attr("data-cart_item_key"),
product_container = $(this).parents('.shop_table');
product_container.block({
message: null,
overlayCSS: {
cursor: 'none'
}
});
$.ajax({
type: 'POST',
dataType: 'json',
url: wc_checkout_params.ajax_url,
data: {
action: "product_remove",
product_id: product_id,
cart_item_key: cart_item_key
},
success: function (result) {
$('body').trigger('update_checkout');
console.log(result);
}
});
});
});
</script>
<?php
}
add_action('wp_ajax_product_remove', 'ajax_product_remove');
add_action('wp_ajax_nopriv_product_remove', 'ajax_product_remove');
function ajax_product_remove(){
ob_start();
foreach (WC()->cart->get_cart() as $cart_item_key => $cart_item) {
if($cart_item['product_id'] == $_POST['product_id'] && $cart_item_key == $_POST['cart_item_key'] ) {
WC()->cart->remove_cart_item($cart_item_key);
}
}
WC()->cart->calculate_totals();
WC()->cart->maybe_set_cart_cookies();
woocommerce_order_review();
$woocommerce_order_review = ob_get_clean();
}
Here is the modified code. I have added some comments where what is changed. This is tested on storefront theme and works.
//We need to load cart scripts
function checkout_woocommerce_scripts()
{
if ( is_checkout() ) wp_enqueue_script( 'wc-cart' );
}
add_action( 'wp_enqueue_scripts', 'checkout_woocommerce_scripts', 10 );
//When we remove all products from checkout will redirect to cart so we redirect to shop instead
//This also will work if we are on cart page and remove all products
add_action('template_redirect','redirect_cart_page');
function redirect_cart_page() {
if(is_cart() && WC()->cart->get_cart_contents_count() == 0 ):
wp_safe_redirect(wc_get_page_permalink( 'shop' ));
endif;
}
add_filter( 'woocommerce_cart_item_name', 'jess_product_thumbnail_on_checkout_order_review', 20, 3 );
function jess_product_thumbnail_on_checkout_order_review( $product_name, $cart_item, $cart_item_key ) {
if ( is_checkout() ) {
$product = $cart_item['data'];
$thumbnail = $product->get_image(array(50, 50));
$image_html = '<div class="product-item-thumbnail">' . $thumbnail . '</div>';
$product_name_link = '' . $product_name . '';
$product_name = $image_html . $product_name_link;
}
return $product_name;
}
add_action( 'wp_footer', 'jess_product_image_css_checkout', 900 );
function jess_product_image_css_checkout(){
if (is_checkout()){ ?>
<style>
.product-item-thumbnail{float:left; padding-right:20px;}
.product-item-thumbnail img{margin:0!important;}
</style>
<?php
}
}
//In this function all i did change is the class of the remove button from remove-product to product-remove
add_filter('woocommerce_checkout_cart_item_quantity', 'jess_qty_change_remove_item_checkout_order_review', 1000, 3);
function jess_qty_change_remove_item_checkout_order_review( $quantity_html, $cart_item, $cart_item_key ) {
$_product = $cart_item['data'];
if ($_product->is_sold_individually()){
$product_quantity = sprintf('<input type="hidden" name="cart[%s][qty]" value="" />', $cart_item_key);
}else{
$product_quantity = woocommerce_quantity_input(
array(
'input_name' => "cart[{$cart_item_key}][qty]",
'input_value' => $cart_item['quantity'],
'max_value' => $_product->get_max_purchase_quantity(),
'min_value' => '1',
'class' => 'qtyinput',
'placeholder' => 'Qty',
'product_name' => $_product->get_name(),
),
$_product,
false
);
}
$cart = WC()->cart->get_cart();
foreach ($cart as $cart_key => $cart_value){
if ($cart_key == $cart_item_key){
$product_id = $cart_item['product_id'];
$_product = $cart_item['data'] ;
$remove_product = sprintf(
'Remove',
esc_url(wc_get_cart_remove_url($cart_key)),
__( 'Remove From My Order', 'woocommerce' ),
esc_attr( $product_id ),
esc_attr( $_product->get_sku() ),
esc_attr( $cart_item_key )
);
}
}
return '<br><span class="product-quantity">' . sprintf( 'Qty: %s', $cart_item['quantity'] ) . ' / ' . $remove_product . '</span>'.$product_quantity.'';
}
// I have added wc_fragment_refresh to update your minicart when qty change.
add_action( 'wp_footer', 'refresh_checkout_on_quantity_change' );
function refresh_checkout_on_quantity_change() {
if (is_checkout()){ ?>
<script type="text/javascript">
<?php $admin_url = get_admin_url(); ?>
jQuery("form.checkout").on("change", "input.qty", function(){
var data = {
action: 'update_order_qty',
security: wc_checkout_params.update_order_review_nonce,
post_data: jQuery('form.checkout').serialize()
};
jQuery.post('<?php echo $admin_url; ?>' + 'admin-ajax.php', data, function(response){
jQuery('body').trigger( 'wc_fragment_refresh' );
jQuery('body').trigger('update_checkout');
});
});
</script>
<?php
}
}
// You dont need to wrap this in a function and do checks wp_ajax_nopriv runs for guests where wp_ajax runs for users
add_action( 'wp_ajax_nopriv_update_order_qty', 'update_order_qty');
add_action( 'wp_ajax_update_order_qty', 'update_order_qty');
function update_order_qty(){
$values = array();
parse_str($_POST['post_data'], $values);
$cart = $values['cart'];
foreach ($cart as $cart_key => $cart_value){
WC()->cart->set_quantity( $cart_key, $cart_value['qty'], false );
WC()->cart->calculate_totals();
woocommerce_cart_totals();
}
exit;
}
This is i think the better solution when we want to update cart items in checkout. Its all woocommerce core so it will perform and last longer than custom code for people who are not into coding.
Here is a video how its working https://webm.red/iV0t . It may get deleted after time.
//We need to load cart scripts
function checkout_woocommerce_scripts()
{
if ( is_checkout() ) wp_enqueue_script( 'wc-cart' );
}
add_action( 'wp_enqueue_scripts', 'checkout_woocommerce_scripts', 10 );
//If we want to redirect to shop page when cart or checkout get empty.
add_action('template_redirect','redirect_cart_page');
function redirect_cart_page() {
if(is_cart() && WC()->cart->get_cart_contents_count() == 0 ):
wp_safe_redirect(wc_get_page_permalink( 'shop' ));
endif;
}
//Load the cart form provided by woocommerce as shortcode.
// I will keep it outside the checkout form since its a form on its self.
// If we want we can extend the layout with modifying the checkout template.
add_action('woocommerce_before_checkout_form','checkout_cart_form');
function checkout_cart_form() {
echo do_shortcode('[woocommerce_cart]');
}
//Since we load cart form we dont need the coupon form twice
//Remove checkout coupon form comment this if you want to use this instead
remove_action( 'woocommerce_before_checkout_form', 'woocommerce_checkout_coupon_form', 10 );
//Remove cart coupon form
function hide_coupon_field_on_cart( $enabled ) {
if ( is_cart() ) { $enabled = false; } return $enabled;
}
//Uncomment this if you want to use this coupon form
// add_filter( 'woocommerce_coupons_enabled', 'hide_coupon_field_on_cart' );
//The scripts and styles we gonna use. Feel free to move them in your theme css js files (make sure they are loaded on checkout page)
add_action( 'wp_footer', 'checkout_styles_scripts');
function checkout_styles_scripts() {
?>
<style>
body.woocommerce-checkout button[name="update_cart"],
body.woocommerce-checkout input[name="update_cart"] {
display: none;
}
</style>
<script>
jQuery( function( $ ) {
let timeout;
$('.woocommerce').on( 'change keyup mouseup', 'input.qty', function(){
if ( timeout !== undefined ) {
clearTimeout( timeout );
}
timeout = setTimeout(function() {
$("[name='update_cart']").trigger("click"); // trigger cart update
}, 1000 ); // 1 second delay, half a second (500) seems comfortable too
});
} );
</script>
<?php
}
So I was looking for a way to update Pricing for a variable Product (Woocommerce + WP), without showing the Price Range + Final Price (including Variables).
I stumbled upon this script, which seems to work perfectly for my use case. Source - Stackoverflow
It works fine on mobile.
However, in Desktop Browser, it requires me to click on a random place of the page to update the pricing. This is very inconvenient.
Any idea how to fix this?
My coding skills are limited to HTML/CSS and very basic js.
Any help is appreciated.
This is the code:
add_action( 'woocommerce_before_single_product', 'check_if_variable_first' );
function check_if_variable_first(){
if ( is_product() ) {
global $post;
$product = wc_get_product( $post->ID );
if ( $product->is_type( 'variable' ) ) {
// removing the price of variable products
remove_action( 'woocommerce_single_product_summary', 'woocommerce_template_single_price', 10 );
// Change location of
add_action( 'woocommerce_single_product_summary', 'custom_wc_template_single_price', 10 );
function custom_wc_template_single_price(){
global $product;
// Variable product only
if($product->is_type('variable')):
// Main Price
$prices = array( $product->get_variation_price( 'min', true ), $product->get_variation_price( 'max', true ) );
$price = $prices[0] !== $prices[1] ? sprintf( __( 'From: %1$s', 'woocommerce' ), wc_price( $prices[0] ) ) : wc_price( $prices[0] );
// Sale Price
$prices = array( $product->get_variation_regular_price( 'min', true ), $product->get_variation_regular_price( 'max', true ) );
sort( $prices );
$saleprice = $prices[0] !== $prices[1] ? sprintf( __( 'From: %1$s', 'woocommerce' ), wc_price( $prices[0] ) ) : wc_price( $prices[0] );
if ( $price !== $saleprice && $product->is_on_sale() ) {
$price = '<del>' . $saleprice . $product->get_price_suffix() . '</del> <ins>' . $price . $product->get_price_suffix() . '</ins>';
}
?>
<style>
div.woocommerce-variation-price,
div.woocommerce-variation-availability,
div.hidden-variable-price {
height: 0px !important;
overflow:hidden;
position:relative;
line-height: 0px !important;
font-size: 0% !important;
}
</style>
<script>
jQuery(document).ready(function($) {
$('select').blur( function(){
if( '' != $('input.variation_id').val() ){
$('p.price').html($('div.woocommerce-variation-price > span.price').html()).append('<p class="availability">'+$('div.woocommerce-variation-availability').html()+'</p>');
console.log($('input.variation_id').val());
} else {
$('p.price').html($('div.hidden-variable-price').html());
if($('p.availability'))
$('p.availability').remove();
console.log('NULL');
}
});
});
</script>
<?php
echo '<p class="price">'.$price.'</p>
<div class="hidden-variable-price" >'.$price.'</div>';
endif;
}
}
}
}
LINK to Image for Usecase explanation - See also Stackoverflow Link where I took the code from
The problem which you are facing seems to be the $('select').blur().
As you want this to change automatically, I suggest changing this to change()..
<script>
jQuery(document).ready(function($) {
$('select').change( function(){
if( '' != $('input.variation_id').val() ){
$('p.price').html($('div.woocommerce-variation-price > span.price').html()).append('<p class="availability">'+$('div.woocommerce-variation-availability').html()+'</p>');
console.log($('input.variation_id').val());
} else {
$('p.price').html($('div.hidden-variable-price').html());
if($('p.availability'))
$('p.availability').remove();
console.log('NULL');
}
});
});
</script>
The blur() event occurs when an object loses focus.. In your case, when you click off the screen.
the change() event occurs when the object changes.. In your case, whenever the select option changes
The code above was flawed.
I found a better solution for my use case in this post: Update Woo Variable Price
I have woocommerce setup with products and variations on these products. When I change the variation (for example, the size of the product (340g or 900g), I want it to dynamically on the page update the price so the person can see what the price difference is between the two sizes. At the moment, I can't even get the variation ID of the variation. This does not seem to be working at all.
If I test and modify the variations, this is all I get from the Javascript console:
Here is my code:
// removing the price of variable products
remove_action( 'woocommerce_single_product_summary','woocommerce_template_single_price', 10 );
// Change location of
add_action( 'woocommerce_single_product_summary', 'custom_wc_template_single_price', 10 );
function custom_wc_template_single_price(){
global $product;
// Variable product only
if($product->is_type('variable')):
// Main Price
$prices = array( $product->get_variation_price( 'min', true ), $product->get_variation_price( 'max', true ) );
$price = $prices[0] !== $prices[1] ? sprintf( __( 'From: %1$s', 'woocommerce' ), wc_price( $prices[0] ) ) : wc_price( $prices[0] );
// Sale Price
$prices = array( $product->get_variation_regular_price( 'min', true ), $product->get_variation_regular_price( 'max', true ) );
sort( $prices );
$saleprice = $prices[0] !== $prices[1] ? sprintf( __( 'From: %1$s', 'woocommerce' ), wc_price( $prices[0] ) ) : wc_price( $prices[0] );
if ( $price !== $saleprice && $product->is_on_sale() ) {
$price = '<del>' . $saleprice . $product->get_price_suffix() . '</del> <ins>' . $price . $product->get_price_suffix() . '</ins>';
}
?>
<style>
div.woocommerce-variation-price,
div.woocommerce-variation-availability,
div.hidden-variable-price {
height: 0px !important;
overflow:hidden;
position:relative;
line-height: 0px !important;
font-size: 0% !important;
}
</style>
<script>
jQuery(document).ready(function($) {
$('select').blur( function(){
console.log("blur");
if( '' != $('input.variation_id').val() ){
console.log($('input.variation_id'));
console.log($('input.variation_id').val());
$('p.price').html($('div.woocommerce-variation-price > span.price').html()).append('<p class="availability">'+$('div.woocommerce-variation-availability').html()+'</p>');
console.log($('input.variation_id').val());
} else {
$('p.price').html($('div.hidden-variable-price').html());
if($('p.availability'))
$('p.availability').remove();
console.log('NULL');
}
});
});
</script>
<?php
echo '<p class="price">'.$price.'</p>
<div class="hidden-variable-price" >'.$price.'</div>';
endif;
}
Here is the site: https://bricksandmortar.ca/product/no-eye-contact/#
Any ideas?
You can hook into the show_variation trigger with some jQuery to get all of the information about the selected variation. Here's an example that will write the price formatted in HTML to the console.
(function( $ ) {
'use strict';
$(function() {
var $variation_form = $( '.variations_form' );
$variation_form.on( "show_variation", function ( event, variation ) {
// Fired when the user selects all the required attributes
console.log(variation.price_html);
} );
});
})( jQuery );
I am setting up GA o'clock tracking on my site and it works for must of the places where I inserted it. When I try to put it into the following code it breaks the site - how to integrate the code here correctly to track onclick events?
I used the following code snippet to integrate in the tags where I wanted to track:
onClick="ga('send', 'event', 'AmzClickout', 'PDPCta', '<?php echo esc_attr( $product->get_sku() ); ?>');"
However, if I try to put it in the code below it breaks.
<?php
/**
* Loop Add to Cart
*
* #author WooThemes
* #package WooCommerce/Templates
* #version 2.1.0
*/
if ( ! defined( 'ABSPATH' ) ) exit; // Exit if accessed directly
global $product;
echo apply_filters( 'woocommerce_loop_add_to_cart_link',
sprintf( '%s',
esc_url( $product->add_to_cart_url() ),
esc_attr( $product->id ),
esc_attr( $product->get_sku() ),
esc_attr( isset( $quantity ) ? $quantity : 1 ),
$product->is_purchasable() && $product->is_in_stock() ? 'add_to_cart_button' : '',
esc_attr( $product->product_type ),
esc_html( $product->add_to_cart_text() )
),
$product );
Thanks a lot upfront!
if ( ! defined( 'ABSPATH' ) ) exit; // Exit if accessed directly
global $product;
echo apply_filters( 'woocommerce_loop_add_to_cart_link',
sprintf( '%s',
esc_url( $product->add_to_cart_url() ),
esc_attr( $product->id ),
esc_attr( $product->get_sku() ),
esc_attr( isset( $quantity ) ? $quantity : 1 ),
$product->is_purchasable() && $product->is_in_stock() ? 'add_to_cart_button' : '',
esc_attr( $product->product_type ),
esc_html( $product->add_to_cart_text() )
),
$product );
Firstly, I know this is 'bad' practice for several different reasons, but for reasons that I won't waste your time with it's something I need to do.
Using a fairly simple plugin and I've tried copying it into functions.php and updating the file paths and dependences, but I'm having some trouble.
Plugin.php file looks like this:-
$plugin_headers = get_file_data( __FILE__, array( 'Version' => 'Version', 'Name' => 'Plugin Name' ) );
/**
* We store our plugin data in the following global array.
* $my_unique_name with your unique name
*/
global $my_unique_name;
$my_unique_name = array();
$my_unique_name['version_key'] = strtolower( str_replace( ' ', '_', $plugin_headers['Name'] ) ) . '_version';
$my_unique_name['version_value'] = $plugin_headers['Version'];
/**
* When the user activates the plugin we add the version number to the
* options table as "my_plugin_name_version" only if this is a newer version.
*/
function inline_comments_acitvation(){
global $my_unique_name;
if ( get_option( $my_unique_name['version_key'] ) && get_option( $my_unique_name['version_key'] ) > $my_unique_name['version_value'] )
return;
update_option( $my_unique_name['version_key'], $my_unique_name['version_value'] );
}
register_activation_hook( __FILE__, 'inline_comments_acitvation' );
/**
* Delete our version number from the database when the plugin is activated.
*/
function inline_comments_deactivate(){
global $my_unique_name;
delete_option( $my_unique_name['version_key'] );
}
register_deactivation_hook( __FILE__, 'inline_comments_deactivate' );
if ( is_admin() )
require_once plugin_dir_path( __FILE__ ) . 'admin/admin-tags.php';
/**
* Theme only functions
*/
require_once plugin_dir_path( __FILE__ ) . 'inc/template-tags.php';
function inline_comments_enqueue_scripts(){
$plugin_headers = get_file_data( __FILE__, array( 'Version' => 'Version', 'Name' => 'Original Plugin Name' ) );
$clean_name = strtolower( str_replace( ' ', '-', $plugin_headers['Name'] ) );
wp_register_style( $clean_name . '-style', plugin_dir_url( __FILE__ ) . 'inc/css/style.css' );
wp_register_script( 'textarea_auto_expand-script', plugin_dir_url( __FILE__ ) . 'vendor/textarea-auto-expand/jquery.textarea_auto_expand.js' );
wp_register_script( $clean_name . '-script', plugin_dir_url( __FILE__ ) . 'inc/js/script.js', array('jquery', 'textarea_auto_expand-script') );
}
add_action('wp_enqueue_scripts', 'inline_comments_enqueue_scripts', 2);
After moving the plugin to the theme folder I've done the following: I've removed the pointless parts and in my functions.php I'm loading the main script.js (it loads) and the css, like so(ie. changed the structure and moved the scripts into relevant folders).
function inline_comments_enqueue_scripts(){
if ( is_singular() || is_page() ) {
wp_enqueue_style( 'inline-style', get_template_directory_uri() . '/css/inline-style.css', '10000', 'all' );
wp_enqueue_script( 'inline-script', get_template_directory_uri() . '/js/inline-script.js', array( 'jquery' ), MEDIUM_VERSION);
}
}
add_action('wp_enqueue_scripts', 'inline_comments_enqueue_scripts', 2);
Ok so this loads the scripts just fine.
The plugin's main template file with the functions and ajax calls is in template-tags.php, but I can't figure out how to get this to load up correctly.
require_once plugin_dir_path( __FILE__ ) . 'inc/template-tags.php';
I've tried copy/pasting this into functions.php and it doesn't seem to work either.
The template-tags.php:
<?php
/**
* #todo Ajax crawling support -- https://developers.google.com/webmasters/ajax-crawling/docs/getting-started
* #todo https://developers.google.com/webmasters/ajax-crawling/
*/
/**
* Perform the following actions/filters when plugins are loaded
*
* #since 0.1-alpha
*/
function inline_comments_loaded(){
add_action( 'wp_ajax_inline_comments_add_comment', 'inline_comments_add_comment' );
add_action( 'wp_ajax_nopriv_inline_comments_add_comment', 'inline_comments_add_comment' );
add_action( 'wp_ajax_nopriv_inline_comments_load_template', 'inline_comments_load_template' );
add_action( 'wp_ajax_inline_comments_load_template', 'inline_comments_load_template' );
add_filter( 'template_redirect', 'inline_comments_template_redirect' );
}
add_action('plugins_loaded', 'inline_comments_loaded');
/**
* Load our JavaScript and Stylesheet on single page only
*
* #since 0.1-alpha
*/
function inline_comments_template_redirect() {
if ( is_singular() || is_page() ) {
add_action( 'wp_enqueue_scripts', 'inline_comments_scripts');
add_action( 'wp_head', 'inline_comments_head');
}
}
/**
* Load our JavaScript and Stylesheet, we include the login-register script only if it is installed.
*
* #uses wp_enqueue_script()
* #uses wp_enqueue_style()
*
* #since 0.1-alpha
*/
function inline_comments_scripts(){
wp_enqueue_script( 'inline-ajax-comments-script' );
wp_enqueue_style( 'inline-ajax-comments-style' );
}
/**
* Print our AJAX URL
*
* #since 0.1-alpha
*/
function inline_comments_head(){
print '<script type="text/javascript"> var ajaxurl = "'. admin_url("admin-ajax.php") .'";</script>';
print '<style type="text/css">'.get_option('additional_styling').'</style>';
}
/**
* Inserts a comment for the current post if the user is logged in.
*
* #since 0.1-alpha
* #uses check_ajax_referer()
* #uses is_user_logged_in()
* #uses wp_insert_comment()
* #uses wp_get_current_user()
* #uses current_time()
* #uses wp_kses()
* #uses get_option()
*/
function inline_comments_add_comment(){
check_ajax_referer('inline_comments_nonce', 'security');
$comment = trim(
wp_kses( $_POST['comment'],
array(
'a' => array(
'href' => array(),
'title' => array()
),
'br' => array(),
'em' => array(),
'strong' => array(),
'blockquote' => array(),
'code' => array()
)
)
);
if ( empty( $comment ) ) die();
if ( get_option('comment_registration') == 1 && ! is_user_logged_in() ) die();
$data = array(
'comment_post_ID' => (int)$_POST['post_id'],
'comment_content' => $comment,
'comment_type' => '',
'comment_parent' => 0,
'comment_author_IP' => $_SERVER['REMOTE_ADDR'],
'comment_agent' => $_SERVER['HTTP_USER_AGENT'],
'comment_date' => current_time('mysql'),
'comment_approved' => 1
);
if ( is_user_logged_in() ){
$current_user = wp_get_current_user();
$author_email = $current_user->user_email;
$author_url = $current_user->user_url;
$author_name = $current_user->user_nicename;
$data['user_id'] = $current_user->ID;
} else {
$author_email = empty( $_POST['user_email'] ) ? null : esc_attr( $_POST['user_email'] );
$author_url = empty( $_POST['user_url'] ) ? null : esc_url( $_POST['user_url'], array('http','https') );
$author_name = empty( $_POST['user_name'] ) ? null : esc_attr( $_POST['user_name'] );
}
$data['comment_author'] = $author_name;
$data['comment_author_email'] = $author_email;
$data['comment_author_url'] = $author_url;
// ck - catch the new comment id for updating comment meta
$comment_id = wp_insert_comment( $data );
// ck - now add the para-id to the comment meta
add_comment_meta( $comment_id, 'para_id' , $_POST['para_id'] );
die();
}
/**
* Load comments and comment form
*
* #since 0.1-alpha
*/
function inline_comments_load_template(){
check_ajax_referer('inline_comments_nonce', 'security');
$comments = get_comments( array(
'post_id' => (int)$_POST['post_id'],
'number' => 100,
'status' => 'approve',
'order' => 'ASC'
) );
?>
<div class="inline-comments-container" id="comments_target">
<?php if ( $comments ) : foreach( $comments as $comment) : ?>
<?php
// ck get the paragraph id from the comment meta
$para_id = get_comment_meta( $comment->comment_ID, 'para_id', true );
$user = new WP_User( $comment->user_id );
$class = null;
if ( ! empty( $user->roles ) && is_array( $user->roles ) ) {
foreach ( $user->roles as $role ){
$class = $role;
}
} else {
$class = 'annon';
}
// ck -added data-comment-para-id to div
?>
<div class="orphan-comment comment-para-id-<?php echo $para_id ?> inline-comments-content inline-comments-<?php echo $class; ?>" id="comment-<?php echo $comment->comment_ID; ?>">
<div class="inline-comments-p">
<?php inline_comments_profile_pic( $comment->comment_author_email ); ?>
<?php print $comment->comment_content; ?><br />
<time class="meta">
<strong><?php $user = get_user_by('login', $comment->comment_author ); if ( ! empty( $user->user_url ) ) : ?><?php print $comment->comment_author; ?><?php else : ?><?php print $comment->comment_author; ?><?php endif; ?></strong>
<?php print human_time_diff( strtotime( $comment->comment_date ), current_time('timestamp') ); ?> ago.
</time>
</div>
</div>
<?php endforeach; endif; ?>
</div>
<?php die();
}
/**
* Determine the profile pic for a user, either the FB pic or
* the gravatar pic. If no ID is passed uses the current logged
* in user.
*
* #uses get_user_meta()
* #uses get_avatar();
*/
function inline_comments_profile_pic( $id_or_email=null, $email=null ){
if ( is_null( $id_or_email ) ) {
global $current_user;
get_currentuserinfo();
$id_or_email = $current_user->ID;
}
$html = get_avatar( $id_or_email, 32 );
print '<span class="inline-comments-profile-pic-container">' . $html . '</span>';
}
function inline_comments_tempalte( $file ){
return plugin_dir_path( dirname( __FILE__ ) ) . 'templates/comments.php';
}
add_filter('comments_template', 'inline_comments_tempalte');
I notice that you've moved the /css and /js directories out of /inc where they seem to have been originally.
So try:
require_once plugin_dir_path( __FILE__ ) . 'template-tags.php';