Snippet load only one page? - wordpress

How to make that snippet using (Code Snippet in Wordpress) load only one page, because of home page and other pages loading time.
The code I'm using:
'''add_action( 'init', 'register_uzleteim_endpoint');
/**
* Register New Endpoint.
*
* #return void.
*/
function register_uzleteim_endpoint(){
add_rewrite_endpoint( 'uzleteim', EP_ROOT | EP_PAGES );
}
add_filter( 'query_vars', 'uzleteim_query_vars' );
/**
* Add new query var.
*
* #param array $vars vars.
*
* #return array An array of items.
*/
function uzleteim_query_vars( $vars ) {
$vars[] = 'uzleteim';
return $vars;
}
add_filter( 'woocommerce_account_menu_items', 'add_uzleteim_tab' );
/**
* Add New tab in my account page.
*
* #param array $items myaccount Items.
*
* #return array Items including New tab.
*/
function add_uzleteim_tab( $items ) {
$items['uzleteim'] = 'Üzleteim';
return $items;
}
add_action( 'woocommerce_account_uzleteim_endpoint', 'add_uzleteim_content' );
/**
* Add content to the new tab.
*
* #return string.
*/
function add_uzleteim_content() {}
I'm already tried something like this:
add_action( 'wp_footer', function () {
if ( ! is_page( array( 42, 'Page Name', 'about-us', 968 ) ) ) return;
// rest of snippet code here
} );
But it was not work, cause "unexpected if"

function custom_page() {
global $post;
if( $post->ID == 18) { ?>
<!-- do your stuff here -->
}
add_action( 'wp_footer', 'custom_page');

Related

Getting customer adress in custom shipping method

I'm currently working on a custom shipping method for WooCommerce. The goal is to calculate the shipping based on the adress the customer enters in the order process. We currently have an API that receives a storeId and the adress of a customer and returns back the exact amount of shipping we need to apply to the order.
For this, I've started to write a new custom shipping order plugin. I am already receiving the $packages array with the order, however I can't seem to find a way to receive the customers adress in the calculate_shipping method. There also will be a useraction required to select the prefered warehouse on the reviewOrderBeforePayment page and I am not quite sure how to access that data yet.
<?php
/*
* Plugin Name: Warehouses Integration
* Description: WooCommerce integration of the Warehouses API
* Version: 1.1.0
* Author: -
* Author URI: -
* Developer: Laura Heimann
* Developer URI: -
* Text Domain: woocommerce-extension
* WC requires at least: 4.0.1
* WC tested up to: 4.0.1
*/
// Security Measure
if (!defined('ABSPATH')) {
exit;
}
// Check if WooCommerce is installed
if (!in_array('woocommerce/woocommerce.php', apply_filters('active_plugins', get_option( 'active_plugins')))) {
alert("WooCommerce is not installed!");
}
// Main Render Function
// This will be hooked into the WooCommerce Order Page
function wcfw_render() {
// TODO: Show List of possible stores, let user select and save selected store somehow
echo "WCFWRENDER";
}
function wcfw_renderThankYou() {
echo "WCFWTHANKYOU";
}
function wcfw_renderReviewOrder() {
// TODO: Show warning if items from different stores
echo "WCFWREVIEWORDER";
}
function wcfw_shippingMethodInit() {
if ( ! class_exists( 'WC_WCFW_Shipping_Method' ) ) {
class WC_WCFW_Shipping_Method extends WC_Shipping_Method {
/**
* Constructor for your shipping class
*
* #access public
* #return void
*/
public function __construct() {
$this->id = 'wcfw_shipping_method';
$this->title = __( 'Warehouses Shipping' );
$this->method_description = __( 'Shipping Method through the Warehouse' );
$this->enabled = "yes";
$this->init();
}
/**
* Init your settings
*
* #access public
* #return void
*/
function init() {
// Load the settings API
$this->init_form_fields(); // This is part of the settings API. Override the method to add your own settings
$this->init_settings(); // This is part of the settings API. Loads settings you previously init.
// Save settings in admin if you have any defined
add_action( 'woocommerce_update_options_shipping_' . $this->id, array( $this, 'process_admin_options' ) );
}
/**
* Settings
*/
function init_form_fields() {
$this->form_fields = array(
'apiBase' => array(
'title' => __('Api Base'),
'type' => 'text',
'description' => __('The base URL for API-Calls.'),
'default' => __('---')
),
);
}
/**
* calculate_shipping function.
*
* #access public
* #param mixed $package
* #return void
*/
public function calculate_shipping( $package = array() ) {
var_dump( $package );
// TODO: Get Customers Adress and selected store
// TODO: Send data to API and apply provided shipping
$rate = array(
'label' => __('Shipping by Truck'),
'cost' => '10.99',
'calc_tax' => 'per_item'
);
// Register the rate
$this->add_rate( $rate );
}
}
}
}
function add_wcfw_shipping_method( $methods ) {
$methods[] = 'WC_WCFW_Shipping_Method';
return $methods;
}
// Hooks
add_action('woocommerce_review_order_before_payment', 'wcfw_render', 10);
add_action('woocommerce_thankyou', 'wcfw_renderThankYou', 10);
add_action('woocommerce_after_cart_contents', 'wcfw_renderReviewOrder', 10);
add_action('woocommerce_shipping_init', 'wcfw_shippingMethodInit');
add_filter('woocommerce_shipping_methods', 'add_wcfw_shipping_method');

Custom Shipping Method Recalculate

I am creating a woocommerce custom shipping method. Its working fine, but when I use the shipping calculator it doesn't refresh.
<?php
/**
* Plugin Name: Expresso Jundiaí for WooCommerce
* Plugin URI: https://valoremarketing.com.br
* Description: Adds Expresso Jundiaí shipping methods to your WooCommerce store.
* Author: Valore + NSC
* Author URI: https://valoremarketing.com.br
* Version: 1.0.0
* License: GPLv2 or later
*
*/
if (!defined('ABSPATH')) {
exit;
}
/*
* Check if WooCommerce is active
*/
if (in_array('woocommerce/woocommerce.php', apply_filters('active_plugins', get_option('active_plugins')))) {
function expresso_jundiai_shipping_method()
{
if (!class_exists('Expresso_Jundiai_Shipping_Method')) {
class Expresso_Jundiai_Shipping_Method extends WC_Shipping_Method
{
private $args = '';
/**
* Constructor
*
* #access public
* #return void
*/
public function __construct($instance_id = 0)
{
$this->id = 'expresso-jundiai';
$this->title = 'Expresso Jundiaí';
$this->instance_id = absint($instance_id);
$this->method_title = __('Expresso Jundiaí Entregas', 'expresso-jundiai');
$this->method_description = __('Entregas feitas por Expresso Jundiaí', 'expresso-jundiai');
/**
* Utilized to woocommerce to verify the supported features by the shipping method
*/
$this->supports = array(
'shipping-zones',
'instance-settings',
'instance-settings-modal',
'settings'
);
$this->init();
}
/**
* Init your settings
*
* #access public
* #return void
*/
public function init()
{
$this->init_form_fields();
$this->init_settings();
/// Actions.
add_action('woocommerce_update_options_shipping_' . $this->id, array($this, 'process_admin_options'));
}
/**
* Define settings field for this shipping
*
* To access the fields:
* $shipping_methods = WC()->shipping->get_shipping_methods();
* foreach ( $shipping_methods as $key => $shipping_method ) {
* $code = $shipping_method->settings->code;
* }
*
* #return void
*/
public function init_form_fields()
{...}
/**
* Get the args needed to make a post request to API target
*
* #param $package
* #return mixed
*/
private function get_request_args( $package )
{...}
/**
* This function is used to calculate the shipping cost.
* Within this function we can check for weights, dimensions and other parameters in package.
*
* #access public
* #param mixed $package
* #return void
*/
public function calculate_shipping( $package = array() )
{
$args = $this->get_request_args( $package );
$uri = $this->get_option( 'apiUri' );
$response = $this->request_to_api( $uri, $args );
if ($response !== NULL) {
$this->add_rate( array(
'id' => $this->id,
'label' => $this->title,
'package' => $package,
'cost' => $response->vlrFrete,
) );
}
}
/**
* Calculates the cubage of all products.
*
* #param $package
* #return float|int
*/
private function get_total_cubage( $package ) {
$total = 0;
foreach ( $package['contents'] as $item_id => $values )
{
$_product = $values['data'];
$height = (float) $_product->get_height();
$width = (float) $_product->get_width();
$length = (float) $_product->get_length();
$total += $height * $width * $length;
}
return ( ($total > 0) ? ( $total/1000000 ) : 0 );
}
/**
* #param $package
* #return int
*/
private function get_total_volumes( $package ) {
$total = 0;
foreach ( $package['contents'] as $item_id => $values ) {
$total += (int) $values['quantity'];
}
return $total;
}
/**
* Calculate the total wheight of all products of the order
* #param $package
* #return float|int
*/
private function get_order_total_weight( $package ) {
$total = 0;
foreach ( $package['contents'] as $item_id => $values )
{
$_product = $values['data'];
$_product_weight = (float) $_product->get_weight();
$total += $_product_weight * $values['quantity'];
}
$total = wc_get_weight( $total, 'kg' );
return $total;
}
/**
* #param $uri
* #param $args
* #return mixed|void
*/
private function request_to_api( $uri, $args )
{
$response = wp_remote_post( $uri, $args );
var_dump($args, $response);
if ( is_wp_error( $response ) || '200' != wp_remote_retrieve_response_code( $response )) {
return;
}
$body = json_decode( wp_remote_retrieve_body( $response ) );
if ( empty( $body ) )
return;
return $body;
}
}
}
}
add_action('woocommerce_shipping_init', 'expresso_jundiai_shipping_method');
/**
* Adds the name of class into shipping methods
*
* #param $methods
* #return array
*/
function add_expresso_jundiai_shipping_method($methods)
{
/**
* The key of the array $method must match the shipping method id
*/
$methods['expresso-jundiai'] = 'Expresso_Jundiai_Shipping_Method';
return $methods;
}
add_filter('woocommerce_shipping_methods', 'add_expresso_jundiai_shipping_method');
}
I need it to recalculate with the same rules when i use the shipping calculator in cart... when wordpress calls /?wc-ajax=update_shipping_method
I' trying two days... Please... help

How to use Widget on Wordpress

Now I'm developing a new WebSite using WordPress.
I don't know how to use widgets.
I tried to search on google so I found some answer.
Here is my code.
class WP_Widget_Home extends WP_Widget {
/**
* Sets up the widgets name etc
*/
public function __construct()
{
parent::__construct('id_widget_home',
__('(TrueLove) [PAGE] Home', 'TrueLove'),
array('description' => __('Intro page.', 'TrueLove')));
}
/**
* Outputs the content of the widget
*
* #param array $args
* #param array $instance
*/
public function widget( $args, $instance ) {
// outputs the content of the widget
echo "<h1>I like U!</h1>";
the_content();
}
...
function registerHomeWidgetFunc()
{
return register_widget("WP_Widget_Home");
}
add_action('widgets_init', 'registerHomeWidgetFunc');
I can insert (TrueLove) [Page] Home widget on WidgetPage('wp-admin/widgets.php').
That's all.
How can I use this?

Can't Change property value through a method in a WordPress plugin

I'm trying to check if WooCommerce is active or not, I created a property with with a default value of false, then I created a method to check if WooCommerce is active using is_plugin_active() and admin_init hook, if active the value of the property must be updated to true: here is the code:
class MyClass{
public $woo_active = false;
public function __construct(){
add_action( 'admin_init', array( $this, 'check_if_woo_active' ) );
}
// check if WooCommerce is active
public function check_if_woo_active(){
if( is_plugin_active( 'woocommerce/woocommerce.php' ) ){
$this->woo_active = true;
}
}
// is_woo_active()
public function is_woo_active(){
return $this->woo_active;
}
}
$var = new MyClass();
var_dump( $var->is_woo_active() );
the issue is that var_dump returns false even if WooCommerce is active, BUT, if I use var_dump inside the function check_if_woo_active(), it returns true.
Why the property value is not updated? thanks
Updated:
The Second Solution as #helgatheviking sugested works fine, also this works very well and short
class MyClass{
// check if WooCommerce is active
public function is_woo_active(){
include_once( ABSPATH . 'wp-admin/includes/plugin.php' );
if( is_plugin_active( 'woocommerce/woocommerce.php' ) ){
return true;
}else{
return false;
}
}
}
$var = new MyClass();
var_dump( $var->is_woo_active() );
If I had to guess, then $var = new MyClass(); is run before admin_init so the check_if_woo_active() isn't run.
Couple things you could do. First, I will usually launch my plugin on the woocommerce_loaded hook. That way I am 100% sure WooCommerce is running.
class MyClass{
protected static $instance = null;
/**
* Main MyClass Instance
*
* Ensures only one instance of MyClass is loaded or can be loaded.
*
* #static
* #see MyClass()
* #return MyClass - Main instance
* #since 0.1.0
*/
public static function instance() {
if ( ! isset( self::$instance ) && ! ( self::$instance instanceof MyClass ) ) {
self::$instance = new MyClass();
}
return self::$instance;
}
public function __construct(){
// Do what you want, WC is definitely active
}
}
/**
* Returns the main instance of class.
*
* #return MyClass
*/
function MyClass() {
return MyClass::instance();
}
// Launch the class if WooCommerce is loaded:
add_action( 'woocommerce_loaded', 'MyClass' );
You could also mimic what WooCommerce does with their premium plugins and check the option that stores the active plugins:
class MyClass{
private static $active_plugins;
public static function get_active_plugins() {
self::$active_plugins = (array) get_option( 'active_plugins', array() );
if ( is_multisite() ){
self::$active_plugins = array_merge( self::$active_plugins, get_site_option( 'active_sitewide_plugins', array() ) );
}
}
// check if WooCommerce is active
public static function check_if_woo_active() {
if ( ! self::$active_plugins ) self::get_active_plugins();
return in_array( 'woocommerce/woocommerce.php', self::$active_plugins ) || array_key_exists( 'woocommerce/woocommerce.php', self::$active_plugins );
}
}
var_dump( MyClass::check_if_woo_active() );

Wordpress - GD Star Rating - Set Rating after wp_insert_post

is it possbile to rate the new post (with admin account) after this?
$post_id = wp_insert_post( $my_post, $wp_error );
According to this post of the Wordpress support forum, what you should do is something like this:
function set_rating($post_id, $vote) { // $vote = 0..10
$admin = get_user_by('login', 'admin');
if ($admin !== false) {
$ip = $_SERVER['SERVER_ADDR'];
$ua = $_SERVER['HTTP_USER_AGENT'];
gdsrBlgDB::save_vote($post_id, $admin->ID, $ip, $ua, $vote);
}
return $admin;
}
You need to add a hook after that happens. First write a function and then this:
add_action('wp_insert_post', 'set_star_rating');
function set_star_rating() {
global $post;
$post = ...
}
There is also save_posts hook which happens while you're saving the post and is better documented.
This may be useful for doing some custom development based on GD Star Rating Plugin. Find my functions to 'save post like', to get 'like count for a post' and to 'check whether current user liked a post'. This is working for custom Post Types as well.
/**
* Function to save post like
* #param type $post_id
* #param type $user_id
*/
function save_post_like($post_id, $user_id) {
$ip = $_SERVER['SERVER_ADDR'];
$ua = $_SERVER['HTTP_USER_AGENT'];
if(has_user_liked_post($post_id) == 0)
gdsrBlgDB::save_vote_thumb($post_id, $user_id, $ip, $ua, 1);
}
/**
* Function to check if user like the post
* #global type $wpdb
* #global type $table_prefix
* #param type $post_id
* #return type
*/
function has_user_liked_post($post_id) {
global $wpdb, $table_prefix;
$userdata = wp_get_current_user();
$user_id = is_object($userdata) ? $userdata->ID : 0;
$sql = "SELECT * FROM " . $table_prefix . "gdsr_votes_log WHERE vote_type = 'artthumb' AND id = " . $post_id . " AND user_id = " . $user_id;
$results = $wpdb->get_row($sql, OBJECT);
if (count($results))
return 1;
else
return 0;
}
/**
* Function to get total Likes of a Post
* #global type $wpdb
* #global type $table_prefix
* #param type $post_id
* #return type
*/
function get_post_like_count($post_id) {
global $wpdb, $table_prefix;
$sql = "SELECT * FROM " . $table_prefix . "gdsr_data_article WHERE post_id = " . $post_id;
$results = $wpdb->get_row($sql, OBJECT);
if (count($results))
return $results->user_recc_plus;
else
return 0;
}

Resources