Condition types for addAttributeToFilter in Magento2 Collections

'eq'            => "{{column}} = ?",
'finset'        => "FIND_IN_SET(?, {{column}})",
'from'          => "{{column}} >= ?",
'gt'            => "{{column}} > ?",
'gteq'          => "{{column}} >= ?",
'in'            => "{{column}} IN(?)",
'is'            => "{{column}} IS ?",
'like'          => "{{column}} LIKE ?",
'lt'            => "{{column}} < ?",
'lteq'          => "{{column}} <= ?",
'neq'           => "{{column}} != ?",
'nin'           => "{{column}} NOT IN(?)",
'nlike'         => "{{column}} NOT LIKE ?",
'notnull'       => "{{column}} IS NOT NULL",
'ntoa'          => "INET_NTOA({{column}}) LIKE ?",
'null'          => "{{column}} IS NULL",
'regexp'        => "{{column}} REGEXP ?",
'seq'           => null,
'sneq'          => null,
'to'            => "{{column}} <= ?"

How to fix Invalid template file error in Magento2 after version upgrade?

This is a very common issue you will face if you using windows machine for development.

Usual error message is:

Invalid template file: '/vendor/magento/module-theme/view/frontend/templates/page/js/require_js.phtml' in module: '' block's name: 'require.js'

So whats the solution?

In case of windows, just replace this function isPathInDirectories in vendor/magento/framework/view/element/template/file/validator.php

protected function isPathInDirectories($path, $directories)
{
    $realPath = str_replace('\\', '/', $this->fileDriver->getRealPath($path));
    if (!is_array($directories)) {
        $directories = (array)$directories;
    }

    foreach ($directories as $directory) {
        if (0 === strpos($realPath, $directory)) {
            return true;
        }
    }
    return false;
}

Reference:

https://magento.stackexchange.com/a/255585/32283

Fixing broken “screen options” in wordpress site

SELECT * from wp_usermeta where `meta_key` like 'edit_%_per_page'

So probably you chose “Number of items per page” as 1000 or 200 and now the page doesnt load anymore because your database ran out of memory.

If that is the case, run the above query on phpmysql or any other way, edit the numbers and fixed!

How to limit ajax apis for your origins (Access-Control-Allow-Origin headers)

$allowed_domains = ["https://www.YOURDOMAIN.com","https://YOURDOMAIN.com","https://staging.YOURDOMAIN.com","https://www.YOURDOMAIN.com/","https://YOURDOMAIN.com/","https://staging.YOURDOMAIN.com/"];
// echo $_SERVER['HTTP_ORIGIN'];
if (in_array($_SERVER['HTTP_ORIGIN'], $allowed_domains)) {
    header('Access-Control-Allow-Origin: ' . $_SERVER['HTTP_ORIGIN']);
}
else{
    if(in_array($_SERVER['HTTP_REFERER'], $allowed_domains)){
        header('Access-Control-Allow-Origin: ' . $_SERVER['HTTP_REFERER']);
    }
}

Sample .htaccess for Laravel with PHP FPM

SetEnvIf Authorization "(.*)" HTTP_AUTHORIZATION=$1

#    RewriteEngine On
#    RewriteCond %{HTTP:Authorization} ^(Bearer\ )(.*)$ [NC]
#    RewriteRule ^(.*) $1?access_token=%2 [QSA]
#Header set Access-Control-Allow-Origin "*"
#Header set Access-Control-Allow-Methods "GET,PUT,POST,DELETE"
#Header set Access-Control-Allow-Headers "Content-Type, Authorization"
<IfModule mod_rewrite.c>

<IfModule mod_negotiation.c>
Options -MultiViews
</IfModule>
RewriteEngine On
RewriteCond %{SERVER_PORT} 80
RewriteRule ^(.*)$ https://kprep.api.ozandac.com/$1 [R,L]
RewriteEngine On
# Prevent direct access to the "public" folder - redirect to root
RewriteCond %{THE_REQUEST} ^[A-Z]{3,9}\ /public/
RewriteRule ^public/(.*) /$1 [R=302,L]

# Redirect Trailing Slashes If Not A Folder...
# - but look for the file in the "public" folder
# (ensure we are not already in the "public" folder)
RewriteCond %{REQUEST_URI} !^/public/
RewriteCond %{DOCUMENT_ROOT}/public/$1 !-d
RewriteRule ^(.*)/$ /$1 [R=302,L]

# Rewrite "everything" to the "public" subdirectory if not already
# This ignores existing files/dirs in the document root
RewriteCond %{REQUEST_URI} ^/(.*)
RewriteRule !^public/ public/%1

# Handle Front Controller... (as before)
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^ index.php [L]
</IfModule>

Gravityforms limit submission – once for user, unlimited for guest

	public function context() {

		// rule targets specific user, if this user is different we don't need to test the rule
		if ( $this->user_id != 'all' ) {
			if ( $this->user_id != get_current_user_id() ) {
				return false;
			}
			
		}
		if($this->user_id == "all")
		{
		    if(get_current_user_id()===0)
			{
			    return false;
			}
		}

		return true;
	}

File: gp-limit-submissions/includes/GPLS_Rule_User.php

Plugin: https://gravitywiz.com/documentation/gravity-forms-limit-submissions

How to add Buy Now button on Product page – WordPress/woocommerce?

Change &amp;&amp; to &&

add_filter('woocommerce_add_to_cart_redirect', 'malpani_redirect_checkout_add_cart');

        function malpani_redirect_checkout_add_cart()
        {
            if (isset($_POST["buynow"]) && $_POST["buynow"] === "2") {
                return wc_get_checkout_url();
            }

        }

        add_filter('woocommerce_after_add_to_cart_button', 'malpani_add_buy_button');
        function malpani_add_buy_button()
        {
        echo '<input id="buynowinput" name="buynow" value="1" hidden>
            <button type="button" id="buy_now" class="buy_now button">Buy Now</button>
            <script>
                jQuery(document).ready(function ($) {
                    $("#buy_now").click(function (e) {
                        $("#buynowinput").val(2);
                        $(".single_add_to_cart_button").click();
                        e.stopPropagation();
                        e.preventDefault();
                    })
                });
            </script>';

How to get Gravity forms entry value by label?

function harsh_get_value_by_label( $form, $entry, $label ) {
	foreach ( $form['fields'] as $field ) {
		$lead_key = $field->label;
		
		if ( strtolower( $lead_key ) == strtolower( $label ) ) {
			return $entry[ $field->id ];
		}
		if($field->inputs != null and count($field->inputs))
		{
			foreach($field->inputs as $children)
			{
				$subLeadKey = $children["label"];
				if ( strtolower( $subLeadKey ) == strtolower( $label ) ) 
				{
					return $entry[ $children["id"] ];
				}
			}
		}
	}
	return false;
}

How to edit wordpress woocommerce order api responses (legacy + latest)

<?php
//// FOR LEGACY API ONLY

add_filter('woocommerce_api_order_response', 'harsh_add_shipping_phone_legacy', 99, 1);
function harsh_add_shipping_phone($order_data)
{
    $order_data["billing_address"]["email"] = "XXXX";
	$shipping_phone = get_post_meta($order_data["id"],"_shipping_phone",1);
	if($shipping_phone!==false && strlen($shipping_phone))
	{
		$order_data["billing_address"]["biller_phone"] = $order_data["billing_address"]["phone"];
		$order_data["shipping_address"]["phone"] = $shipping_phone;
		$order_data["billing_address"]["phone"] = $shipping_phone;
	}
	foreach($order_data["line_items"] as $k=>$v)
	{
		unset($order_data["line_items"][$k]["meta"]);
	}
    return $order_data;
}


//// FOR latest api

function wc_add_rest_order_meta( $response, $post, $request ) {

	$order_data = $response->get_data();
    $order_data["billing"]["email"] = "XXXX";
   $sp = array_search('_shipping_phone', array_column($order_data["meta_data"], 'key'));
   if($sp!==false)
   {
     $order_data["billing"]["biller_phone"] = $order_data["billing"]["phone"];
     if(strlen($order_data["meta_data"][$sp]->value))
     {
     $order_data["shipping"]["phone"] = $order_data["meta_data"][$sp]->value;
     $order_data["billing"]["phone"] = $order_data["meta_data"][$sp]->value;
     }
   }
	foreach($order_data["line_items"] as $k=>$v)
	{
		unset($order_data["line_items"][$k]["meta_data"]);
	}
	
	$response->data = $order_data;

	return $response;	
}
function wc_add_rest_order_meta2( $response, $post, $request ) {
foreach($response as $oneorder)
{
	$order_data = $oneorder->get_data();
    $order_data["billing"]["email"] = "XXXX";
   $sp = array_search('_shipping_phone', array_column($order_data["meta_data"], 'key'));
   if($sp!==false)
   {
     $order_data["billing"]["biller_phone"] = $order_data["billing"]["phone"];
     if(strlen($order_data["meta_data"][$sp]->value))
     {
     $order_data["shipping"]["phone"] = $order_data["meta_data"][$sp]->value;
     $order_data["billing"]["phone"] = $order_data["meta_data"][$sp]->value;
     }
   }
	foreach($order_data["line_items"] as $k=>$v)
	{
		unset($order_data["line_items"][$k]["meta_data"]);
	}
	
	$oneorder->data = $order_data;

}
	
	return $response;	
}
add_filter( 'woocommerce_rest_prepare_shop_order_object', 'wc_add_rest_order_meta', 10, 3 );
add_filter( 'woocommerce_rest_prepare_shop_orders_object', 'wc_add_rest_order_meta2', 10, 3 );

Standalone script to print all published post IDs in WordPress

<?php
header("Access-Control-Allow-Origin: *");
header('Content-Type: application/json');
define( 'SHORTINIT', true );
require( 'wp-load.php' );
if(isset($wpdb))
{
$qr = 'SELECT * FROM `'.$wpdb->prefix . 'posts` where `post_type`="post" and `post_status`="publish"';
$posts = $wpdb->get_results( $qr);
//$pr = implode(",",array_column($posts,"ID"));
$pr = json_encode(array_column($posts,"ID"));
echo $pr;
}