Merge branch 'woocommerce:trunk' into gatewaySession

This commit is contained in:
Alexis Urien 2024-08-29 09:25:52 -07:00 committed by GitHub
commit 95968c2fdb
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
2806 changed files with 106163 additions and 65372 deletions

View File

@ -0,0 +1,7 @@
# Report Flaky Tests
A GitHub action to report flaky E2E tests to GitHub issues.
**This package is still experimental and breaking changes could be introduced in future minor versions (`v0.x`). Use it at your own risks.**
<br/><br/><p align="center"><img src="https://s.w.org/style/images/codeispoetry.png?1" alt="Code is Poetry." /></p>

View File

@ -0,0 +1,78 @@
# How to update
## Source code
This action is extracted and bundled version of the following:
Repository: https://github.com/WordPress/gutenberg/tree/trunk/packages/report-flaky-tests
Commit ID: ce803384250671d01fde6c7d6d2aa83075fcc726
## How to build
After checking out the repository, navigate to packages/report-flaky-tests and do some modifications:
### package.json file
Add the following dependency: `"ts-loader": "^9.5.1",`.
### tsconfig.json file
The file context should be updated to following state:
```
{
"$schema": "https://json.schemastore.org/tsconfig.json",
"extends": "../../tsconfig.base.json",
"compilerOptions": {
"outDir": "dist",
"target": "es6",
"module": "commonjs",
"esModuleInterop": true,
"moduleResolution": "node",
"declarationDir": "build-types",
"rootDir": "src",
"emitDeclarationOnly": false,
},
"include": [ "src/**/*" ],
"exclude": [ "src/__tests__/**/*", "src/__fixtures__/**/*" ]
}
```
### webpack.config.js file
The file should be added with the following content:
```
const path = require( 'path' );
const buildMode = process.env.NODE_ENV || 'production';
module.exports = {
entry: './src/index.ts',
target: 'node',
mode: buildMode,
module: {
rules: [
{
test: /\.tsx?$/,
use: 'ts-loader',
exclude: /node_modules/,
},
],
},
resolve: {
extensions: [ '.tsx', '.ts', '.js' ],
},
plugins: [],
output: {
filename: 'index.js',
path: path.resolve( __dirname, 'dist' ),
clean: true,
},
};
```
### Build
Run `webpack --config webpack.config.js` (don't forget about `npm install` before that).
Use the generated files under `packages/report-flaky-tests/dist` to update the bundled distribution in this repository.

View File

@ -0,0 +1,17 @@
name: 'Report flaky tests'
description: 'Report flaky tests to GitHub issues'
inputs:
repo-token:
description: 'GitHub token'
required: true
label:
description: 'The flaky-test label name'
required: true
default: 'flaky-test'
artifact-path:
description: 'The path of the downloaded artifact'
required: true
default: 'flaky-tests'
runs:
using: 'node20'
main: 'dist/index.js'

File diff suppressed because one or more lines are too long

View File

@ -0,0 +1,41 @@
/*!
* fill-range <https://github.com/jonschlinkert/fill-range>
*
* Copyright (c) 2014-present, Jon Schlinkert.
* Licensed under the MIT License.
*/
/*!
* is-number <https://github.com/jonschlinkert/is-number>
*
* Copyright (c) 2014-present, Jon Schlinkert.
* Released under the MIT License.
*/
/*!
* is-plain-object <https://github.com/jonschlinkert/is-plain-object>
*
* Copyright (c) 2014-2017, Jon Schlinkert.
* Released under the MIT License.
*/
/*!
* to-regex-range <https://github.com/micromatch/to-regex-range>
*
* Copyright (c) 2015-present, Jon Schlinkert.
* Released under the MIT License.
*/
/*! formdata-polyfill. MIT License. Jimmy Wärting <https://jimmy.warting.se/opensource> */
/*! ws. MIT License. Einar Otto Stangvik <einaros@gmail.com> */
/**
* @license React
* react-is.production.min.js
*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

View File

@ -22,14 +22,14 @@ inputs:
runs:
using: 'composite'
steps:
- name: 'Read PNPM Version'
id: 'read-pnpm-version'
shell: 'bash'
run: 'echo "version=$(./.github/actions/setup-woocommerce-monorepo/scripts/read-pnpm-version.sh package.json)" >> $GITHUB_OUTPUT'
- name: 'Setup PNPM'
uses: 'pnpm/action-setup@a3252b78c470c02df07e9d59298aecedc3ccdd6d'
with:
version: ${{ steps.read-pnpm-version.outputs.version }}
# Next step is rudimentary - fixes a know composite action bug during post-actions:
# Error: Index was out of range. Must be non-negative and less than the size of the collection.
- name: 'Read PNPM version'
id: 'read-pnpm-version'
shell: 'bash'
run: 'echo "version=$(pnpm --version)" >> $GITHUB_OUTPUT'
- name: 'Setup Node'
uses: 'actions/setup-node@8f152de45cc393bb48ce5d89d36b731f54556e65'
with:
@ -52,8 +52,15 @@ runs:
uses: 'actions/cache@ab5e6d0c87105b4c9c2047343972218f562e4319'
with:
path: "${{ env.PNPM_STORE_PATH }}"
key: "${{ runner.os }}-pnpm-${{ inputs.pull-package-deps }}-${{ hashFiles( 'pnpm-lock.yaml' ) }}"
restore-keys: '${{ runner.os }}-pnpm-${{ inputs.pull-package-deps }}-'
key: "${{ runner.os }}-pnpm-${{ inputs.pull-package-deps }}-build:${{ inputs.build-type }}-${{ hashFiles( 'pnpm-lock.yaml' ) }}"
restore-keys: '${{ runner.os }}-pnpm-${{ inputs.pull-package-deps }}-build:${{ inputs.build-type }}-'
- name: 'Cache: node cache'
if: ${{ inputs.pull-package-deps != 'false' }}
uses: 'actions/cache@ab5e6d0c87105b4c9c2047343972218f562e4319'
with:
path: './node_modules/.cache'
key: "${{ runner.os }}-node-cache-${{ inputs.pull-package-deps }}-${{ hashFiles( 'pnpm-lock.yaml' ) }}"
restore-keys: '${{ runner.os }}-node-cache-${{ inputs.pull-package-deps }}-'
- name: 'Cache Composer Dependencies'
if: ${{ inputs.pull-package-deps != 'false' }}
uses: 'actions/cache@ab5e6d0c87105b4c9c2047343972218f562e4319'
@ -79,7 +86,15 @@ runs:
if: ${{ inputs.install == 'true' || steps.project-filters.outputs.install != '' }}
shell: 'bash'
# The installation command is a bit odd as it's a workaround for know bug - https://github.com/pnpm/pnpm/issues/6300.
run: "pnpm install ${{ steps.project-filters.outputs.install }} --frozen-lockfile ${{ steps.project-filters.outputs.install != '' && '--config.dedupe-peer-dependents=false' || '' }}"
run: |
if [[ '${{ inputs.install }}' == '@woocommerce/plugin-woocommerce...' && '${{ inputs.build-type }}' == 'backend' ]]; then
# PHPUnit/REST testing optimized installation of the deps: minimalistic and parallellized between PHP/JS.
# JS deps installation is abit hard-core, but all we need actually is wp-env and playwright - we are good at that regard.
composer install --working-dir=./plugins/woocommerce --quiet &
pnpm install --filter='@woocommerce/plugin-woocommerce' --frozen-lockfile --config.dedupe-peer-dependents=false --ignore-scripts
else
pnpm install ${{ steps.project-filters.outputs.install }} --frozen-lockfile ${{ steps.project-filters.outputs.install != '' && '--config.dedupe-peer-dependents=false' || '' }}
fi
# We want to include an option to build projects using this action so that we can make
# sure that the build cache is always used when building projects.
- name: 'Cache Build Output'

View File

@ -1,9 +0,0 @@
#!/usr/bin/env bash
PACKAGE_FILE=$1
if [[ -z "$PACKAGE_FILE" ]]; then
echo "Usage: $0 <package.json>"
exit 1
fi
awk -F'"' '/"pnpm": ".+"/{ print $4; exit; }' $PACKAGE_FILE

View File

@ -31,24 +31,25 @@
- team: vortex
"packages/js/components/**/*":
- team: mothra
- team: woo-fse
- team: ghidorah
"packages/js/csv-export/**/*":
- team: mothra
- team: woo-fse
"packages/js/currency/**/*":
- team: mothra
- team: woo-fse
"packages/js/customer-effort-score/**/*":
- team: mothra
- team: woo-fse
- team: ghidorah
"packages/js/data/**/*":
- team: mothra
- team: woo-fse
- team: ghidorah
"packages/js/date/**/*":
- team: mothra
- team: woo-fse
"packages/js/dependency-extraction-webpack-plugin/**/*":
- team: vortex
@ -57,26 +58,27 @@
- team: vortex
"packages/js/experimental/**/*":
- team: mothra
- team: woo-fse
"packages/js/explat/**/*":
- team: mothra
- team: woo-fse
- team: ghidorah
"packages/js/navigation/**/*":
- team: mothra
- team: woo-fse
"packages/js/number/**/*":
- team: mothra
- team: woo-fse
"packages/js/onboarding/**/*":
- team: ghidorah
"packages/js/product-editor/**/*":
- team: mothra
- team: woo-fse
"packages/js/tracks/**/*":
- team: mothra
- team: woo-fse
- team: ghidorah
"plugins/woocommerce/**/*":
- team: proton
@ -89,7 +91,7 @@
- team: proton
"plugins/woocommerce/src/Admin/**/*":
- team: mothra
- team: woo-fse
- team: ghidorah
"plugins/woocommerce/src/Blocks/**/*":
@ -97,7 +99,7 @@
- team: woo-fse
"plugins/woocommerce/src/Internal/Admin/**/*":
- team: mothra
- team: woo-fse
- team: ghidorah
"plugins/woocommerce/src/StoreApi/**/*":
@ -105,7 +107,7 @@
- team: woo-fse
"plugins/woocommerce-admin/**/*":
- team: mothra
- team: woo-fse
- team: ghidorah
"plugins/woocommerce-blocks/**/*":

View File

@ -12,4 +12,4 @@ jobs:
uses: acq688/Request-Reviewer-For-Team-Action@v1.1
with:
config: '.github/automate-team-review-assignment-config.yml'
GITHUB_TOKEN: ${{ secrets.FINE_GRAINED_TOKEN_ACTIONS }}
GITHUB_TOKEN: ${{ secrets.PR_ASSIGN_TOKEN }}

View File

@ -14,48 +14,16 @@ on:
required: true
default: 'default'
type: string
workflow_dispatch:
inputs:
pr_simulate:
description: 'Would you like to run CI on a pull request? If so, enter the PR number here. If blank, the entire suite will be run.'
type: string
default: ''
concurrency:
group: '${{ github.workflow }}-${{ github.ref }}'
# Cancel concurrent jobs but not for push event. For push use the run_id to have a unique group.
group: ci-${{ github.event_name == 'push' && github.run_id || github.event_name }}-${{ github.ref }}-${{ inputs.trigger }}
cancel-in-progress: true
env:
FORCE_COLOR: 1
jobs:
dispatch-handler:
name: 'Handle dispatched workflow'
runs-on: 'ubuntu-20.04'
if: ${{ github.event_name == 'workflow_dispatch' && inputs.pr_simulate }}
outputs:
head: ${{ steps.pr-info.outputs.head }}
base: ${{ steps.pr-info.outputs.base }}
steps:
- uses: actions/github-script@v7
name: 'Grab PR info.'
id: 'pr-info'
env:
PR: ${{ inputs.pr_simulate }}
with:
retries: 3
script: |
if ( ! process.env.PR ) {
return;
}
const PR = await github.rest.pulls.get( {
pull_number: process.env.PR,
repo: context.repo.repo,
owner: context.repo.owner,
} );
core.setOutput( 'head', PR.data.head.ref );
core.setOutput( 'base', PR.data.base.ref );
project-jobs:
# Since this is a monorepo, not every pull request or change is going to impact every project.
# Instead of running CI tasks on all projects indiscriminately, we use a command to detect
@ -63,12 +31,6 @@ jobs:
# matrices that we can use to run CI tasks only on the projects that need them.
name: 'Build Project Jobs'
runs-on: 'ubuntu-20.04'
needs: 'dispatch-handler'
# Because forks of this repository may want to skip running this CI automatically, but still
# be able to run it via workflow_dispatch, if the SKIP_CI variable is truthy, and we're not
# running from a workflow_dispatch, we'll skip generating the project matrix and any jobs.
# Because dispatch-handler may be skipped, we need the always() here.
if: ${{ always() && ( github.event_name == 'workflow_dispatch' || ! vars.SKIP_CI ) }}
outputs:
lint-jobs: ${{ steps.project-jobs.outputs.lint-jobs }}
test-jobs: ${{ steps.project-jobs.outputs.test-jobs }}
@ -77,25 +39,21 @@ jobs:
- uses: 'actions/checkout@v4'
name: 'Checkout'
with:
fetch-depth: 0
# If the workflow wasn't triggered by dispatch, this will be empty and use defaults.
ref: ${{ needs.dispatch-handler.outputs.head }}
- uses: './.github/actions/setup-woocommerce-monorepo'
name: 'Setup Monorepo'
with:
php-version: false # We don't want to waste time installing PHP since we aren't using it in this job.
# If 'base_ref' is available, the 'Build Matrix' step requires non-shallow git-history to identify changed files.
fetch-depth: ${{ ( ( github.base_ref && '0' ) || '1' ) }}
- name: 'Setup PNPM'
uses: 'pnpm/action-setup@a3252b78c470c02df07e9d59298aecedc3ccdd6d'
- uses: actions/github-script@v7
name: 'Build Matrix'
id: 'project-jobs'
env:
PR_SIM: ${{ needs.dispatch-handler.outputs.base }}
with:
script: |
const prSim = process.env.PR_SIM;
// Intended behaviour of the jobs generation:
// - PRs: run CI jobs aiming PRs and filter out jobs based on the content changes
// - Pushes: run CI jobs aiming pushes without filtering based on the content changes
let baseRef = prSim || ${{ toJson( github.base_ref ) }};
// github.base_ref is only available for pull_request events
let baseRef = ${{ toJson( github.base_ref ) }};
if ( baseRef ) {
baseRef = `--base-ref origin/${ baseRef }`;
}
@ -118,35 +76,30 @@ jobs:
githubEvent = trigger;
}
// Override the event 'workflow_dispatch' event type if we're simulating a PR.
if ( prSim ) {
githubEvent = 'pull_request';
// `pre-release` should trigger `release-checks`, but without a 'tag' ref.
// This will run all release-checks against the branch the workflow targeted, instead of a release artifact.
if ( trigger === 'pre-release' ) {
githubEvent = 'release-checks';
}
const child_process = require( 'node:child_process' );
child_process.execSync( `pnpm utils ci-jobs ${ baseRef } --event ${ githubEvent }` );
project-lint-jobs:
name: "Lint - ${{ matrix.projectName }} ${{ matrix.optional && ' (optional)' || ''}}"
runs-on: 'ubuntu-20.04'
needs: [
'project-jobs',
'dispatch-handler'
]
# Because dispatch-handler may be skipped, we need the always() here.
if: ${{ always() && needs.project-jobs.outputs.lint-jobs != '[]' && ( github.event_name == 'pull_request' || inputs.pr_simulate != '' ) }}
needs: 'project-jobs'
if: ${{ needs.project-jobs.outputs.lint-jobs != '[]' && github.event_name == 'pull_request' }}
strategy:
fail-fast: false
matrix:
include: ${{ fromJSON( needs.project-jobs.outputs.lint-jobs ) }}
steps:
- uses: 'actions/checkout@v4'
name: 'Checkout'
with:
fetch-depth: 0
# If the workflow wasn't triggered by dispatch, this will be empty and use defaults.
ref: ${{ needs.dispatch-handler.outputs.head }}
# the WooCommerce plugin package uses phpcs-changed for linting, which requires non-shallow git-history.
fetch-depth: ${{ ( ( matrix.projectName == '@woocommerce/plugin-woocommerce' && '0' ) || '1' ) }}
- uses: './.github/actions/setup-woocommerce-monorepo'
name: 'Setup Monorepo'
@ -157,27 +110,20 @@ jobs:
- name: 'Lint'
run: 'pnpm --filter="${{ matrix.projectName }}" ${{ matrix.command }}'
project-test-jobs:
name: "${{ matrix.name }}"
runs-on: 'ubuntu-20.04'
needs: [
'project-jobs',
'dispatch-handler'
]
if: ${{ always() && needs.project-jobs.outputs.test-jobs != '[]' }}
needs: 'project-jobs'
if: ${{ needs.project-jobs.outputs.test-jobs != '[]' }}
env: ${{ matrix.testEnv.envVars }}
strategy:
fail-fast: false
matrix:
include: ${{ fromJSON( needs.project-jobs.outputs.test-jobs ) }}
steps:
- uses: 'actions/checkout@v4'
name: 'Checkout'
with:
# If the workflow wasn't triggered by dispatch, this will be empty and use defaults.
ref: ${{ needs.dispatch-handler.outputs.head }}
- uses: './.github/actions/setup-woocommerce-monorepo'
name: 'Install Monorepo'
@ -194,9 +140,9 @@ jobs:
env:
RELEASE_TAG: ${{ github.ref_name }}
ARTIFACT_NAME: ${{ github.ref_name == 'nightly' && 'woocommerce-trunk-nightly.zip' || 'woocommerce.zip' }}
WP_ENV_CONFIG_PATH: ${{ matrix.projectPath }}
working-directory: ${{ matrix.projectPath }}
run: node ./github/workflows/scripts/override-wp-env-plugins.js
# band-aid to get the path to wp-env.json for blocks e2e tests, until they're migrated to plugins/woocommerce
WP_ENV_CONFIG_PATH: ${{ github.workspace }}/${{ matrix.testEnv.start == 'env:start:blocks' && 'plugins/woocommerce-blocks' || matrix.projectPath }}
run: node .github/workflows/scripts/override-wp-env-plugins.js
- name: 'Start Test Environment'
id: 'prepare-test-environment'
@ -204,37 +150,92 @@ jobs:
env: ${{ matrix.testEnv.envVars }}
run: 'pnpm --filter="${{ matrix.projectName }}" ${{ matrix.testEnv.start }}'
- name: 'Get commit message'
id: 'get_commit_message'
- name: 'Determine BuildKite Analytics Message'
env:
HEAD_COMMIT_MESSAGE: ${{ github.event.head_commit.message }}
PR_TITLE: ${{ github.event.pull_request.title }}
run: |
if [[ "${{ github.event_name }}" == "push" ]]; then
COMMIT_MESSAGE=`echo "$HEAD_COMMIT_MESSAGE" | head -1`
MESSAGE=`echo "$HEAD_COMMIT_MESSAGE" | head -1`
elif [[ "${{ github.event_name }}" == "pull_request" ]]; then
COMMIT_MESSAGE="$PR_TITLE"
MESSAGE="$PR_TITLE"
else
COMMIT_MESSAGE="${{ github.event_name }}"
MESSAGE="${{ github.event_name }}"
fi
echo "COMMIT_MESSAGE=$COMMIT_MESSAGE" >> "$GITHUB_OUTPUT"
echo "BUILDKITE_ANALYTICS_MESSAGE=$MESSAGE" >> "$GITHUB_ENV"
shell: bash
- name: 'Run tests (${{ matrix.testType }})'
env:
E2E_ENV_KEY: ${{ secrets.E2E_ENV_KEY }}
BUILDKITE_ANALYTICS_TOKEN: ${{ secrets.BUILDKITE_CORE_E2E_TOKEN }}
BUILDKITE_ANALYTICS_MESSAGE: ${{ steps.get_commit_message.outputs.COMMIT_MESSAGE }}
CODEVITALS_PROJECT_TOKEN: ${{ secrets.CODEVITALS_PROJECT_TOKEN }} # required by Metrics tests
run: 'pnpm --filter="${{ matrix.projectName }}" ${{ matrix.command }}'
- name: 'Resolve artifacts path'
if: ${{ always() && matrix.report.resultsPath != '' }}
# Blocks e2e use a relative path which is not supported by actions/upload-artifact@v4
# https://github.com/actions/upload-artifact/issues/176
env:
ARTIFACTS_PATH: '${{ matrix.projectPath }}/${{ matrix.report.resultsPath }}'
run: echo "ARTIFACTS_PATH=$(realpath $ARTIFACTS_PATH)" >> $GITHUB_ENV
run: |
# first runs will probably not have the directory, so we need to create it so that realpath doesn't fail
mkdir -p $ARTIFACTS_PATH
echo "ARTIFACTS_PATH=$(realpath $ARTIFACTS_PATH)" >> $GITHUB_ENV
- name: 'Download Playwright last run info'
id: 'download-last-run-info'
if: ${{ always() && matrix.report.resultsPath != '' && matrix.testType == 'e2e' }}
uses: actions/download-artifact@v4
with:
pattern: 'last-run__${{ strategy.job-index }}'
- name: 'Run tests (${{ matrix.testType }})'
env:
E2E_ENV_KEY: ${{ secrets.E2E_ENV_KEY }}
BUILDKITE_ANALYTICS_TOKEN: ${{ secrets.BUILDKITE_CORE_E2E_TOKEN }}
CODEVITALS_PROJECT_TOKEN: ${{ secrets.CODEVITALS_PROJECT_TOKEN }} # required by Metrics tests
LAST_FAILED_RUN: ${{ vars.LAST_FAILED_RUN }}
run: |
lastRunFile="${{ steps.download-last-run-info.outputs.download-path }}/last-run__${{ strategy.job-index }}/.last-run.json"
lastRunFileDest="$ARTIFACTS_PATH/.last-run.json"
if [ -f "$lastRunFile" ]; then
echo "Found last run info file: \"$lastRunFile\""
echo "Moving to destination: \"$lastRunFileDest\""
mkdir -p "$ARTIFACTS_PATH"
mv "$lastRunFile" "$lastRunFileDest"
else
echo "No last run info file found. Searched for: \"$lastRunFile\""
fi
lastRunFlag=""
if [ -f "$lastRunFileDest" ]; then
# Playwright last run info is available, parse the file and check if there are failed tests
cat "$lastRunFileDest"
failedTests=$(jq '.failedTests | length' "$lastRunFileDest")
# Only if there are failed tests, we want to use the --last-failed flag.
# The run will fail if we're using the flag and there are no failed tests.
if [ "$failedTests" -gt 0 ]; then
if [ "$LAST_FAILED_RUN" == "1" ]; then
echo "Found failed tests, running only failed tests"
# Add shard 1/1 to override the default shard value. No tests will run for shards > 1.
# The clean way would be to replace the shard flag from the command, but this also works.
lastRunFlag="--last-failed --shard=1/1"
else
echo "Found failed tests, but LAST_FAILED_RUN is switched off. Running all tests."
fi
else
echo "No failed tests found, running all tests"
fi
fi
# Finally, run the tests
pnpm --filter="${{ matrix.projectName }}" ${{ matrix.command }} $lastRunFlag
- name: 'Upload Playwright last run info'
# always upload the last run info, even if the test run passed
if: ${{ always() && matrix.report.resultsPath != '' }}
uses: actions/upload-artifact@v4
with:
name: 'last-run__${{ strategy.job-index }}'
path: '${{ env.ARTIFACTS_PATH }}/.last-run.json'
if-no-files-found: ignore
overwrite: true
- name: 'Upload artifacts'
if: ${{ always() && matrix.report.resultsPath != '' }}
@ -249,15 +250,6 @@ jobs:
name: flaky-tests-${{ strategy.job-index }}
path: ${{ env.ARTIFACTS_PATH }}/flaky-tests
if-no-files-found: ignore
- name: 'Archive metrics results'
if: ${{ success() && startsWith(matrix.name, 'Metrics') }} # this seems too fragile, we should update the reporting path and use the generic upload step above
uses: actions/upload-artifact@v4
env:
WP_ARTIFACTS_PATH: ${{ github.workspace }}/artifacts
with:
name: metrics-results
path: ${{ env.WP_ARTIFACTS_PATH }}/*.performance-results*.json
evaluate-project-jobs:
# In order to add a required status check we need a consistent job that we can grab onto.
@ -273,7 +265,7 @@ jobs:
'project-lint-jobs',
'project-test-jobs',
]
if: ${{ always() && github.event_name == 'pull_request' }}
if: ${{ !cancelled() && github.event_name == 'pull_request' }}
steps:
- uses: 'actions/checkout@v4'
name: 'Checkout'
@ -302,15 +294,13 @@ jobs:
'project-lint-jobs',
'project-test-jobs',
]
if: ${{ always() && github.event_name != 'pull_request' && ! github.event.pull_request.head.repo.fork }}
if: ${{ !cancelled() && github.event_name != 'pull_request' && github.repository == 'woocommerce/woocommerce' }}
steps:
- uses: 'actions/checkout@v4'
name: 'Checkout'
- uses: './.github/actions/setup-woocommerce-monorepo'
name: 'Setup Monorepo'
with:
php-version: false
- name: 'Setup PNPM'
uses: 'pnpm/action-setup@a3252b78c470c02df07e9d59298aecedc3ccdd6d'
- name: 'Send messages for failed jobs'
env:
@ -339,7 +329,7 @@ jobs:
'project-jobs',
'project-test-jobs',
]
if: ${{ always() && needs.project-jobs.outputs.report-jobs != '[]' && ! github.event.pull_request.head.repo.fork }}
if: ${{ !cancelled() && needs.project-jobs.outputs.report-jobs != '[]' && github.repository == 'woocommerce/woocommerce' }}
strategy:
fail-fast: false
matrix:
@ -393,48 +383,42 @@ jobs:
-f suite="$REPORT_NAME" \
-f report_title="$REPORT_TITLE" \
--repo woocommerce/woocommerce-test-reports
report-flaky-tests:
name: 'Create issues for flaky tests'
if: ${{ !cancelled() && ! github.event.pull_request.head.repo.fork }}
needs: [ 'project-test-jobs' ]
if: ${{ !cancelled() && github.repository == 'woocommerce/woocommerce' && needs.project-jobs.outputs.test-jobs != '[]' }}
needs:
[
'project-jobs',
'project-test-jobs',
]
runs-on: ubuntu-latest
permissions:
contents: read
issues: write
steps:
- uses: actions/checkout@v4
with:
repository: WordPress/gutenberg
ref: dbf201449e9736f672b61e422787d47659db327a
- uses: 'actions/checkout@v4'
name: 'Checkout'
- uses: actions/download-artifact@v4
id: download-artifact
- uses: 'actions/download-artifact@v4'
name: 'Download artifacts'
with:
pattern: flaky-tests*
path: flaky-tests
merge-multiple: true
- name: 'Check if there are flaky tests reports'
- name: 'Merge flaky tests reports'
run: |
downloadPath='${{ steps.download-artifact.outputs.download-path }}'
downloadPath='${{ steps.download-artifact.outputs.download-path || './flaky-tests' }}'
# make dir so that next step doesn't fail if it doesn't exist
mkdir -p $downloadPath
# any output means there are reports
echo "FLAKY_REPORTS=$(ls -A $downloadPath | head -1)" >> $GITHUB_ENV
- name: 'Setup'
if: ${{ !!env.FLAKY_REPORTS }}
uses: ./.github/setup-node
- name: 'Build packages'
if: ${{ !!env.FLAKY_REPORTS }}
run: npm run build:packages
- name: 'Report flaky tests'
if: ${{ !!env.FLAKY_REPORTS }}
uses: ./packages/report-flaky-tests
uses: './.github/actions/report-flaky-tests'
with:
repo-token: ${{ secrets.GITHUB_TOKEN }}
label: 'metric: flaky e2e test'

View File

@ -41,13 +41,17 @@ jobs:
- name: Setup WooCommerce Monorepo
uses: ./.github/actions/setup-woocommerce-monorepo
with:
# Both install and build are handled by compressed-size-action.
install: false
build: false
php-version: false
pull-package-deps: '@woocommerce/plugin-woocommerce'
- uses: preactjs/compressed-size-action@f780fd104362cfce9e118f9198df2ee37d12946c
env:
BROWSERSLIST_IGNORE_OLD_DATA: true
with:
repo-token: '${{ secrets.GITHUB_TOKEN }}'
pattern: './{packages/js/!(*e2e*|*internal*|*test*|*plugin*|*create*),plugins/woocommerce-blocks}/{build,build-style}/**/*.{js,css}'
clean-script: '--if-present distclean'
install-script: 'pnpm install --filter="@woocommerce/plugin-woocommerce..." --frozen-lockfile --config.dedupe-peer-dependents=false --ignore-scripts'
build-script: '--filter="@woocommerce/plugin-woocommerce" build'
clean-script: '--if-present buildclean'
minimum-change-threshold: 100
omit-unchanged: true

View File

@ -8,6 +8,8 @@ on:
- '**/changelog/**'
- '**/tests/**'
- '**/*.md'
- '.github/**'
- '!.github/workflows/pr-build-live-branch.yml'
concurrency:
# Cancel concurrent jobs on pull_request but not push, by including the run_id in the concurrency group for the latter.

View File

@ -3,6 +3,7 @@ on:
pull_request:
paths:
- 'plugins/woocommerce/**'
- '!plugins/woocommerce/templates/templates/**'
jobs:
analyze:
name: 'Analyze Branch Changes'
@ -26,7 +27,7 @@ jobs:
GIT_CLONE_PROTECTION_ACTIVE: false
run: |
HEAD_REF=$(git rev-parse HEAD)
exclude="plugins/woocommerce/tests plugins/woocommerce-admin/tests plugins/woocommerce-blocks/tests"
exclude="plugins/woocommerce/tests plugins/woocommerce/templates/templates plugins/woocommerce-admin/tests plugins/woocommerce-blocks/tests"
version=$(pnpm analyzer major-minor "$HEAD_REF" "plugins/woocommerce/woocommerce.php" | tail -n 1)
pnpm analyzer "$HEAD_REF" $version -o "github" -e $exclude
- uses: 'actions/github-script@v6'

View File

@ -38,9 +38,7 @@ jobs:
docs/docs-manifest.json
- name: Setup PNPM
uses: pnpm/action-setup@fe02b34f77f8bc703788d5817da081398fad5dd2
with:
version: '8.6.7'
uses: pnpm/action-setup@a3252b78c470c02df07e9d59298aecedc3ccdd6d
- name: Setup Node
uses: actions/setup-node@64ed1c7eab4cce3362f8c340dee64e5eaeef8f7c

View File

@ -31,7 +31,6 @@ jobs:
issues: write
pull-requests: write
outputs:
pnpmVersion: ${{ steps.read-pnpm-version.outputs.version }}
isTodayAcceleratedFreeze: ${{ steps.get-versions.outputs.isTodayAcceleratedFreeze }}
isTodayMonthlyFreeze: ${{ steps.get-versions.outputs.isTodayMonthlyFreeze }}
acceleratedVersion: ${{ steps.get-versions.outputs.acceleratedVersion }}
@ -47,18 +46,8 @@ jobs:
with:
fetch-depth: 0
- name: Read PNPM Version
id: read-pnpm-version
shell: bash
run: |
version=$(./.github/actions/setup-woocommerce-monorepo/scripts/read-pnpm-version.sh package.json)
echo "version=$version" >> $GITHUB_OUTPUT
echo "PNPM Version: $version"
- name: Setup PNPM
uses: pnpm/action-setup@fe02b34f77f8bc703788d5817da081398fad5dd2
with:
version: ${{ steps.read-pnpm-version.outputs.version }}
uses: pnpm/action-setup@a3252b78c470c02df07e9d59298aecedc3ccdd6d
- name: Setup Node
uses: actions/setup-node@64ed1c7eab4cce3362f8c340dee64e5eaeef8f7c
@ -149,9 +138,7 @@ jobs:
fetch-depth: 0
- name: Setup PNPM
uses: pnpm/action-setup@fe02b34f77f8bc703788d5817da081398fad5dd2
with:
version: ${{ needs.code-freeze-prep.outputs.pnpmVersion }}
uses: pnpm/action-setup@a3252b78c470c02df07e9d59298aecedc3ccdd6d
- name: Setup Node
uses: actions/setup-node@64ed1c7eab4cce3362f8c340dee64e5eaeef8f7c
@ -275,9 +262,7 @@ jobs:
fetch-depth: 0
- name: Setup PNPM
uses: pnpm/action-setup@fe02b34f77f8bc703788d5817da081398fad5dd2
with:
version: ${{ needs.code-freeze-prep.outputs.pnpmVersion }}
uses: pnpm/action-setup@a3252b78c470c02df07e9d59298aecedc3ccdd6d
- name: Setup Node
uses: actions/setup-node@64ed1c7eab4cce3362f8c340dee64e5eaeef8f7c
@ -346,9 +331,7 @@ jobs:
fetch-depth: 0
- name: Setup PNPM
uses: pnpm/action-setup@fe02b34f77f8bc703788d5817da081398fad5dd2
with:
version: ${{ needs.code-freeze-prep.outputs.pnpmVersion }}
uses: pnpm/action-setup@a3252b78c470c02df07e9d59298aecedc3ccdd6d
- name: Setup Node
uses: actions/setup-node@64ed1c7eab4cce3362f8c340dee64e5eaeef8f7c

View File

@ -20,14 +20,10 @@ jobs:
- name: Setup WooCommerce Monorepo
uses: ./.github/actions/setup-woocommerce-monorepo
with:
install: '@woocommerce/plugin-woocommerce'
build: '@woocommerce/plugin-woocommerce'
install: '@woocommerce/plugin-woocommerce-beta-tester...'
build: '@woocommerce/plugin-woocommerce-beta-tester...'
pull-package-deps: '@woocommerce/plugin-woocommerce-beta-tester'
- name: Lint
working-directory: plugins/woocommerce-beta-tester
run: composer run phpcs
- name: Build WooCommerce Beta Tester Zip
working-directory: plugins/woocommerce-beta-tester
run: pnpm build:zip

View File

@ -1,66 +1,70 @@
name: Remind reviewers to also review the testing instructions.
name: Remind reviewers to also review the testing instructions and test coverage
on:
pull_request_target:
types: [review_requested]
pull_request_target:
types: [review_requested]
permissions: {}
concurrency:
group: ${{ github.workflow }}-${{ github.event.pull_request.number }}
cancel-in-progress: true
jobs:
add-testing-instructions-review-comment:
runs-on: ubuntu-20.04
permissions:
pull-requests: write
steps:
- uses: actions/checkout@v3
add-testing-instructions-review-comment:
runs-on: ubuntu-20.04
permissions:
pull-requests: write
steps:
- uses: actions/checkout@v3
- name: Setup Node.js
uses: actions/setup-node@64ed1c7eab4cce3362f8c340dee64e5eaeef8f7c
- name: Setup Node.js
uses: actions/setup-node@64ed1c7eab4cce3362f8c340dee64e5eaeef8f7c
- name: Install Octokit
run: npm --prefix .github/workflows/scripts install @octokit/action@~6.1.0
- name: Install Octokit
run: npm --prefix .github/workflows/scripts install @octokit/action@~6.1.0
- name: Install Actions Core
run: npm --prefix .github/workflows/scripts install @actions/core@~1.10.1
- name: Install Actions Core
run: npm --prefix .github/workflows/scripts install @actions/core@~1.10.1
- name: Check if user is a community contributor
id: is-community-contributor
run: node .github/workflows/scripts/is-community-contributor.js
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
- name: Check if user is a community contributor
id: is-community-contributor
run: node .github/workflows/scripts/is-community-contributor.js
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
- name: Get the username of requested reviewers
if: steps.is-community-contributor.outputs.is-community == 'no'
id: get_reviewer_username
run: |
# Retrieves the username of all reviewers and stores them in a comma-separated list
reviewers=$(echo '${{ toJson(github.event.pull_request.requested_reviewers[*].login) }}' | jq -r 'map("@\(.)") | join(", ")')
echo "REVIEWERS=$reviewers" >> $GITHUB_ENV
- name: Get the username of requested reviewers
if: steps.is-community-contributor.outputs.is-community == 'no'
id: get_reviewer_username
run: |
# Retrieves the username of all reviewers and stores them in a comma-separated list
reviewers=$(echo '${{ toJson(github.event.pull_request.requested_reviewers[*].login) }}' | jq -r 'map("@\(.)") | join(", ")')
echo "REVIEWERS=$reviewers" >> $GITHUB_ENV
- name: Get the name of requested teams
id: get_team_name
run: |
# Retrieves the name of all teams asked for review and stores them in a comma-separated list
teams=$(echo '${{ toJson(github.event.pull_request.requested_teams[*].slug) }}' | jq -r 'map("@woocommerce/\(.)") | join(", ")')
echo "TEAMS=$teams" >> $GITHUB_ENV
- name: Get the name of requested teams
id: get_team_name
run: |
# Retrieves the name of all teams asked for review and stores them in a comma-separated list
teams=$(echo '${{ toJson(github.event.pull_request.requested_teams[*].slug) }}' | jq -r 'map("@woocommerce/\(.)") | join(", ")')
echo "TEAMS=$teams" >> $GITHUB_ENV
- name: Find the comment by github-actions[bot] asking for reviewing the testing instructions
uses: peter-evans/find-comment@034abe94d3191f9c89d870519735beae326f2bdb
id: find-comment
with:
issue-number: ${{ github.event.pull_request.number }}
comment-author: 'github-actions[bot]'
body-includes: please make sure to review the testing instructions
- name: Find the comment by github-actions[bot] asking for reviewing the testing instructions
uses: peter-evans/find-comment@034abe94d3191f9c89d870519735beae326f2bdb
id: find-comment
with:
issue-number: ${{ github.event.pull_request.number }}
comment-author: 'github-actions[bot]'
body-includes: please make sure to review the testing instructions
- name: Create or update PR comment asking for reviewers to review the testing instructions
uses: peter-evans/create-or-update-comment@67dcc547d311b736a8e6c5c236542148a47adc3d
with:
comment-id: ${{ steps.find-comment.outputs.comment-id }}
issue-number: ${{ github.event.pull_request.number }}
body: |
Hi ${{ env.REVIEWERS }}, ${{ env.TEAMS }}
Apart from reviewing the code changes, please make sure to review the testing instructions as well.
You can follow this guide to find out what good testing instructions should look like:
https://github.com/woocommerce/woocommerce/wiki/Writing-high-quality-testing-instructions
edit-mode: replace
- name: Create or update PR comment asking for reviewers to review the testing instructions and test coverage
uses: peter-evans/create-or-update-comment@67dcc547d311b736a8e6c5c236542148a47adc3d
with:
comment-id: ${{ steps.find-comment.outputs.comment-id }}
issue-number: ${{ github.event.pull_request.number }}
body: |
Hi ${{ env.REVIEWERS }}, ${{ env.TEAMS }}
Apart from reviewing the code changes, please make sure to review the testing instructions and verify that relevant tests (E2E, Unit, Integration, etc.) have been added or updated as needed.
You can follow this guide to find out what good testing instructions should look like:
https://github.com/woocommerce/woocommerce/wiki/Writing-high-quality-testing-instructions
edit-mode: replace

View File

@ -20,24 +20,50 @@ if ( ! WP_ENV_CONFIG_PATH ) {
const artifactUrl = `https://github.com/woocommerce/woocommerce/releases/download/${ RELEASE_TAG }/${ ARTIFACT_NAME }`;
const testEnvPlugins = {
env: {
tests: {
plugins: [],
},
},
};
const data = fs.readFileSync( `${ WP_ENV_CONFIG_PATH }/.wp-env.json`, 'utf8' );
const configPath = `${ WP_ENV_CONFIG_PATH }/.wp-env.json`;
console.log( `Reading ${ configPath }` );
const data = fs.readFileSync( configPath, 'utf8' );
const wpEnvConfig = JSON.parse( data );
testEnvPlugins.env.tests.plugins = wpEnvConfig.env.tests.plugins;
const currentDirEntry = testEnvPlugins.env.tests.plugins.indexOf( '.' );
const overrideConfig = {};
if ( currentDirEntry !== -1 ) {
testEnvPlugins.env.tests.plugins[ currentDirEntry ] = artifactUrl;
if ( wpEnvConfig.plugins ) {
overrideConfig.plugins = wpEnvConfig.plugins;
}
if ( wpEnvConfig.env?.tests?.plugins ) {
overrideConfig.env = {
tests: {
plugins: wpEnvConfig.env.tests.plugins,
},
};
}
const entriesToReplace = [ '.', '../woocommerce' ];
for ( const entry of entriesToReplace ) {
// Search and replace in root plugins
let found = overrideConfig.plugins.indexOf( entry );
if ( found >= 0 ) {
console.log(
`Replacing ${ entry } with ${ artifactUrl } in root plugins`
);
overrideConfig.plugins[ found ] = artifactUrl;
}
// Search and replace in test env plugins
found = overrideConfig.env?.tests?.plugins?.indexOf( entry );
if ( found >= 0 ) {
console.log(
`Replacing ${ entry } with ${ artifactUrl } in env.tests.plugins`
);
overrideConfig.env.tests.plugins[ found ] = artifactUrl;
}
}
const overrideConfigPath = `${ WP_ENV_CONFIG_PATH }/.wp-env.override.json`;
console.log( `Saving ${ overrideConfigPath }` );
fs.writeFileSync(
`${ WP_ENV_CONFIG_PATH }/.wp-env.override.json`,
JSON.stringify( testEnvPlugins, null, 2 )
overrideConfigPath,
JSON.stringify( overrideConfig, null, 2 )
);

View File

@ -2,30 +2,49 @@
set -eo pipefail
function title() {
echo -e "\n\033[1m$1\033[0m"
}
if [[ -z "$GITHUB_EVENT_NAME" ]]; then
echo "::error::GITHUB_EVENT_NAME must be set"
exit 1
fi
title "Installing NVM"
curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.39.1/install.sh | bash > /dev/null
export NVM_DIR="$HOME/.nvm"
[ -s "$NVM_DIR/nvm.sh" ] && \. "$NVM_DIR/nvm.sh"
echo "Installed version: $(nvm -v)"
title "Installing dependencies"
pnpm install --frozen-lockfile --filter="compare-perf" > /dev/null
if [[ "$GITHUB_EVENT_NAME" == "pull_request" ]]; then
echo "Comparing performance with trunk"
title "Comparing performance with trunk"
pnpm --filter="compare-perf" run compare perf $GITHUB_SHA trunk --tests-branch $GITHUB_SHA
elif [[ "$GITHUB_EVENT_NAME" == "push" ]]; then
echo "Comparing performance with base branch"
# The base hash used here need to be a commit that is compatible with the current WP version
# The current one is 19f3d0884617d7ecdcf37664f648a51e2987cada
# it needs to be updated every time it becomes unsupported by the current wp-env (WP version).
# It is used as a base comparison point to avoid fluctuation in the performance metrics.
title "Comparing performance with base branch"
WP_VERSION=$(awk -F ': ' '/^Tested up to/{print $2}' readme.txt)
# Updating the WP version used for performance jobs means theres a high
# chance that the reference commit used for performance test stability
# becomes incompatible with the WP version. So, every time the "Tested up
# to" flag is updated in the readme.txt, we also have to update the
# reference commit below (BASE_SHA). The new reference needs to meet the
# following requirements:
# - Be compatible with the new WP version used in the “Tested up to” flag.
# - Be tracked on https://www.codevitals.run/project/woo for all existing
# metrics.
BASE_SHA=3d7d7f02017383937f1a4158d433d0e5d44b3dc9
echo "WP_VERSION: $WP_VERSION"
IFS=. read -ra WP_VERSION_ARRAY <<< "$WP_VERSION"
WP_MAJOR="${WP_VERSION_ARRAY[0]}.${WP_VERSION_ARRAY[1]}"
pnpm --filter="compare-perf" run compare perf $GITHUB_SHA 19f3d0884617d7ecdcf37664f648a51e2987cada --tests-branch $GITHUB_SHA --wp-version "$WP_MAJOR"
pnpm --filter="compare-perf" run compare perf $GITHUB_SHA $BASE_SHA --tests-branch $GITHUB_SHA --wp-version "$WP_MAJOR"
echo "Publish results to CodeVitals"
title "Publish results to CodeVitals"
COMMITTED_AT=$(git show -s $GITHUB_SHA --format="%cI")
pnpm --filter="compare-perf" run log $CODEVITALS_PROJECT_TOKEN trunk $GITHUB_SHA 19f3d0884617d7ecdcf37664f648a51e2987cada $COMMITTED_AT
pnpm --filter="compare-perf" run log $CODEVITALS_PROJECT_TOKEN trunk $GITHUB_SHA $BASE_SHA $COMMITTED_AT
else
echo "Unsupported event: $GITHUB_EVENT_NAME"
fi

View File

@ -1,45 +1,51 @@
name: 'Process stale needs-feedback issues'
on:
schedule:
- cron: '21 0 * * *'
schedule:
- cron: '21 0 * * *'
workflow_dispatch:
permissions: {}
permissions: { }
jobs:
stale:
runs-on: ubuntu-20.04
permissions:
contents: read
issues: write
pull-requests: write
steps:
- name: Scan issues
uses: actions/stale@v9.0.0
with:
repo-token: ${{ secrets.GITHUB_TOKEN }}
stale-issue-message: "As a part of this repository's maintenance, this issue is being marked as stale due to inactivity. Please feel free to comment on it in case we missed something.\n\n###### After 7 days with no activity this issue will be automatically be closed."
close-issue-message: 'This issue was closed because it has been 14 days with no activity.'
operations-per-run: 140
days-before-stale: -1
days-before-close: -1
days-before-issue-stale: 7
days-before-issue-close: 7
stale-issue-label: 'status: stale'
stale-pr-label: 'status: stale'
exempt-issue-labels: 'type: enhancement'
only-issue-labels: 'needs: author feedback'
close-issue-label: "status: can't reproduce"
ascending: true
- name: Close Stale Flaky Test Issues
uses: actions/stale@v9.0.0
with:
only-labels: 'metric: flaky e2e test, team: Vortex'
days-before-stale: 5
days-before-close: 2
stale-issue-label: 'metric: stale flaky e2e test report'
stale-issue-message: 'This test may have been a one-time failure. It will be auto-closed if no further activity occurs within the next 2 days.'
close-issue-message: 'Auto-closed due to inactivity. Please re-open if you believe this issue is still valid.'
close-issue-reason: 'not_planned'
remove-stale-when-updated: true
exempt-all-assignees: true
enable-statistics: true
stale:
runs-on: ubuntu-20.04
permissions:
contents: read
issues: write
pull-requests: write
steps:
- name: Scan issues
uses: actions/stale@v9.0.0
with:
repo-token: ${{ secrets.GITHUB_TOKEN }}
stale-issue-message: "As a part of this repository's maintenance, this issue is being marked as stale due to inactivity. Please feel free to comment on it in case we missed something.\n\n###### After 7 days with no activity this issue will be automatically be closed."
close-issue-message: 'This issue was closed because it has been 14 days with no activity.'
operations-per-run: 140
days-before-stale: -1
days-before-close: -1
days-before-issue-stale: 7
days-before-issue-close: 7
stale-issue-label: 'status: stale'
stale-pr-label: 'status: stale'
exempt-issue-labels: 'type: enhancement'
only-issue-labels: 'needs: author feedback'
close-issue-label: "status: can't reproduce"
ascending: true
- name: Process Stale Flaky Test Issues
uses: actions/stale@v9.0.0
with:
repo-token: ${{ secrets.GITHUB_TOKEN }}
only-issue-labels: 'metric: flaky e2e test'
days-before-stale: -1
days-before-close: -1
days-before-issue-stale: 5
days-before-issue-close: 2
stale-issue-label: 'status: stale'
stale-issue-message: 'This issue is being marked as stale due to inactivity. It will be auto-closed if no further activity occurs within the next 2 days.'
close-issue-message: 'Auto-closed due to inactivity. Please re-open if you believe this issue is still valid.'
close-issue-reason: 'not_planned'
remove-stale-when-updated: true
exempt-all-assignees: false
enable-statistics: true
ascending: true
operations-per-run: 120

View File

@ -59,8 +59,8 @@ jobs:
<${{ github.event.pull_request.html_url }}|${{ github.event.pull_request.title }}>
*Labels:* ${{ join(github.event.pull_request.labels.*.name, ', ') }}
*Monthly Release Milestone:* <${{ github.event.pull_request.milestone.html_url }}|${{ github.event.pull_request.milestone.title }}> (Release Date: ${{ env.MILESTONE_DATE }})
*WooAF (weekly) Timeline: this PR can be tested from:* ${{ env.TEST_DATE_MESSAGE }}
Please visit the <#${{ secrets.WOO_CORE_RELEASES_SLACK_CHANNEL }}> to obtain the latest WooAF build for testing.
Please check the Milestone above and test using the latest <https://github.com/woocommerce/woocommerce/releases|pre-release build>.
If a pre-release build for the stated Milestone does not exist, please use the Nightly build.
slack-optional-unfurl_links: false
slack-optional-unfurl_media: false

View File

@ -7,6 +7,7 @@ on:
jobs:
run-tests:
name: 'Run tests'
if: github.repository == 'woocommerce/woocommerce'
uses: ./.github/workflows/ci.yml
with:
trigger: 'daily-checks'

38
.github/workflows/tests-on-demand.yml vendored Normal file
View File

@ -0,0 +1,38 @@
name: 'On demand tests run'
on:
workflow_dispatch:
inputs:
trigger:
type: choice
description: 'Event name: it will be used to filter the jobs to run in ci.yml.'
required: true
options:
- push
- daily-checks
- pre-release
- on-demand
- custom
default: on-demand
custom-trigger:
type: string
description: 'Custom event name: In case the `Event name` choice is `custom`, this field is required.'
required: false
jobs:
validate-input:
runs-on: ubuntu-latest
steps:
- name: 'Validate input'
run: |
if [ "${{ inputs.trigger }}" == "custom" ] && [ -z "${{ inputs.custom-trigger }}" ]; then
echo "Custom event name is required when event name choice `custom`."
exit 1
fi
run-tests:
name: 'Run tests'
uses: ./.github/workflows/ci.yml
with:
trigger: ${{ inputs.trigger == 'custom' && inputs.custom-trigger || inputs.trigger }}
secrets: inherit

View File

@ -1,4 +1,10 @@
#!/bin/sh
#!/usr/bin/env bash
. "$(dirname "$0")/_/husky.sh"
pnpm install --frozen-lockfile
changedManifests=$( ( git diff --name-only HEAD ORIG_HEAD | grep -E '(package.json|pnpm-lock.yaml|pnpm-workspace.yaml|composer.json|composer.lock)$' ) || echo '' )
if [ -n "$changedManifests" ]; then
printf "It was a change in the following file(s) - refreshing dependencies:\n"
printf " %s\n" $changedManifests
pnpm install --frozen-lockfile
fi

View File

@ -12,7 +12,7 @@
"dependencies": [
"pnpm"
],
"pinVersion": "^9.1.0",
"pinVersion": "9.1.3",
"packages": [
"**"
]
@ -41,7 +41,43 @@
"@types/*",
"@typescript-eslint/*",
"@woocommerce/*",
"@wordpress/*",
"@wordpress/api-fetch",
"@wordpress/autop",
"@wordpress/babel-preset-default",
"@wordpress/base-styles",
"@wordpress/block-editor",
"@wordpress/blocks",
"@wordpress/browserslist-config",
"@wordpress/components",
"@wordpress/compose",
"@wordpress/core-data",
"@wordpress/data",
"@wordpress/data-controls",
"@wordpress/date",
"@wordpress/dependency-extraction-webpack-plugin",
"@wordpress/deprecated",
"@wordpress/dom",
"@wordpress/dom-ready",
"@wordpress/e2e-test-utils",
"@wordpress/e2e-test-utils-playwright",
"@wordpress/e2e-tests",
"@wordpress/element",
"@wordpress/html-entities",
"@wordpress/i18n",
"@wordpress/icons",
"@wordpress/is-shallow-equal",
"@wordpress/notices",
"@wordpress/plugins",
"@wordpress/postcss-plugins-preset",
"@wordpress/postcss-themes",
"@wordpress/prettier-config",
"@wordpress/primitives",
"@wordpress/scripts",
"@wordpress/server-side-render",
"@wordpress/style-engine",
"@wordpress/stylelint-config",
"@wordpress/url",
"@wordpress/wordcount",
"babel*",
"eslint*",
"glob*",
@ -52,7 +88,8 @@
"webpack*"
],
"packages": [
"@woocommerce/block-library"
"@woocommerce/block-library",
"@woocommerce/storybook"
],
"isIgnored": true
},
@ -136,7 +173,7 @@
"packages": [
"**"
],
"pinVersion": "^1.45.1"
"pinVersion": "^1.46.1"
},
{
"dependencies": [
@ -163,7 +200,8 @@
"@wordpress/viewport",
"@wordpress/interface",
"@wordpress/router",
"@wordpress/edit-site"
"@wordpress/edit-site",
"@wordpress/private-apis"
],
"packages": [
"@woocommerce/block-templates",
@ -205,9 +243,10 @@
"@wordpress/env"
],
"packages": [
"@woocommerce/block-library",
"**"
],
"pinVersion": "^9.0.7"
"pinVersion": "^10.1.0"
},
{
"dependencies": [
@ -216,7 +255,7 @@
"packages": [
"**"
],
"pinVersion": "wp-6.4"
"pinVersion": "wp-6.6"
},
{
"dependencies": [

View File

@ -4,7 +4,7 @@ This document aims to provide as much context as possible to aid in the developm
## Getting Started
Please refer to [the Getting Started section of the `README.md`](README.md#getting-started) for a general-purpose guide on getting started. The rest of this document will assume that you've installed all of the prequisites and setup described there.
Please refer to [the Getting Started section of the `README.md`](README.md#getting-started) for a general-purpose guide on getting started. The rest of this document will assume that you've installed all of the prerequisites and setup described there.
### Plugin, Package, and Tool Filtering

View File

@ -0,0 +1,44 @@
diff --git a/build-module/lock-unlock.js b/build-module/lock-unlock.js
index 2265f933ceec19f65ca6776c24c3f88b368d713f..e9e10980bfd1b584ab0a037c3b72edae29a2a26e 100644
--- a/build-module/lock-unlock.js
+++ b/build-module/lock-unlock.js
@@ -1,9 +1,34 @@
/**
- * WordPress dependencies
+ * External dependencies
*/
import { __dangerousOptInToUnstableAPIsOnlyForCoreModules } from '@wordpress/private-apis';
-export const {
- lock,
- unlock
-} = __dangerousOptInToUnstableAPIsOnlyForCoreModules('I know using unstable features means my plugin or theme will inevitably break on the next WordPress release.', '@wordpress/edit-site');
+
+// Workaround for Gutenberg private API consent string differences between WP 6.3 and 6.4+
+// The modified version checks for the WP version and replaces the consent string with the correct one.
+// This can be removed once we drop support for WP 6.3 in the "Customize Your Store" task.
+// See this PR for details: https://github.com/woocommerce/woocommerce/pull/40884
+
+const wordPressConsentString = {
+ 6.4: 'I know using unstable features means my plugin or theme will inevitably break on the next WordPress release.',
+ 6.5: 'I know using unstable features means my theme or plugin will inevitably break in the next version of WordPress.',
+ 6.6: 'I acknowledge private features are not for use in themes or plugins and doing so will break in the next version of WordPress.',
+};
+
+function optInToUnstableAPIs() {
+ let error;
+ for ( const optInString of Object.values( wordPressConsentString ) ) {
+ try {
+ return __dangerousOptInToUnstableAPIsOnlyForCoreModules(
+ optInString,
+ '@wordpress/edit-site'
+ );
+ } catch ( anError ) {
+ error = anError;
+ }
+ }
+
+ throw error;
+}
+
+export const { lock, unlock } = optInToUnstableAPIs();
//# sourceMappingURL=lock-unlock.js.map

View File

@ -1,5 +1,600 @@
== Changelog ==
= 9.2.3 2024-08-26 =
**WooCommerce**
* Fix - Ensure translation is fully loaded for certain parts of Checkout block. [#50892](https://github.com/woocommerce/woocommerce/pull/50892)
= 9.2.2 2024-08-22 =
**WooCommerce**
* Fix - Revert PR#48731 to address possible issues with plugins using WC's bundled select2 package. [#50854](https://github.com/woocommerce/woocommerce/pull/50854)
* Fix - Partially revert PR#48709 as it could cause issues for some users of the REST API system_status endpoint. [#50881](https://github.com/woocommerce/woocommerce/pull/50881)
= 9.2.1 2024-08-21 =
**WooCommerce**
* Fix - Revert turning of AccessiblePrivateMethods::_accessible_private_methods into a static property because it caused fatal errors in some edge cases. [#50809](https://github.com/woocommerce/woocommerce/pull/50809)
= 9.2.0 2024-08-20 =
**WooCommerce**
* Update - Enhanced sanitization in `@woocommerce/currency`. [#50802](https://github.com/woocommerce/woocommerce/pull/50802)
* Fix - Hardening against XSS by leveraging HTML API for adding block attribute data. [#50801](https://github.com/woocommerce/woocommerce/pull/50801)
* Fix - Prevent downloads of digitial products after partial refund. [#50804](https://github.com/woocommerce/woocommerce/pull/50804)
* Add - Adds support for tracking downloads when a partial (ranged) request is made. [#50805](https://github.com/woocommerce/woocommerce/pull/50805)
* Update - Turn AccessiblePrivateMethods::_accessible_private_methods into a static property. [#50806](https://github.com/woocommerce/woocommerce/pull/50806)
* Fix - Correct label of shipping dimensions length field. [#50180](https://github.com/woocommerce/woocommerce/pull/50180)
* Fix - Allow new accounts to set new password even if logged in. [#50700](https://github.com/woocommerce/woocommerce/pull/50700)
* Fix - Remove global_unique_id from interface and add warning in case it is not implemented [#50685](https://github.com/woocommerce/woocommerce/pull/50685)
* Fix - CYS: avoid to enqueue Jetpack scripts [#50679](https://github.com/woocommerce/woocommerce/pull/50679)
* Fix - Clear product unique ID (`global_unique_id`) when duplicating products. [#50629](https://github.com/woocommerce/woocommerce/pull/50629)
* Fix - Resolved an issue that caused the page title and content text to display in the incorrect order on the Order Confirmation page. [#50592](https://github.com/woocommerce/woocommerce/pull/50592)
* Fix - Customer Account - Maintain the size of the icon in smaller screens. [#50410](https://github.com/woocommerce/woocommerce/pull/50410)
* Fix - Accessibility: Prevent shipping losing focus when making selections during checkout. [#48370](https://github.com/woocommerce/woocommerce/pull/48370)
* Fix - Add aria-label to mini-cart button on first render to improve accessibility [#48329](https://github.com/woocommerce/woocommerce/pull/48329)
* Fix - Add missing script dependencies to product variation generation script. [#49595](https://github.com/woocommerce/woocommerce/pull/49595)
* Fix - Address timing issue with React 18 when unregistering blocks and add missing dependency to editor bootstrapping code. [#49642](https://github.com/woocommerce/woocommerce/pull/49642)
* Fix - Add the "Customer account" block into the "Minimal Header" to fix the spacing. [#49893](https://github.com/woocommerce/woocommerce/pull/49893)
* Fix - Avoid Product Search Results block template to fall back to the Product Catalog template from the theme [#48887](https://github.com/woocommerce/woocommerce/pull/48887)
* Fix - Changed from using React.render to React.createRoot for product editor areas as it has been deprecated since React 18 [#48834](https://github.com/woocommerce/woocommerce/pull/48834)
* Fix - Check if parent product exists when creating attribute lookup data for variations [#49474](https://github.com/woocommerce/woocommerce/pull/49474)
* Fix - Check if there's an actual session available inside wc_clear_cart_after_payment [#45821](https://github.com/woocommerce/woocommerce/pull/45821)
* Fix - Comment: Update db_version variable and use it to prevent adding global_unique_id when the lookup table was not yet updated [#49472](https://github.com/woocommerce/woocommerce/pull/49472)
* Fix - Correctly escape the HTML when linking customer orders. [#49195](https://github.com/woocommerce/woocommerce/pull/49195)
* Fix - CSY - Fix intro banner copy for existing themes [#49787](https://github.com/woocommerce/woocommerce/pull/49787)
* Fix - CYS - Fix marking the CYS task as completed only by accessing the Intro page. [#49374](https://github.com/woocommerce/woocommerce/pull/49374)
* Fix - CYS - Remove the site title block length from the "Large Header" and the "Centered Menu Header". [#48671](https://github.com/woocommerce/woocommerce/pull/48671)
* Fix - CYS: Disable readonly mode only when full composability feature flag is enabled. [#48752](https://github.com/woocommerce/woocommerce/pull/48752)
* Fix - CYS: Ensure that the button in the Intro page redirects to the Customizer when a classic theme is enabled. [#49804](https://github.com/woocommerce/woocommerce/pull/49804)
* Fix - CYS: fix: Assembler follows admin color schema. [#49159](https://github.com/woocommerce/woocommerce/pull/49159)
* Fix - CYS: fix arrow welcome tour [#49607](https://github.com/woocommerce/woocommerce/pull/49607)
* Fix - CYS: Fix border width pattern preview. [#49753](https://github.com/woocommerce/woocommerce/pull/49753)
* Fix - CYS: Fix button background on Featured Category Cover image [#49659](https://github.com/woocommerce/woocommerce/pull/49659)
* Fix - CYS: fix drag to resize bar [#49657](https://github.com/woocommerce/woocommerce/pull/49657)
* Fix - CYS: fix flickering effect. [#48767](https://github.com/woocommerce/woocommerce/pull/48767)
* Fix - CYS: fix logic to disable click on the no block placeholder [#48722](https://github.com/woocommerce/woocommerce/pull/48722)
* Fix - CYS: Fix no block placeholder style. [#49673](https://github.com/woocommerce/woocommerce/pull/49673)
* Fix - CYS: Fix pattern rendering issues [#49041](https://github.com/woocommerce/woocommerce/pull/49041)
* Fix - CYS: fix pattern wrapped twice by group blocks [#48712](https://github.com/woocommerce/woocommerce/pull/48712)
* Fix - CYS: fix selected header/footer pattern [#49788](https://github.com/woocommerce/woocommerce/pull/49788)
* Fix - CYS: fix shuffle feature logic. [#49153](https://github.com/woocommerce/woocommerce/pull/49153)
* Fix - CYS: fix the default intro pattern. [#49082](https://github.com/woocommerce/woocommerce/pull/49082)
* Fix - CYS: Fix the tooltip overlap with the pattern. [#49700](https://github.com/woocommerce/woocommerce/pull/49700)
* Fix - CYS: fix toolbar position after the site preview resizes [#49028](https://github.com/woocommerce/woocommerce/pull/49028)
* Fix - CYS: hide button to resize the image [#48714](https://github.com/woocommerce/woocommerce/pull/48714)
* Fix - CYS: Hide shuffle button when only one pattern is available [#49790](https://github.com/woocommerce/woocommerce/pull/49790)
* Fix - CYS: not enable PTK features on WordPress 6.5. [#49591](https://github.com/woocommerce/woocommerce/pull/49591)
* Fix - CYS: open Intro panel when user clicks on Design your homepage [#49005](https://github.com/woocommerce/woocommerce/pull/49005)
* Fix - CYS: Remove not necessary placeholder on homepage sidebar. [#49705](https://github.com/woocommerce/woocommerce/pull/49705)
* Fix - CYS: show default TT4 fonts pair. [#49675](https://github.com/woocommerce/woocommerce/pull/49675)
* Fix - CYS: show logo when the header is updated. [#49681](https://github.com/woocommerce/woocommerce/pull/49681)
* Fix - Display "View store" button text by default in the toolbar. [#48690](https://github.com/woocommerce/woocommerce/pull/48690)
* Fix - Display admin notice of expired and expiring Woo subscription when the product
is connected / activated on the site. [#49717](https://github.com/woocommerce/woocommerce/pull/49717)
* Fix - Do not set the `tk_ai` tracking cookie if tracking is disabled. [#47863](https://github.com/woocommerce/woocommerce/pull/47863)
* Fix - Ensure the second address line input appears when using autofill [#49730](https://github.com/woocommerce/woocommerce/pull/49730)
* Fix - Ensure the Store API recalculates cart totals prior to running validation hooks. [#49455](https://github.com/woocommerce/woocommerce/pull/49455)
* Fix - Exclude simple products from variations reports by default. [#49244](https://github.com/woocommerce/woocommerce/pull/49244)
* Fix - Failure to fetch the country list no longer blocks users in the profiler. [#49519](https://github.com/woocommerce/woocommerce/pull/49519)
* Fix - Fetch site cache status correctly if directly navigating to LYS Success page, and some refactoring [#48710](https://github.com/woocommerce/woocommerce/pull/48710)
* Fix - Fix: Make woocommerce/product-price available in the Single Product template [#49906](https://github.com/woocommerce/woocommerce/pull/49906)
* Fix - Fix a bug where woocommerce removes the current-menu-item class. [#45095](https://github.com/woocommerce/woocommerce/pull/45095)
* Fix - Fix add product task to create template first and simplify logic [#49631](https://github.com/woocommerce/woocommerce/pull/49631)
* Fix - Fix add zone button flinching and vertical centering [#48869](https://github.com/woocommerce/woocommerce/pull/48869)
* Fix - Fix Analytics - Tax Report Pagination [#49562](https://github.com/woocommerce/woocommerce/pull/49562)
* Fix - Fix confusing messages prompting switch to classic templates [#48717](https://github.com/woocommerce/woocommerce/pull/48717)
* Fix - Fix default shipping selection when changing between pickup and shipping on block checkout. [#49718](https://github.com/woocommerce/woocommerce/pull/49718)
* Fix - Fixed "woocommerce_new_order" triggering on checkout blocks page visit. [#47422](https://github.com/woocommerce/woocommerce/pull/47422)
* Fix - Fixed a bug causing account email not to be taken in consideration for coupon validation when a customer has a different billing email set. [#48488](https://github.com/woocommerce/woocommerce/pull/48488)
* Fix - Fixed a bug that would cause incorrect pricing at checkout for very large amounts. [#49361](https://github.com/woocommerce/woocommerce/pull/49361)
* Fix - Fixed a bug where the close button is not visible on the mini cart when viewed on a mobile device [#48769](https://github.com/woocommerce/woocommerce/pull/48769)
* Fix - Fixed horizontal and vertical layout overflows on LYS success page [#49127](https://github.com/woocommerce/woocommerce/pull/49127)
* Fix - Fix fatal error in order reports when parent order doesn't exist [#49006](https://github.com/woocommerce/woocommerce/pull/49006)
* Fix - Fix get_options deprecated notice when viewing Analytics > Orders [#49092](https://github.com/woocommerce/woocommerce/pull/49092)
* Fix - Fix Order Count inconsistency between stats and reports [#49283](https://github.com/woocommerce/woocommerce/pull/49283)
* Fix - Fix sidebar attribute control in Products by Attribute block [#49351](https://github.com/woocommerce/woocommerce/pull/49351)
* Fix - Fix site coming soon page heading color [#49129](https://github.com/woocommerce/woocommerce/pull/49129)
* Fix - Fix Task List - Reminder bar close button styling [#49532](https://github.com/woocommerce/woocommerce/pull/49532)
* Fix - Fix the mini cart items not being visible when zoomed in [#48384](https://github.com/woocommerce/woocommerce/pull/48384)
* Fix - Fix the namespace of the RestApiControllerBase class [#49333](https://github.com/woocommerce/woocommerce/pull/49333)
* Fix - Fix the undefined array key "name" warning in ComingSoonRequestHandler.php when the font name is not set [#49795](https://github.com/woocommerce/woocommerce/pull/49795)
* Fix - Fix variation name in analytics variations report [#49440](https://github.com/woocommerce/woocommerce/pull/49440)
* Fix - Issue fixed where tags are overlapping divider line in "Filter by product category". [#48756](https://github.com/woocommerce/woocommerce/pull/48756)
* Fix - Made coupon fields during block checkout stack on smaller screen sizes [#48623](https://github.com/woocommerce/woocommerce/pull/48623)
* Fix - Make sure the correct block template file is used in the Site Editor for templates with fallback [#48621](https://github.com/woocommerce/woocommerce/pull/48621)
* Fix - Make the edit/delete actions of shipping/products in manual orders accessible [#48238](https://github.com/woocommerce/woocommerce/pull/48238)
* Fix - Make the Leaderboards on the Analytics > Dashboard page use consistent currency and number formatting across the page, and perceive the currency setting comes from the relevant filter. [#49097](https://github.com/woocommerce/woocommerce/pull/49097)
* Fix - Narrowed scope of block theme notice templates so other template overrides are unaffected [#48686](https://github.com/woocommerce/woocommerce/pull/48686)
* Fix - Prevent a warning showing when using the Shipping Address Calculator in combination with the additional checkout fields API [#49685](https://github.com/woocommerce/woocommerce/pull/49685)
* Fix - Prevent download permissions metabox from being toggled when toggling individual permission details. [#49022](https://github.com/woocommerce/woocommerce/pull/49022)
* Fix - Prevent possible type error in BatchProcessingController. [#49728](https://github.com/woocommerce/woocommerce/pull/49728)
* Fix - Prevent product editor styles loading on non wc-admin pages [#49170](https://github.com/woocommerce/woocommerce/pull/49170)
* Fix - Product Collection: allow custom collections to hide all of the filter controls, not only some of them [#49713](https://github.com/woocommerce/woocommerce/pull/49713)
* Fix - Product Collection: Fix alignment of the first item in Grid layout for WP 6.6 [#49096](https://github.com/woocommerce/woocommerce/pull/49096)
* Fix - Product Collection: Fix the Preview badge's corner radius [#48856](https://github.com/woocommerce/woocommerce/pull/48856)
* Fix - Product Collection: Show "Sync with current query" option only in archive templates where it makes sense [#48917](https://github.com/woocommerce/woocommerce/pull/48917)
* Fix - Product Fitlers: Bring back pattern [#49601](https://github.com/woocommerce/woocommerce/pull/49601)
* Fix - Product rating - Inherit the color of the star when no ratings [#49678](https://github.com/woocommerce/woocommerce/pull/49678)
* Fix - Provide more informative errors if a refund cannot be requested via the REST API, due to plugin conflicts. [#47918](https://github.com/woocommerce/woocommerce/pull/47918)
* Fix - Redirect the lost password page to edit account while logged in. [#49670](https://github.com/woocommerce/woocommerce/pull/49670)
* Fix - Removes several side effects in the code bases that caused translations to be loaded too early. [#47113](https://github.com/woocommerce/woocommerce/pull/47113)
* Fix - Remove strong tags from patterns [#49901](https://github.com/woocommerce/woocommerce/pull/49901)
* Fix - Replace the red CSS color with the $red SASS variable in WooCommerce legacy elements [#48742](https://github.com/woocommerce/woocommerce/pull/48742)
* Fix - Resolved issues with new order hook triggers during transitions to and from draft statuses. [#49098](https://github.com/woocommerce/woocommerce/pull/49098)
* Fix - Set coming soon preview body aspect ratio to 1/1 to fix broken template [#49749](https://github.com/woocommerce/woocommerce/pull/49749)
* Fix - Show variations only for the selected product's variations [#49470](https://github.com/woocommerce/woocommerce/pull/49470)
* Fix - Tooltips message is now selected based on the order status instead of the label of the order status, which would break if the current WordPress language was not English. Also passes the order object to the woocommerce_get_order_status_labels filter to allow for more personalized tooltips. [#49812](https://github.com/woocommerce/woocommerce/pull/49812)
* Fix - Update allowed statuses in legacy payment handler for checkout block. [#48788](https://github.com/woocommerce/woocommerce/pull/48788)
* Add - Use UTM parameters to link Tracks events from connect notice CTA and successful site connection [#50126](https://github.com/woocommerce/woocommerce/pull/50126)
* Add - Add a generic function to determine remote logging eligibility [#49371](https://github.com/woocommerce/woocommerce/pull/49371)
* Add - Add a rest api to manage the product custom fields [#48504](https://github.com/woocommerce/woocommerce/pull/48504)
* Add - Add column `global_unique_id` to `wc_product_meta_lookup` table
Add global_unique_id field to product and product variations [#49472](https://github.com/woocommerce/woocommerce/pull/49472)
* Add - Added notice to the order confirmation page for new accounts instructing them to change the default password. [#48673](https://github.com/woocommerce/woocommerce/pull/48673)
* Add - Add global unique ID field to the classic product editor [#49312](https://github.com/woocommerce/woocommerce/pull/49312)
* Add - Add placeholder options and validation to checkout country and state select inputs. [#49616](https://github.com/woocommerce/woocommerce/pull/49616)
* Add - Add Refresh Remote Inbox Notifications and Delete Remote Notification Tools [#48961](https://github.com/woocommerce/woocommerce/pull/48961)
* Add - Add some robots.txt rules about directories created by WooCommerce [#49432](https://github.com/woocommerce/woocommerce/pull/49432)
* Add - Adds product usage notice [#47697](https://github.com/woocommerce/woocommerce/pull/47697)
* Add - Add support to run e2e tests against WPCOM website. [#49403](https://github.com/woocommerce/woocommerce/pull/49403)
* Add - Add UTM parameters to missing payment method notice links. [#49621](https://github.com/woocommerce/woocommerce/pull/49621)
* Add - Add validation for `__experimentalRegisterProductCollection` arguments [#48141](https://github.com/woocommerce/woocommerce/pull/48141)
* Add - CYS: add badge that informs how many patterns have been inserted from each category. [#48668](https://github.com/woocommerce/woocommerce/pull/48668)
* Add - CYS: Add default patterns. [#48839](https://github.com/woocommerce/woocommerce/pull/48839)
* Add - CYS: Add Tracking for Fiverr Logo Maker CTA [#49783](https://github.com/woocommerce/woocommerce/pull/49783)
* Add - CYS: Enable the PTK feature. [#49565](https://github.com/woocommerce/woocommerce/pull/49565)
* Add - Expose __experimentalRegisterProductCollection in @woocommerce/blocks-registry Package [#48141](https://github.com/woocommerce/woocommerce/pull/48141)
* Add - Improvements in the handling of feature compatibility for plugins [#48169](https://github.com/woocommerce/woocommerce/pull/48169)
* Add - Product Collection: Rename "Sync with current query" option to "Use page context" and make it working in non-archive context as well [#49627](https://github.com/woocommerce/woocommerce/pull/49627)
* Update - Add pattern validation for global_unique_id [#50501](https://github.com/woocommerce/woocommerce/pull/50501)
* Update - Clear global_unique_id when restoring a product that doesn't have an unique id [#50496](https://github.com/woocommerce/woocommerce/pull/50496)
* Update - Use admin password reset on admin login screen [#50200](https://github.com/woocommerce/woocommerce/pull/50200)
* Update - Prevent creation of password-protected coupons. [#50236](https://github.com/woocommerce/woocommerce/pull/50236)
* Update - Add a link to the Theming docs from the blockified templates README.md file [#48538](https://github.com/woocommerce/woocommerce/pull/48538)
* Update - Add a new icon style to the "Customer Account" block. [#48979](https://github.com/woocommerce/woocommerce/pull/48979)
* Update - Adds setting to control the visibility of product count in Mini cart block [#48545](https://github.com/woocommerce/woocommerce/pull/48545)
* Update - Add tracking for enable auto renew links on notices [#49710](https://github.com/woocommerce/woocommerce/pull/49710)
* Update - Add UTM parameters to subscription renewal notice links. [#49645](https://github.com/woocommerce/woocommerce/pull/49645)
* Update - Adjust input field height and input label text size. [#49636](https://github.com/woocommerce/woocommerce/pull/49636)
* Update - Adjust top margin of the coupon code in the Cart and Checkout blocks. [#49603](https://github.com/woocommerce/woocommerce/pull/49603)
* Update - CYS - Add borders to footer and header patterns on the assembler. [#49299](https://github.com/woocommerce/woocommerce/pull/49299)
* Update - CYS - Add missing patterns to their categories for the assembler [#49154](https://github.com/woocommerce/woocommerce/pull/49154)
* Update - CYS - Add tracking events to pattern features. [#49556](https://github.com/woocommerce/woocommerce/pull/49556)
* Update - CYS - Disable the Full Composability for CYS AI flows [#49290](https://github.com/woocommerce/woocommerce/pull/49290)
* Update - CYS - Fetch patterns from the private dotcom patterns category instead of from the default source site. [#49007](https://github.com/woocommerce/woocommerce/pull/49007)
* Update - CYS - Fetch patterns from the WooCommerce PTK source site. [#48492](https://github.com/woocommerce/woocommerce/pull/48492)
* Update - CYS - Filter out patterns with external dependencies. [#48618](https://github.com/woocommerce/woocommerce/pull/48618)
* Update - CYS - Fix CSS spacing issues in the assembler. [#49232](https://github.com/woocommerce/woocommerce/pull/49232)
* Update - CYS - Fix dark patterns buttons color. [#49181](https://github.com/woocommerce/woocommerce/pull/49181)
* Update - CYS - Fix the column spacing for the "Four Image Grid Content Left" pattern [#49669](https://github.com/woocommerce/woocommerce/pull/49669)
* Update - CYS - Fix the font size of the "DON'T HAVE A LOGO YET?" title. [#49231](https://github.com/woocommerce/woocommerce/pull/49231)
* Update - CYS - Fix the intro cards size to match the designs. [#49297](https://github.com/woocommerce/woocommerce/pull/49297)
* Update - CYS - Fix the pattern preview border color on hover and for inserted patterns. [#49206](https://github.com/woocommerce/woocommerce/pull/49206)
* Update - CYS - Improve margins for CYS core patterns. [#49196](https://github.com/woocommerce/woocommerce/pull/49196)
* Update - CYS - Improve the designs of the Intro page bottom cards. [#48983](https://github.com/woocommerce/woocommerce/pull/48983)
* Update - CYS - Include the dotcom patterns from the "Reviews" category. [#49140](https://github.com/woocommerce/woocommerce/pull/49140)
* Update - CYS - Make some titles bold on CYS patterns. [#49151](https://github.com/woocommerce/woocommerce/pull/49151)
* Update - CYS - Make the patterns content translatable for patterns in the dictionary. [#49633](https://github.com/woocommerce/woocommerce/pull/49633)
* Update - CYS - Register PTK "Testimonials" patterns as "Reviews" [#48674](https://github.com/woocommerce/woocommerce/pull/48674)
* Update - CYS - Remove non-default patterns and register them from the PTK. Update margins. [#49101](https://github.com/woocommerce/woocommerce/pull/49101)
* Update - CYS - Schedule the `fetch_patterns` actions only once every hour. [#49754](https://github.com/woocommerce/woocommerce/pull/49754)
* Update - CYS - Update pattern categories and its descriptions. [#48665](https://github.com/woocommerce/woocommerce/pull/48665)
* Update - CYS - Update pattern toolbar delete button copy to `Delete`. [#49295](https://github.com/woocommerce/woocommerce/pull/49295)
* Update - CYS - Update the full composability layout styles [#49303](https://github.com/woocommerce/woocommerce/pull/49303)
* Update - CYS - Update the intro pages for different type of themes. [#49910](https://github.com/woocommerce/woocommerce/pull/49910)
* Update - CYS: Add the proper tracking string to the external Fiverr link in sidebar of the **Add your logo** screen. [#49745](https://github.com/woocommerce/woocommerce/pull/49745)
* Update - CYS: Add `rel="noreferrer"` to External Fiverr Link in sidebar of **Add your logo** screen. [#49314](https://github.com/woocommerce/woocommerce/pull/49314)
* Update - CYS: Improve Block Toolbar logic. [#48799](https://github.com/woocommerce/woocommerce/pull/48799)
* Update - CYS: improve copy no blocks placeholder. [#49030](https://github.com/woocommerce/woocommerce/pull/49030)
* Update - CYS: Improve patterns order [#49204](https://github.com/woocommerce/woocommerce/pull/49204)
* Update - CYS: no highlight the pattern when it is added. [#48802](https://github.com/woocommerce/woocommerce/pull/48802)
* Update - CYS: Remove margin last pattern preview [#49767](https://github.com/woocommerce/woocommerce/pull/49767)
* Update - CYS: Remove not necessary patterns. [#48750](https://github.com/woocommerce/woocommerce/pull/48750)
* Update - CYS: Revisit sidebar layout. [#48803](https://github.com/woocommerce/woocommerce/pull/48803)
* Update - CYS: Update Block Toolbar Position [#48662](https://github.com/woocommerce/woocommerce/pull/48662)
* Update - CYS: Update icon used by the "Customer account" block into header patterns [#49133](https://github.com/woocommerce/woocommerce/pull/49133)
* Update - CYS: Update sidebar homepage copy [#48882](https://github.com/woocommerce/woocommerce/pull/48882)
* Update - CYS: Update verbiage in the CTA to our Fiverr Logo Maker landing page. [#48987](https://github.com/woocommerce/woocommerce/pull/48987)
* Update - CYS: when the footer/header is clicked, the border color is blue. [#48765](https://github.com/woocommerce/woocommerce/pull/48765)
* Update - Deprecate and create new coming soon block version [#49786](https://github.com/woocommerce/woocommerce/pull/49786)
* Update - E2E: check the `Add` button when creating product variations in the new Product Editor [#48928](https://github.com/woocommerce/woocommerce/pull/48928)
* Update - E2E: in the new Product Editor app, update how to detect when global attributes are loaded. [#48915](https://github.com/woocommerce/woocommerce/pull/48915)
* Update - E2E: remove UI check when creating attribute global terms [#48934](https://github.com/woocommerce/woocommerce/pull/48934)
* Update - Ensure expiration-related modal is shown to the installed Woo subscriptions [#49747](https://github.com/woocommerce/woocommerce/pull/49747)
* Update - Ensures the product ID is valid when interacting with product variations via the REST API. [#48804](https://github.com/woocommerce/woocommerce/pull/48804)
* Update - Ensure that active plugins shown in the System Status api endpoint actually exist [#48709](https://github.com/woocommerce/woocommerce/pull/48709)
* Update - Ensuring product creation with unique sku for concurrent requests [#47476](https://github.com/woocommerce/woocommerce/pull/47476)
* Update - Fix: Show preview label only when Product Collection block is selected [#48795](https://github.com/woocommerce/woocommerce/pull/48795)
* Update - Fix Classic Template block registration on WP 6.6 [#48730](https://github.com/woocommerce/woocommerce/pull/48730)
* Update - Fix typo on Congratulations screen [#49233](https://github.com/woocommerce/woocommerce/pull/49233)
* Update - Hide account creation options not relevent to block checkout when using block checkout. [#49389](https://github.com/woocommerce/woocommerce/pull/49389)
* Update - Improve rendering of order list table on mobile. [#49592](https://github.com/woocommerce/woocommerce/pull/49592)
* Update - Improve the handling of the deprecated WC()->api property [#48884](https://github.com/woocommerce/woocommerce/pull/48884)
* Update - Make proceed to order button non sticky when zoom level is bigger than 100% [#48391](https://github.com/woocommerce/woocommerce/pull/48391)
* Update - Make Single Product gallery thumbnail images sharper by defining a srcset [#49112](https://github.com/woocommerce/woocommerce/pull/49112)
* Update - Migrate the cart and checkout block's state, country and custom field input to a native select [#48180](https://github.com/woocommerce/woocommerce/pull/48180)
* Update - Move remote logger to `./src` and improve `fetch_latest_woocommerce_version()` logic [#49639](https://github.com/woocommerce/woocommerce/pull/49639)
* Update - Optimize the method that gets the downloads count for a given download [#49008](https://github.com/woocommerce/woocommerce/pull/49008)
* Update - preparing checkout blocks docs for dev docs site [#49010](https://github.com/woocommerce/woocommerce/pull/49010)
* Update - Product Collection: revert renaming "Sync with current query" option [#49907](https://github.com/woocommerce/woocommerce/pull/49907)
* Update - Product Editor: improve E2E tests. Test the `+3 More` item label in the Organization tab [#48891](https://github.com/woocommerce/woocommerce/pull/48891)
* Update - Product Editor: restore and fix E2E test that creates product variations [#48725](https://github.com/woocommerce/woocommerce/pull/48725)
* Update - Product Editor: restore Product (local) Attributes E2E test [#48871](https://github.com/woocommerce/woocommerce/pull/48871)
* Update - Product Editor: update create product variations E2E test [#48627](https://github.com/woocommerce/woocommerce/pull/48627)
* Update - Redesigned the Product Collection block's insertion journey. [#48911](https://github.com/woocommerce/woocommerce/pull/48911)
* Update - Remove Jetpack copy experiment from core profiler [#49452](https://github.com/woocommerce/woocommerce/pull/49452)
* Update - Remove the hooked blocks feature gate and replace with wc_hooked_blocks_version option [#49302](https://github.com/woocommerce/woocommerce/pull/49302)
* Update - Replace the "Customer account" line logo. [#49666](https://github.com/woocommerce/woocommerce/pull/49666)
* Update - Return HTTP 404 for REST API requests involving non-existing tax class. [#48579](https://github.com/woocommerce/woocommerce/pull/48579)
* Update - Return HTTP 404 when accessing non-existent webhooks via REST API. [#48729](https://github.com/woocommerce/woocommerce/pull/48729)
* Update - Return HTTP 404 when trying to read or delete a non-existent product review. [#48726](https://github.com/woocommerce/woocommerce/pull/48726)
* Update - Run full e2e tests suite against Pressable and WPCOM websites. [#49597](https://github.com/woocommerce/woocommerce/pull/49597)
* Update - Update content for usage tracking modal for CYS experience [#49911](https://github.com/woocommerce/woocommerce/pull/49911)
* Update - Updated account settings descriptions for added clarity [#48556](https://github.com/woocommerce/woocommerce/pull/48556)
* Update - Update Jetpack's new SSO classes and methods to prevent deprecation notice. [#49752](https://github.com/woocommerce/woocommerce/pull/49752)
* Update - Update required and tested up to WP versions for the WordPress 6.6 release. [#49619](https://github.com/woocommerce/woocommerce/pull/49619)
* Update - Update Settings to disable Save button unless modifications are made. [#47444](https://github.com/woocommerce/woocommerce/pull/47444)
* Update - Update shipping method setup modal copy if the block-based local pickup is enabled [#48529](https://github.com/woocommerce/woocommerce/pull/48529)
* Update - Update Store Alert styles [#49174](https://github.com/woocommerce/woocommerce/pull/49174)
* Update - Update Store Alert widths to match main body [#48487](https://github.com/woocommerce/woocommerce/pull/48487)
* Update - Update the "Customer Account" block icon for the line style. [#49401](https://github.com/woocommerce/woocommerce/pull/49401)
* Update - Update the CYS opt-in messaging [#49894](https://github.com/woocommerce/woocommerce/pull/49894)
* Update - Update the footer section in "Add products" task [#49782](https://github.com/woocommerce/woocommerce/pull/49782)
* Update - Update WC Tasks in the WC Home. Rename to WooCommerce marketplace, add new browse marketplace, remove connect to woocomerce.com from inbox [#48128](https://github.com/woocommerce/woocommerce/pull/48128)
* Update - Utilize the new shared component to showcase WooPayments payment method logos. [#49300](https://github.com/woocommerce/woocommerce/pull/49300)
* Dev - Add Allure to Blocks e2e tests [#49228](https://github.com/woocommerce/woocommerce/pull/49228)
* Dev - Add daily checks for core e2e with PHP 8.1 and WP latest-1 [#48929](https://github.com/woocommerce/woocommerce/pull/48929)
* Dev - Add hook to customize the rendered receipt template [#48872](https://github.com/woocommerce/woocommerce/pull/48872)
* Dev - Add new CI workflow to trigger tests on demand. [#49674](https://github.com/woocommerce/woocommerce/pull/49674)
* Dev - Add support for e2e testing against external sites in CI [#49017](https://github.com/woocommerce/woocommerce/pull/49017)
* Dev - Another attempt to stabilize flaky Product Collection E2E tests. [#49638](https://github.com/woocommerce/woocommerce/pull/49638)
* Dev - Blocks E2E: Fix a flaky Product Collection test where accidental multiple edits occur and break the template saving step. [#49590](https://github.com/woocommerce/woocommerce/pull/49590)
* Dev - Blocks E2E: Fix DB snapshot removal step in setup script. [#49677](https://github.com/woocommerce/woocommerce/pull/49677)
* Dev - Build: speedup dependencies installation by disabling composer optimize autoloading by default. [#48980](https://github.com/woocommerce/woocommerce/pull/48980)
* Dev - CI: buffix for linting missing strict types directive. [#49015](https://github.com/woocommerce/woocommerce/pull/49015)
* Dev - CI: cleanup CI related command after fixing jobs matrix generation. [#49330](https://github.com/woocommerce/woocommerce/pull/49330)
* Dev - CI: code style fixes to pass linting in updated CI environment. [#49020](https://github.com/woocommerce/woocommerce/pull/49020)
* Dev - CI: improve flacky tests reporting job execution time. [#49665](https://github.com/woocommerce/woocommerce/pull/49665)
* Dev - CI: Re-group PHPUnit jobs. [#49443](https://github.com/woocommerce/woocommerce/pull/49443)
* Dev - CI: reduce running time for PHPUnit related jobs. [#49193](https://github.com/woocommerce/woocommerce/pull/49193)
* Dev - CI: tuning deps caching for playwright. [#49081](https://github.com/woocommerce/woocommerce/pull/49081)
* Dev - CI config: update changes lists to include wp-env config [#49626](https://github.com/woocommerce/woocommerce/pull/49626)
* Dev - Clean up unused files in plugins/woocommerce-blocks [#49319](https://github.com/woocommerce/woocommerce/pull/49319)
* Dev - Create a separate JS cart and checkout JavaScript bundle to improve performance. [#48010](https://github.com/woocommerce/woocommerce/pull/48010)
* Dev - CYS - Fix the "test_fetch_patterns_should_register_testimonials_category_as_reviews" tests. [#48719](https://github.com/woocommerce/woocommerce/pull/48719)
* Dev - Dropping select2 and point it to SelectWoo [#48731](https://github.com/woocommerce/woocommerce/pull/48731)
* Dev - E2E: enable slow tests reporting for blocks E2E tests. [#49367](https://github.com/woocommerce/woocommerce/pull/49367)
* Dev - E2E tests: fix basic spec for multiple environments [#49609](https://github.com/woocommerce/woocommerce/pull/49609)
* Dev - E2E tests: fix failing settings-tax e2e test [#48792](https://github.com/woocommerce/woocommerce/pull/48792)
* Dev - E2E tests: Fix flaky account email receiving test [#48957](https://github.com/woocommerce/woocommerce/pull/48957)
* Dev - E2E tests: Fix flaky connect to Woo.com test [#48926](https://github.com/woocommerce/woocommerce/pull/48926)
* Dev - E2E tests: Fix flaky filling regular price in the inventory tab [#49226](https://github.com/woocommerce/woocommerce/pull/49226)
* Dev - E2E tests: Fix flaky filling SKU field and CYS footer [#49191](https://github.com/woocommerce/woocommerce/pull/49191)
* Dev - E2E tests: Fix flaky Gutenberg, WC Services tests [#48916](https://github.com/woocommerce/woocommerce/pull/48916)
* Dev - E2E tests: Fix flaky Gutenberg tests [#48896](https://github.com/woocommerce/woocommerce/pull/48896)
* Dev - E2E tests: Fix flaky Gutenberg tests [#49548](https://github.com/woocommerce/woocommerce/pull/49548)
* Dev - E2E tests: Fix flaky logo picker waiting for response tests [#49451](https://github.com/woocommerce/woocommerce/pull/49451)
* Dev - E2E tests: Fix flaky merchant filling sku field in the new editor [#49134](https://github.com/woocommerce/woocommerce/pull/49134)
* Dev - E2E tests: Fix flaky merchant tests [#49381](https://github.com/woocommerce/woocommerce/pull/49381)
* Dev - E2E tests: Fix merchant settings general test [#48907](https://github.com/woocommerce/woocommerce/pull/48907)
* Dev - E2E tests: fix shopper checkout block test [#49596](https://github.com/woocommerce/woocommerce/pull/49596)
* Dev - E2E tests: fix some tests for WP 6.6 [#49634](https://github.com/woocommerce/woocommerce/pull/49634)
* Dev - E2E tests: tag different envs in e2e test suite to run in workflows [#48715](https://github.com/woocommerce/woocommerce/pull/48715)
* Dev - Final sanity check to make sure attributes are done saving [#48737](https://github.com/woocommerce/woocommerce/pull/48737)
* Dev - Fix broken syntax in e2e-guidelines.md. [#49018](https://github.com/woocommerce/woocommerce/pull/49018)
* Dev - Fix flaky orphaned refund test [#49741](https://github.com/woocommerce/woocommerce/pull/49741)
* Dev - Hide product filters overlay template part experimental feature from public release [#49564](https://github.com/woocommerce/woocommerce/pull/49564)
* Dev - In blocks codebase, export SITE_CURRENCY property with properties matching typescript definitions. [#48727](https://github.com/woocommerce/woocommerce/pull/48727)
* Dev - Lint new PHP files for strict types directive [#48943](https://github.com/woocommerce/woocommerce/pull/48943)
* Dev - Minor tooling tweaks (zip compression level, composer invocation) [#48857](https://github.com/woocommerce/woocommerce/pull/48857)
* Dev - Monorepo: enable Jest and babel-loader caching. [#49656](https://github.com/woocommerce/woocommerce/pull/49656)
* Dev - Monorepo: fix side-effects of setting strict mode for linting script. [#49436](https://github.com/woocommerce/woocommerce/pull/49436)
* Dev - Monorepo: minor tweaks in zip building script (use frozen lock file when installing dependecies). [#49640](https://github.com/woocommerce/woocommerce/pull/49640)
* Dev - Monorepo: refine approach to patching dependecies in favour of built-in pnpm functionality. [#49892](https://github.com/woocommerce/woocommerce/pull/49892)
* Dev - Monorepo: set strict mode for linting script. [#49366](https://github.com/woocommerce/woocommerce/pull/49366)
* Dev - Monorepo: tweak patching dependencies for better Webpack perfromance. [#49703](https://github.com/woocommerce/woocommerce/pull/49703)
* Dev - Move buildkite-test-collector to devDependencies [#49051](https://github.com/woocommerce/woocommerce/pull/49051)
* Dev - move docs out of main folder until subcategories are ready [#49354](https://github.com/woocommerce/woocommerce/pull/49354)
* Dev - Product Collection: add tracking for block usage [#46466](https://github.com/woocommerce/woocommerce/pull/46466)
* Dev - Remove performance tests from PR checks (leave on push to trunk) [#48927](https://github.com/woocommerce/woocommerce/pull/48927)
* Dev - Switch `render()` to `createRoot().render()` to use React 18 features. [#48858](https://github.com/woocommerce/woocommerce/pull/48858)
* Dev - Tests: pin wp-env core version to 6.5 (temporary until tests are fixed to pass with 6.6) [#49620](https://github.com/woocommerce/woocommerce/pull/49620)
* Dev - Tweaks related to caching Composer dependecies and Playwright downloads in CI. [#48865](https://github.com/woocommerce/woocommerce/pull/48865)
* Dev - Update Action Scheduler to 3.8.1 [#49483](https://github.com/woocommerce/woocommerce/pull/49483)
* Dev - Update a few e2e tests failing on the daily run [#49313](https://github.com/woocommerce/woocommerce/pull/49313)
* Dev - Update all values to be random so that retries don't fail on assertions [#48734](https://github.com/woocommerce/woocommerce/pull/48734)
* Dev - Updated CodeSniffer configuration to address conflicting rules. [#49183](https://github.com/woocommerce/woocommerce/pull/49183)
* Dev - Update Playwright from 1.44 to 1.45 [#49202](https://github.com/woocommerce/woocommerce/pull/49202)
* Tweak - Add admin_install_timestamp in WC_Tracker [#50076](https://github.com/woocommerce/woocommerce/pull/50076)
* Tweak - Add $wpdb->esc_like to the search criteria when searching for a product custom field name [#48949](https://github.com/woocommerce/woocommerce/pull/48949)
* Tweak - Add the initially installed WooCommerce version to the wp_options table [#49139](https://github.com/woocommerce/woocommerce/pull/49139)
* Tweak - Change CLIRunner namespace for better PSR compatibility. [#49390](https://github.com/woocommerce/woocommerce/pull/49390)
* Tweak - Equalize data in Order export with data in Client side CSV export [#49356](https://github.com/woocommerce/woocommerce/pull/49356)
* Tweak - Exclude coming soon patterns from block inserter [#48821](https://github.com/woocommerce/woocommerce/pull/48821)
* Tweak - Fix tip block syntax in register-product-collection.md [#49785](https://github.com/woocommerce/woocommerce/pull/49785)
* Tweak - Get tax line label instead of name in StoreAPI Order endpoint. [#48445](https://github.com/woocommerce/woocommerce/pull/48445)
* Tweak - Improve checks when offering to remove test orders [#49032](https://github.com/woocommerce/woocommerce/pull/49032)
* Tweak - Initialize BlockTemplatesController for block themes only. [#48905](https://github.com/woocommerce/woocommerce/pull/48905)
* Tweak - Product Collection: flatten telemetry query filters data to json string [#49680](https://github.com/woocommerce/woocommerce/pull/49680)
* Tweak - Remove enctype from verify email form [#48859](https://github.com/woocommerce/woocommerce/pull/48859)
* Tweak - Remove unneeded IE styling as IE is no longer supported [#49027](https://github.com/woocommerce/woocommerce/pull/49027)
* Tweak - Rename Google Listings and Ads with Google for WooCommerce [#47614](https://github.com/woocommerce/woocommerce/pull/47614)
* Tweak - Show Guest when there is no Customer name [#49594](https://github.com/woocommerce/woocommerce/pull/49594)
* Tweak - Trigger doing_it_wrong() when using HPOS query args for CPT order queries. [#47457](https://github.com/woocommerce/woocommerce/pull/47457)
* Tweak - Update text to Content right with image left pattern [#49792](https://github.com/woocommerce/woocommerce/pull/49792)
* Tweak - Update the "API enabled" entry in the System Status Report to clarify that it pertains to the Legacy REST API. [#48878](https://github.com/woocommerce/woocommerce/pull/48878)
* Tweak - Add placeholder options and validation to all checkout select inputs. [#49929](https://github.com/woocommerce/woocommerce/pull/49929)
* Performance - Load REST API namespaces only when needed. [#47704](https://github.com/woocommerce/woocommerce/pull/47704)
* Performance - Reduced number of recalculations on Store API cart routes [#48944](https://github.com/woocommerce/woocommerce/pull/48944)
* Enhancement - Add address title to edit/add buttons on My Account page [#49171](https://github.com/woocommerce/woocommerce/pull/49171)
* Enhancement - Added password field to block checkout (when enabled in settings) for new accounts to set a custom password. [#48985](https://github.com/woocommerce/woocommerce/pull/48985)
* Enhancement - Add required indication to login forms [#48743](https://github.com/woocommerce/woocommerce/pull/48743)
* Enhancement - Add scope attributes to the order table on My Account [#49201](https://github.com/woocommerce/woocommerce/pull/49201)
* Enhancement - Add strength meter to block checkout password field. [#49164](https://github.com/woocommerce/woocommerce/pull/49164)
* Enhancement - Allow blocks with parents in the "woocommerce" namespace to be added to the Checkout block without requiring them to be added to the "__experimental_woocommerce_blocks_add_data_attributes_to_block" hook. [#48543](https://github.com/woocommerce/woocommerce/pull/48543)
* Enhancement - Convert edit address link to a button on checkout [#49471](https://github.com/woocommerce/woocommerce/pull/49471)
* Enhancement - CYS: make the entire shuffle section clickable. [#48889](https://github.com/woocommerce/woocommerce/pull/48889)
* Enhancement - CYS: Remove iframe animation [#48941](https://github.com/woocommerce/woocommerce/pull/48941)
* Enhancement - Made the "return to cart" link (in the checkout block) hidden by default. [#48762](https://github.com/woocommerce/woocommerce/pull/48762)
* Enhancement - Provide the location context within the Product Collection block context [#44145](https://github.com/woocommerce/woocommerce/pull/44145)
* Enhancement - Updated block checkout and Store API stock handling so stock is only reserved when attempting payment for an order. [#49446](https://github.com/woocommerce/woocommerce/pull/49446)
= 9.1.4 2024-07-26 =
**WooCommerce**
* Fix - Revert fixing terms count in tracking PR as it caused product_add_publish to be triggered more than usual. [#49797](https://github.com/woocommerce/woocommerce/pull/49797)
* Fix - Hardening against XSS via the Product Button unescaped attribute. [#50010](https://github.com/woocommerce/woocommerce/pull/50010)
* Fix - Enhance escaping for block attributes. [#50015](https://github.com/woocommerce/woocommerce/pull/50015)
= 9.1.2 2024-07-12 =
**WooCommerce**
* Fix - Revert 46857 to preserve backcompat with earlier WC versions. [#48753](https://github.com/woocommerce/woocommerce/pull/48753)
= 9.1.1 2024-07-11 =
**WooCommerce**
* Tweak - Revert #46262, as that PR would render input values invisible under certain conditions. [49404](https://github.com/woocommerce/woocommerce/pull/49404)
= 9.1.0 2024-07-10 =
**WooCommerce**
* Fix - Prevent HTML tags being rendered on order confirmation and emails [#49370](https://github.com/woocommerce/woocommerce/pull/49370)
* Security - Improve the way we cache information about recent customer activity, to prevent the wrong data being retrieved in some specific conditions involving multisite networks. [#49373](https://github.com/woocommerce/woocommerce/pull/49373)
* Fix - Prevent BatchProcessingController from cleaning up processors after a premature shutdown. [#49243](https://github.com/woocommerce/woocommerce/pull/49243)
* Fix - CYS: fix not template set correctly. [#49113](https://github.com/woocommerce/woocommerce/pull/49113)
* Fix - CYS: Disable readonly mode only when full composability feature flag is enabled. [#48752](https://github.com/woocommerce/woocommerce/pull/48752)
* Fix - CYS: fix crash of CYS on WordPress 6.6 [#48664](https://github.com/woocommerce/woocommerce/pull/48664)
* Fix - Revert "Set stock quantity value as 0 by default (#48448)" #48863 [#48863](https://github.com/woocommerce/woocommerce/pull/48863)
* Fix - Add product id to product_edit_view track in classic product edit screen [#47853](https://github.com/woocommerce/woocommerce/pull/47853)
* Fix - Address responsiveness issues in orders list table. [#47684](https://github.com/woocommerce/woocommerce/pull/47684)
* Fix - Add screen-reader-text styles to e-mails. [#47738](https://github.com/woocommerce/woocommerce/pull/47738)
* Fix - Adds new hook `woocommerce_rest_delete_shipping_zone_method` which will fire after a shipping zone method is deleted via the REST API. [#47862](https://github.com/woocommerce/woocommerce/pull/47862)
* Fix - Allow products with non-integer stock to be created via REST API. [#48541](https://github.com/woocommerce/woocommerce/pull/48541)
* Fix - Calling $product->get_status() after $product->save() on a new product now returns correct status. [#48241](https://github.com/woocommerce/woocommerce/pull/48241)
* Fix - Change the cursor to a pointer when hovering over the mini cart [#46996](https://github.com/woocommerce/woocommerce/pull/46996)
* Fix - CYS - Hovering over the header or footer on the "Design your homepage" section should not make them highlighted. [#48358](https://github.com/woocommerce/woocommerce/pull/48358)
* Fix - CYS - Select the next block after deleting the selected one (instead of the header). [#48316](https://github.com/woocommerce/woocommerce/pull/48316)
* Fix - CYS: apply white color to the heading elements in the core/cover block. [#48447](https://github.com/woocommerce/woocommerce/pull/48447)
* Fix - CYS: Fix crash homepage. [#48205](https://github.com/woocommerce/woocommerce/pull/48205)
* Fix - CYS: Fix CSS header. [#48389](https://github.com/woocommerce/woocommerce/pull/48389)
* Fix - CYS: fix logic to disable mover buttons. [#48502](https://github.com/woocommerce/woocommerce/pull/48502)
* Fix - CYS: fix tooltip position. [#48495](https://github.com/woocommerce/woocommerce/pull/48495)
* Fix - CYS: hide popover when the mouse pointer leaves the site preview and then back. [#48394](https://github.com/woocommerce/woocommerce/pull/48394)
* Fix - Do not create empty webhooks after failure to deliver deleted webhook. [#48480](https://github.com/woocommerce/woocommerce/pull/48480)
* Fix - Ensure attribute slugs with multibyte characters are handled property when outputting attributes in the REST API products endpoint [#48198](https://github.com/woocommerce/woocommerce/pull/48198)
* Fix - Ensure available stock is updated correctly when updating line items in orders via the REST API. [#47784](https://github.com/woocommerce/woocommerce/pull/47784)
* Fix - Ensure data filtered by `woocommerce_logger_log_message` does not carry across multiple log handlers [#48336](https://github.com/woocommerce/woocommerce/pull/48336)
* Fix - Ensure getPreviousDate default behaviour is comparing previous_year [#47951](https://github.com/woocommerce/woocommerce/pull/47951)
* Fix - Ensure permission checks for the customer downloads REST API endpoint use the correct customer ID. [#47854](https://github.com/woocommerce/woocommerce/pull/47854)
* Fix - Ensure that data containing multibyte characters and/or slashes that is appended to log entries gets encoded and rendered correctly [#48341](https://github.com/woocommerce/woocommerce/pull/48341)
* Fix - Fix a bug with the woocommerce_get_default_value_for_{key} filter that was preventing setting a falsey value on a checkbox (i.e. to uncheck it dynamically) [#48031](https://github.com/woocommerce/woocommerce/pull/48031)
* Fix - Fix activation limit for single license subscriptions on woocommerce.com [#47643](https://github.com/woocommerce/woocommerce/pull/47643)
* Fix - Fix a null parameter being passed into strpos in Admin/Orders/PageController.php [#48476](https://github.com/woocommerce/woocommerce/pull/48476)
* Fix - Fix bug where Core Profiler initiates a Jetpack connection even if it was already connected before [#48345](https://github.com/woocommerce/woocommerce/pull/48345)
* Fix - Fix bumped down data when analytics chart current period contains 29th Feb [#45874](https://github.com/woocommerce/woocommerce/pull/45874)
* Fix - Fix coming soon footer banner doesn't display properly on tablet and mobile [#47980](https://github.com/woocommerce/woocommerce/pull/47980)
* Fix - Fix e2e tests about the tabs selection during the product creation experience [#47860](https://github.com/woocommerce/woocommerce/pull/47860)
* Fix - Fix edit variable product test [#48288](https://github.com/woocommerce/woocommerce/pull/48288)
* Fix - Fix FlexSlider thumbnail animation for variable products with default form values on small devices. </details> <details> [#48137](https://github.com/woocommerce/woocommerce/pull/48137)
* Fix - Fix location settings not updated in tax task [#48606](https://github.com/woocommerce/woocommerce/pull/48606)
* Fix - Fix LYS private link URL parameter regardless of permalink settings [#48425](https://github.com/woocommerce/woocommerce/pull/48425)
* Fix - Fix product archive page not hidden behind the coming soon page [#48522](https://github.com/woocommerce/woocommerce/pull/48522)
* Fix - Fix Product Gallery block error on revisiting Single Product template without fully reloading the page. [#47636](https://github.com/woocommerce/woocommerce/pull/47636)
* Fix - Fix product tracks when importing #47857 [#47857](https://github.com/woocommerce/woocommerce/pull/47857)
* Fix - Fix some issues in performance tests #47735 [#47735](https://github.com/woocommerce/woocommerce/pull/47735)
* Fix - Fix the issue that the React-powered admin routing pages added after the filter initialization could not be displayed. [#47696](https://github.com/woocommerce/woocommerce/pull/47696)
* Fix - Fix the terms counts in wcadmin_product_add_publish event. [#48194](https://github.com/woocommerce/woocommerce/pull/48194)
* Fix - Fix two products being added to cart when Geolocate (with page caching support) was enabled and AJAX add to cart buttons disabled [#47761](https://github.com/woocommerce/woocommerce/pull/47761)
* Fix - Fix untranslated strings on CYS and marketplace [#48127](https://github.com/woocommerce/woocommerce/pull/48127)
* Fix - Honor empty "additional content" setting in e-mails. [#47809](https://github.com/woocommerce/woocommerce/pull/47809)
* Fix - Improve consistency of Setting-> Gateway Manage button for WooPayments gateway [#48212](https://github.com/woocommerce/woocommerce/pull/48212)
* Fix - In general, the `last_access` field of a REST API key should only be updated once-per-request.
* Fix - Make coupon metadata read robust against wrongly stored product related metadata [#48362](https://github.com/woocommerce/woocommerce/pull/48362)
* Fix - Moved WooCommerce block categories registration on the server-side, fixing a bug that would show warnings to developers trying to hook new blocks in such categories. [#47836](https://github.com/woocommerce/woocommerce/pull/47836)
* Fix - Possible availability of unpublished coupons on sites with an object cache has been addressed through improved cache management. [#47739](https://github.com/woocommerce/woocommerce/pull/47739)
* Fix - Prefer update URLs over PluginURI in My Subscriptions for plugins without a subscription. [#47950](https://github.com/woocommerce/woocommerce/pull/47950)
* Fix - Prevent on-sale badge from showing on top of the coming soon banner. [#48082](https://github.com/woocommerce/woocommerce/pull/48082)
* Fix - Prevent Product Gallery from being inserted on Posts and Pages. [#48228](https://github.com/woocommerce/woocommerce/pull/48228)
* Fix - Product Collection: prevent throwing warnings in some circumstances when rendering block [#48530](https://github.com/woocommerce/woocommerce/pull/48530)
* Fix - Product Price: Narrow down the ancestors of the block so it's available in inserter only in places where block makes sense [#47802](https://github.com/woocommerce/woocommerce/pull/47802)
* Fix - Re-enable variable product E2E test #48294 [#48294](https://github.com/woocommerce/woocommerce/pull/48294)
* Fix - Related Products: hides unusable options from Inspector Controls [#47845](https://github.com/woocommerce/woocommerce/pull/47845)
* Fix - Run possibly_add_template_id function in woocommerce_rest_prepare_product_variation_object hook [#48325](https://github.com/woocommerce/woocommerce/pull/48325)
* Fix - Scroll to view the templates section on the status page [#48125](https://github.com/woocommerce/woocommerce/pull/48125)
* Fix - Set stock quantity value as 0 by default #48448 [#48448](https://github.com/woocommerce/woocommerce/pull/48448)
* Fix - Update plugin installation error logger to use plugin track key for extension name [#47786](https://github.com/woocommerce/woocommerce/pull/47786)
* Fix - When a product attribute is updated, unchanged values should not be reset to their defaults. [#48120](https://github.com/woocommerce/woocommerce/pull/48120)
* Fix - WooCommerce: fixes the checks when migrating the product form template [#48386](https://github.com/woocommerce/woocommerce/pull/48386)
* Fix - [CYS Full Composability] Ensure that the assembler doesn't crash when the feature flag is enabled, but the site doesn't have the latest version of Gutenberg. [#47546](https://github.com/woocommerce/woocommerce/pull/47546)
* Add - Add CLI tools for the product attributes lookup table [#47311](https://github.com/woocommerce/woocommerce/pull/47311)
* Add - Add 'woocommerce_order_note_deleted' hook for order note deletions. [#47916](https://github.com/woocommerce/woocommerce/pull/47916)
* Add - Add CLI tools to enable and disable HPOS compatibility mode. [#48117](https://github.com/woocommerce/woocommerce/pull/48117)
* Add - Added 'woocommerce_restore_order_item_stock' filter for restored line item stock on canceled orders [#40848](https://github.com/woocommerce/woocommerce/pull/40848)
* Add - Add ErrorBoundary component for handling unexpect errors [#48250](https://github.com/woocommerce/woocommerce/pull/48250)
* Add - Add filter to dynamically exclude a page from Coming soon mode [#47787](https://github.com/woocommerce/woocommerce/pull/47787)
* Add - Add Printful product placement to Add Products task [#48520](https://github.com/woocommerce/woocommerce/pull/48520)
* Add - Add skipped test custom reporter to surface skipped tests in CI runs [#48195](https://github.com/woocommerce/woocommerce/pull/48195)
* Add - Add the ability to test experimental blocks via the Advanced > Features menu of WooCommerce settings. [#47701](https://github.com/woocommerce/woocommerce/pull/47701)
* Add - Add woocommerce_manage_stock option to the default_option_permissions list in the Options rest controller [#48239](https://github.com/woocommerce/woocommerce/pull/48239)
* Add - CYS: add CTA to our Fiverr Logo Maker landing page. [#48486](https://github.com/woocommerce/woocommerce/pull/48486)
* Add - CYS: add pattern category in the block toolbar. [#48501](https://github.com/woocommerce/woocommerce/pull/48501)
* Add - CYS: Add the Delete button to the Block Toolbar. [#48143](https://github.com/woocommerce/woocommerce/pull/48143)
* Add - CYS: Ensure that toolbar appears only when the homepage sidebar is open. [#48115](https://github.com/woocommerce/woocommerce/pull/48115)
* Add - CYS: Show Patterns from PTK. [#48207](https://github.com/woocommerce/woocommerce/pull/48207)
* Add - CYS: Show popover when the user clicks on the pattern [#47583](https://github.com/woocommerce/woocommerce/pull/47583)
* Add - Determine _product_template_id from 'woocommerce_product_editor_determine_product_template' filter [#47762](https://github.com/woocommerce/woocommerce/pull/47762)
* Add - Display an admin notice in Setting and Extension pages when there are expiring subscriptions and connected account doesn't have a payment method. [#47141](https://github.com/woocommerce/woocommerce/pull/47141)
* Add - Enhancements to background batch processing. [#48078](https://github.com/woocommerce/woocommerce/pull/48078)
* Add - Highlight the pattern when the user hovers it. [#47415](https://github.com/woocommerce/woocommerce/pull/47415)
* Add - LYS - Add 'Remove test orders' for WooPayments [#47832](https://github.com/woocommerce/woocommerce/pull/47832)
* Add - PFT: introduce controller and initialize it [#48221](https://github.com/woocommerce/woocommerce/pull/48221)
* Add - REST API: extened shipping_classes namespace with the /suggest-slug endpoint [#47896](https://github.com/woocommerce/woocommerce/pull/47896)
* Add - Updated shipstation copy [#48549](https://github.com/woocommerce/woocommerce/pull/48549)
* Add - WooCommerce: create a new product_form CPT [#48073](https://github.com/woocommerce/woocommerce/pull/48073)
* Add - WooCommerce: introduce `product-editor-template-system` feature flag [#48136](https://github.com/woocommerce/woocommerce/pull/48136)
* Add - WooCommerce: update CPT product_form posts when plugin updates [#48265](https://github.com/woocommerce/woocommerce/pull/48265)
* Add - WooCommerce Blocks: Added a GitHub Action to create issues for flaky E2E tests [#47758](https://github.com/woocommerce/woocommerce/pull/47758)
* Update - Add feature flag for Printful placement [#49104](https://github.com/woocommerce/woocommerce/pull/49104)
* Update - Add a control to enable a separator on the Checkout block's "Checkout Terms" block. This will enable a separator above the block that can be turned off in case the block is moved. [#47565](https://github.com/woocommerce/woocommerce/pull/47565)
* Update - Change the item schemas for Orders and Order Refunds API endpoints to correctly specify that the rate_id property in a tax_line object is an integer, not a string [#47779](https://github.com/woocommerce/woocommerce/pull/47779)
* Update - Clean up theming sections in WooCommerce blocks docs [#48420](https://github.com/woocommerce/woocommerce/pull/48420)
* Update - CYS - Exclude two testimonials patterns from registering since they depend on Jetpack. [#48233](https://github.com/woocommerce/woocommerce/pull/48233)
* Update - CYS - Fix active/inactive patterns for each of the sections in the assembler. [#48458](https://github.com/woocommerce/woocommerce/pull/48458)
* Update - CYS - Install the patterns during the CYS flow if the transient is not set. [#48274](https://github.com/woocommerce/woocommerce/pull/48274)
* Update - CYS - Redirect to the same section after installing fonts or patterns on the assembler. [#48227](https://github.com/woocommerce/woocommerce/pull/48227)
* Update - CYS - Show tooltips on the Shuffle and Delete buttons in the assembler toolbar. [#48465](https://github.com/woocommerce/woocommerce/pull/48465)
* Update - CYS: set new default patterns. [#48467](https://github.com/woocommerce/woocommerce/pull/48467)
* Update - Display return to cart link on mobile devices. [#48103](https://github.com/woocommerce/woocommerce/pull/48103)
* Update - Docs: update documentation regarding Compatibility Layer [#48456](https://github.com/woocommerce/woocommerce/pull/48456)
* Update - Expand block templates documentation [#48247](https://github.com/woocommerce/woocommerce/pull/48247)
* Update - Experimental blocks now have "(Experimental)" suffix [#48071](https://github.com/woocommerce/woocommerce/pull/48071)
* Update - fix: label improvement on my order page template [#48374](https://github.com/woocommerce/woocommerce/pull/48374)
* Update - Improve WooCommerce block template names in the Add New Template screen. [#48106](https://github.com/woocommerce/woocommerce/pull/48106)
* Update - Invalidate cache for SiteGround Speed Optimizer [#48523](https://github.com/woocommerce/woocommerce/pull/48523)
* Update - Optimize the regeneration of the product attributes lookup table [#47700](https://github.com/woocommerce/woocommerce/pull/47700)
* Update - Product Archive templates: Replace the default block from Products (Beta) to Product Collection block [#48112](https://github.com/woocommerce/woocommerce/pull/48112)
* Update - Product Block Editor: disable the `product-editor-template-system` feature flag as default, even for the development environment. [#48378](https://github.com/woocommerce/woocommerce/pull/48378)
* Update - Product Collection: Handpicked Products filter now allows searching from 2 characters and more and updates available results as you type [#48379](https://github.com/woocommerce/woocommerce/pull/48379)
* Update - Product Elements: hide Product Summary from Single Product block and only show Excerpt variation [#48253](https://github.com/woocommerce/woocommerce/pull/48253)
* Update - Product Rating Stars and Product Rating Counter from the inserter [#48229](https://github.com/woocommerce/woocommerce/pull/48229)
* Update - Products (Beta): hide block from inserter in favor of Product Collection block [#48204](https://github.com/woocommerce/woocommerce/pull/48204)
* Update - Product Summary: Increase the length of the description from 55 to 100 words (max supported by core/post-excerpt) [#47651](https://github.com/woocommerce/woocommerce/pull/47651)
* Update - Reduced the number of FlexSlider animation engines from 2 to 1, now always using CSS3 transitions. [#46564](https://github.com/woocommerce/woocommerce/pull/46564)
* Update - Replace the use of options endpoint with the LYS API endpoint to query woocommerce_admin_launch_your_store_survey_completed option. [#47915](https://github.com/woocommerce/woocommerce/pull/47915)
* Update - The archive product title will now be updated to the title of the current shop
page. If the page does not exist, it will fall back to "Shop". [#48255](https://github.com/woocommerce/woocommerce/pull/48255)
* Update - Toggle LYS feature flag on for 9.1 [#48244](https://github.com/woocommerce/woocommerce/pull/48244)
* Update - Update input fields styles of the Checkout block [#46362](https://github.com/woocommerce/woocommerce/pull/46362)
* Update - WooCommerce: store the template description in the `product_form` excerpt property. [#48327](https://github.com/woocommerce/woocommerce/pull/48327)
* Update - Wrap activity panels in error boundary [#48415](https://github.com/woocommerce/woocommerce/pull/48415)
* Update - [CYS] Ensure fetch PTK patterns requests are always done async to improve performance. [#47551](https://github.com/woocommerce/woocommerce/pull/47551)
* Update - [CYS] Refactor the pattern registration and add patterns from the PTK API. [#47306](https://github.com/woocommerce/woocommerce/pull/47306)
* Update - [CYS] Remove the restriction to TT4 and allow users to proceed to the pattern assembler with any block themes. Update intro page design. [#46916](https://github.com/woocommerce/woocommerce/pull/46916)
* Update - [CYS] Show a message when tracking is not allowed in patterns and add the ability for users to opt-in and fetch patterns. </details> <details> [#48095](https://github.com/woocommerce/woocommerce/pull/48095)
* Dev - Improve E2E selector by making it stricter. Wait for text due to AJAX call. [#48471](https://github.com/woocommerce/woocommerce/pull/48471)
* Dev - Added e2e test to check ability to connect to woocommerce.com [#48028](https://github.com/woocommerce/woocommerce/pull/48028)
* Dev - Added test enviornments [#48101](https://github.com/woocommerce/woocommerce/pull/48101)
* Dev - Add previous error class to checkout endpoint response [#47489](https://github.com/woocommerce/woocommerce/pull/47489)
* Dev - Add test for wcpay_connect_account_clicked track [#48347](https://github.com/woocommerce/woocommerce/pull/48347)
* Dev - Add tests for some product editor tracks [#48245](https://github.com/woocommerce/woocommerce/pull/48245)
* Dev - Blocks E2E: Remove confusing utilities in favor of native locator functionality. [#47904](https://github.com/woocommerce/woocommerce/pull/47904)
* Dev - CI: merge test jobs [#48175](https://github.com/woocommerce/woocommerce/pull/48175)
* Dev - Clean up eslint comments after rules update in Blocks E2E tests. [#47875](https://github.com/woocommerce/woocommerce/pull/47875)
* Dev - Clean up tasklist progression headercard experiment [#47983](https://github.com/woocommerce/woocommerce/pull/47983)
* Dev - Clean up welcome modal code [#48346](https://github.com/woocommerce/woocommerce/pull/48346)
* Dev - Do not dismiss the error snackbar automatically, fix E2E test #48192 [#48192](https://github.com/woocommerce/woocommerce/pull/48192)
* Dev - E2E test: Improve analytics data spec by disabling the task list reminder bar [#48357](https://github.com/woocommerce/woocommerce/pull/48357)
* Dev - E2E tests: configure snapshotPathTemplate [#47773](https://github.com/woocommerce/woocommerce/pull/47773)
* Dev - E2E tests: fixing flakiness in checkout block and launch your store tests [#48016](https://github.com/woocommerce/woocommerce/pull/48016)
* Dev - E2E tests: fixing flaky assembler homepage test [#48356](https://github.com/woocommerce/woocommerce/pull/48356)
* Dev - E2E tests: fixing flaky checkout block test [#48527](https://github.com/woocommerce/woocommerce/pull/48527)
* Dev - E2E tests: fixing flaky color palette picker test [#48496](https://github.com/woocommerce/woocommerce/pull/48496)
* Dev - E2E tests: fixing flaky connect to woo test [#48613](https://github.com/woocommerce/woocommerce/pull/48613)
* Dev - E2E tests: fixing flaky customize store transitional test [#48532](https://github.com/woocommerce/woocommerce/pull/48532)
* Dev - E2E tests: fixing flaky logo picker test [#48503](https://github.com/woocommerce/woocommerce/pull/48503)
* Dev - E2E tests: fixing flaky merchant create variable product test [#48276](https://github.com/woocommerce/woocommerce/pull/48276)
* Dev - E2E tests: fixing flaky merchant customer list test [#48463](https://github.com/woocommerce/woocommerce/pull/48463)
* Dev - E2E tests: fixing flaky merchant product attribute test [#48230](https://github.com/woocommerce/woocommerce/pull/48230)
* Dev - E2E tests: fixing flaky merchant user create and logging [#48446](https://github.com/woocommerce/woocommerce/pull/48446)
* Dev - E2E tests: fixing flaky shopper checkout coupons [#48555](https://github.com/woocommerce/woocommerce/pull/48555)
* Dev - E2E tests: fixing flaky shopper search browse products in the shop [#48560](https://github.com/woocommerce/woocommerce/pull/48560)
* Dev - E2E tests: fixing flaky store owner core profiler test [#48430](https://github.com/woocommerce/woocommerce/pull/48430)
* Dev - E2E tests: fixing skipped mini cart test [#47756](https://github.com/woocommerce/woocommerce/pull/47756)
* Dev - E2E tests: fixing skipped tests [#47859](https://github.com/woocommerce/woocommerce/pull/47859)
* Dev - E2E tests: improve existing merchant e2e tests for creating page and post [#48162](https://github.com/woocommerce/woocommerce/pull/48162)
* Dev - E2E tests: improve existing util for inserting blocks via shortcut [#48225](https://github.com/woocommerce/woocommerce/pull/48225)
* Dev - E2E tests: improving cart util and updating relevant tests [#48475](https://github.com/woocommerce/woocommerce/pull/48475)
* Dev - E2E tests: updated the test ignore pattern for Gutenberg tests project [#47764](https://github.com/woocommerce/woocommerce/pull/47764)
* Dev - E2E tests: update tests checking if blocks can be added [#48211](https://github.com/woocommerce/woocommerce/pull/48211)
* Dev - E2E tests: update the report configuration for all core jobs [#48424](https://github.com/woocommerce/woocommerce/pull/48424)
* Dev - Fix a filters block e2e test that was mistakenly merged incorrectly. [#48122](https://github.com/woocommerce/woocommerce/pull/48122)
* Dev - Fixing a flaky core profiler e2e test [#47917](https://github.com/woocommerce/woocommerce/pull/47917)
* Dev - Fix path to test results for api core tests [#48490](https://github.com/woocommerce/woocommerce/pull/48490)
* Dev - Implement unit test for tracks wcadmin_page_view, wcadmin_tasklist_view, wcadmin_tasklist_task_completed, wcadmin_tasklist_click [#47876](https://github.com/woocommerce/woocommerce/pull/47876)
* Dev - Include blocks e2e in ci.yml [#48224](https://github.com/woocommerce/woocommerce/pull/48224)
* Dev - Migrate release smoke workflow to the new CI setup [#48113](https://github.com/woocommerce/woocommerce/pull/48113)
* Dev - Product Editor: Move variation pricing fields to General tab. [#48155](https://github.com/woocommerce/woocommerce/pull/48155)
* Dev - Remove the isFeaturePlugin function, which was used to turn off experimental block styling (but was non functional). Also remove associated code in FeatureGating class. [#47866](https://github.com/woocommerce/woocommerce/pull/47866)
* Dev - Remove WOOCOMMERCE_BLOCKS_PHASE completely from the monorepo, introduce BUNDLE_EXPERIMENTAL_BLOCKS just for the purpose of building/bundling experimental blocks [#47807](https://github.com/woocommerce/woocommerce/pull/47807)
* Dev - Skipped flaky test: test_order_updated_webhook_delivered_once [#48064](https://github.com/woocommerce/woocommerce/pull/48064)
* Dev - Streamline the implementation of the Blocks' E2E utilities. [#47660](https://github.com/woocommerce/woocommerce/pull/47660)
* Dev - Streamline the usage of WP CLI in Blocks E2E tests. [#47869](https://github.com/woocommerce/woocommerce/pull/47869)
* Dev - Tweak the paths that should trigger e2e tests. [#48067](https://github.com/woocommerce/woocommerce/pull/48067)
* Dev - Unskip some tests that have been skipped for flakiness [#47772](https://github.com/woocommerce/woocommerce/pull/47772)
* Dev - Update @wordpress/env version to 9.7.0 [#48443](https://github.com/woocommerce/woocommerce/pull/48443)
* Dev - Updated Core Profilers XState version to V5 [#48135](https://github.com/woocommerce/woocommerce/pull/48135)
* Dev - Update Playwright from 1.41.1 to 1.44.1 (latest) and fixed tests [#48291](https://github.com/woocommerce/woocommerce/pull/48291)
* Dev - Update pnpm-lock with updated React [#47973](https://github.com/woocommerce/woocommerce/pull/47973)
* Dev - Update the React version in the pnpm-lock file [#47993](https://github.com/woocommerce/woocommerce/pull/47993)
* Dev - Update the URLs for order-related e2e tests to use new URLs from HPOS [#46397](https://github.com/woocommerce/woocommerce/pull/46397)
* Dev - [e2e tests] Fix e2e test reports paths [#48320](https://github.com/woocommerce/woocommerce/pull/48320)
* Tweak - Update Printful label [#48778](https://github.com/woocommerce/woocommerce/pull/48778)
* Tweak - Add a close button to dismiss store alerts [#48453](https://github.com/woocommerce/woocommerce/pull/48453)
* Tweak - Adds a defensive check to reduce error log noise when regenerating images. [#47785](https://github.com/woocommerce/woocommerce/pull/47785)
* Tweak - Adds best practice advice to the API key generation screen. [#48483](https://github.com/woocommerce/woocommerce/pull/48483)
* Tweak - CYS - Update the copy for the intro tour. [#48202](https://github.com/woocommerce/woocommerce/pull/48202)
* Tweak - CYS: Refactor routing approach. [#48312](https://github.com/woocommerce/woocommerce/pull/48312)
* Tweak - Include 'original_post_status' in HPOS edit form. [#48196](https://github.com/woocommerce/woocommerce/pull/48196)
* Tweak - Minor improvements to BlockTemplatesController instantiation [#48107](https://github.com/woocommerce/woocommerce/pull/48107)
* Tweak - Only load 'productCount' and 'experimentalBlocksEnabled' settings in admin [#48152](https://github.com/woocommerce/woocommerce/pull/48152)
* Tweak - Product Editor: Skip momentarily the 'can create a variation option and publish the product' E2E test [#47618](https://github.com/woocommerce/woocommerce/pull/47618)
* Tweak - Remove checkstyle.xml file [#47844](https://github.com/woocommerce/woocommerce/pull/47844)
* Tweak - Remove unused woocommerce_task_list_prompt_shown option [#48304](https://github.com/woocommerce/woocommerce/pull/48304)
* Tweak - Update coming soon banner text to use translation function [#47742](https://github.com/woocommerce/woocommerce/pull/47742)
* Tweak - Update LYS survey completion track props [#47985](https://github.com/woocommerce/woocommerce/pull/47985)
* Tweak - Update printful copy. [#48626](https://github.com/woocommerce/woocommerce/pull/48626)
* Tweak - Update WC blocks e2e tests to WordPress 6.6 [#48436](https://github.com/woocommerce/woocommerce/pull/48436)
* Tweak - Verify if the coming soon cache is displayed when launching the store and alerts the user if it is still present. [#48586](https://github.com/woocommerce/woocommerce/pull/48586)
* Performance - Add DISTINCT keyword for smaller response and performance. [#48139](https://github.com/woocommerce/woocommerce/pull/48139)
* Performance - CYS - Optimize the `Choose a professionally designed theme` intro page image. [#48566](https://github.com/woocommerce/woocommerce/pull/48566)
* Performance - Replaced `classnames` package with the faster and smaller `clsx` package. [#47760](https://github.com/woocommerce/woocommerce/pull/47760)
* Performance - Revert changing the title of the edit comments screen when editing a review. [#48485](https://github.com/woocommerce/woocommerce/pull/48485)
* Enhancement - Accessibility enhancement for the whole shop accounts section [#47144](https://github.com/woocommerce/woocommerce/pull/47144)
* Enhancement - Add information about block/shortcode/template usage on Cart and Checkout pages to the WC system report. [#48300](https://github.com/woocommerce/woocommerce/pull/48300)
* Enhancement - CYS: add shuffle feature. [#47356](https://github.com/woocommerce/woocommerce/pull/47356)
* Enhancement - CYS: allow to the user to move the pattern. [#47322](https://github.com/woocommerce/woocommerce/pull/47322)
* Enhancement - Enhancement editor loading speed [#47425](https://github.com/woocommerce/woocommerce/pull/47425)
* Enhancement - Handle core profiler get countries error [#48317](https://github.com/woocommerce/woocommerce/pull/48317)
* Enhancement - If a variable product doesn't have a Product Image but variations do have images, the zoom and flex slider will be initiated as expected [#47714](https://github.com/woocommerce/woocommerce/pull/47714)
* Enhancement - Improve spacing between steps in the Checkout block on mobile and desktop [#47565](https://github.com/woocommerce/woocommerce/pull/47565)
* Enhancement - Increase connection timeout to 30 seconds for the requests in WCCOM connection flow [#47842](https://github.com/woocommerce/woocommerce/pull/47842)
* Enhancement - Limit coming soon options API call to home screen [#48303](https://github.com/woocommerce/woocommerce/pull/48303)
* Enhancement - Modified order status tooltip labels [#47861](https://github.com/woocommerce/woocommerce/pull/47861)
* Enhancement - Optimize text wrapping for wc admin pages [#48131](https://github.com/woocommerce/woocommerce/pull/48131)
* Enhancement - Remove the previous product management experience [#47814](https://github.com/woocommerce/woocommerce/pull/47814)
= 9.0.2 2024-06-24 =
**WooCommerce**
@ -5651,12 +6246,12 @@
* Dev - Revert work done in #4857 for automated shipping after OBW is completed #5971
* Add - Welcome modal when coming from Calypso #6004
* Enhancement - Add an a/b experiment for installing free business features #5786
* Dev - Add `onChangeCallback` feature to the wc-admin `<Form>` component #5786
* Dev - Add `onChangeCallback` feature to the wc-admin `<Form>` component #5786
* Fix - Generate JSON translation chunks on plugin activation #6028
* Dev - Add merchant email notifications #5922
* Dev - Add merchant email notifications #5922
* Add - Email note to add first product. #6024
* Add - Note for users coming from Calypso. #6030
* Enhancement - Add an "unread" indicator to inbox messages. #6047
* Enhancement - Add an "unread" indicator to inbox messages. #6047
* Add - Manage activity from home screen inbox message. #6072
= 4.9.5 2022-03-10 =
@ -6459,7 +7054,7 @@
* Fix - The WCPay method not appearing as recommended sometimes #4345
* Fix - Removed URLSearchParams method #4501
* Fix - REST API collections schema. #4484
* Fix - null issue in wpNavMenuClassChange #4513 🎉 gradosevic
* Fix - null issue in wpNavMenuClassChange #4513 🎉 gradosevic
* Fix - RTL stylesheet loading for split code chunks. #4542
* Fix - Don't show store location step in tax and shipping tasks if the address has already been provided #4507
* Fix - Check for enabled methods before payment task completion #4530
@ -6601,7 +7196,7 @@
* Dev - Fixed failing unit tests. #105
**WooCommerce Admin 1.2.3**
* Enhancement - Add onboarding payments note #4157
* Enhancement - Add onboarding payments note #4157
* Enhancement - Marketing Inbox Note #4030
* Performance - Use Route based code splitting to reduce bundle size #4094
* Performance - trim down inbox note API request. #3977
@ -7012,7 +7607,7 @@
* Dev - Add a filter `woocommerce_ajax_add_order_item_validation` to allow validations in `add_order_item` function. #24518
* Dev - Use `wc_get_cart_url` instead of `wc_get_page_permalink( 'cart' )` because former has a filter `woocommerce_get_cart_url` to allow customization. #24530
* Dev - New `woocommerce_product_after_tabs` action hook added. #24694
* Dev - Enable append hashes on custom events (like ajax requests) #24665
* Dev - Enable append hashes on custom events (like ajax requests) #24665
* Dev - Introduced `woocommerce_order_get_formatted_billing_address` and `woocommerce_order_get_formatted_shipping_address` filters. #24677
* Dev - WC_Abstract_Order::recalculate_coupons() is public now. #24740
* Dev - Added 'applied_coupon' trigger to checkout.js. #24406
@ -7125,7 +7720,7 @@
* Tweak - Update the generate username setting description label to reflect how the username is actually generated. #23911
* Tweak - OBW: Adjust plugin highlight container sizes to avoid overlap. #23997
* Tweak - Round tax amounts late when the round at subtotal level setting is enabled to reduce rounding errors. #24024
* Tweak - OBW: Now includes WooCommerce Admin as a recommended plugin. #24058
* Tweak - OBW: Now includes WooCommerce Admin as a recommended plugin. #24058
* Template - Review and update all template files escaping. #23460
* Template - Remove mention of shipping section from the checkout/form-login.php template as shipping is not always a requirement for an order. #23941
* Template - Add new filter `woocommerce_before_thankyou` to the checkout/thankyou.php template. #23538
@ -7797,7 +8392,7 @@
* Fix - Fix warning when using logger instance in woocommerce_logging_class filter. #21448
* Fix - Use uppercase "ID" when sorting product queries by ID. #21461
* Fix - Consistently escape the gateway ID in the checkout payment method template. #21439
* Fix - Avoid treating HTTP 301 and 302 codes as failures for webhooks. #21491
* Fix - Avoid treating HTTP 301 and 302 codes as failures for webhooks. #21491
* Fix - Add address_1 to shipping packages info in WC_Cart:: get_shipping_packages to make it work correctly in address formatting functions. #21493
* Fix - Don't fire two of the same action when saving shipping settings. #21494
* Fix - Remove double condition for address line 2 in `WC_Countries::get_default_address_fields`. #20629
@ -8109,7 +8704,7 @@
* Fix - Delete orphaned variations after product import. #19378
* Fix - Ensure API credentials exist before defining PayPal refund support. #19380
* Fix - Force word-wrapping in the log viewer to prevent layout-breaking long lines. #19503
* Fix - Removes permission checks that were preventing webhooks from displaying properly when no post object existed. #19508
* Fix - Removes permission checks that were preventing webhooks from displaying properly when no post object existed. #19508
* Fix - Empty cart after completing PayPal payment. #19509
* Fix - Strip tags on aria-labels in Add to Cart template to prevent broken HTML. #19522
* Fix - Update post_modified date when saving products and variations but no other product data. #19595
@ -8131,7 +8726,7 @@
* Fix - WC API should not try to create a product image when creating a product variation if an empty image is passed. #19971
* Fix - Force settings API settings to autoload by default. #19998
* Fix - Cart html5 validation events when using keyboard. #20001
* Fix - Don't show stock status fields in external product quick-edit. #20005
* Fix - Don't show stock status fields in external product quick-edit. #20005
* Fix - Prevent an infinite loop if 2 grouped products are linked. #20020
* Fix - Switch stock_status when manage stock gets changed to prevent being out of stock if stock quantity is > 0. #20021
* Fix - When duplicating variation, set the date to null. #20083
@ -8393,7 +8988,7 @@
* Fix - is_visible should ensure product is is not trashed before returning true.
* Fix - Return packages with no rates back to the cart so the shipping calculator is displayed even when the current country is not shippable.
* Fix - Merge session and persistent carts when both exists after login.
* Fix - Remove "wc_error" query string after login.
* Fix - Remove "wc_error" query string after login.
* Fix - Allow woocommerce_form_field() have 'custom_attributes' equal 0.
* Fix - Bulk actions in status logs table.
* Fix - Exclude add-to-cart from pagination links.
@ -8434,19 +9029,19 @@
* Fix - Removed class within class in admin meta boxes HTML.
* Fix - Fixed wrong `flex-control-nav` selector scope in `add-to-cart-variation.js`
* Fix - Allow variations to be added to cart from query string.
* Fix - Use `add_filter` for `comment_feed_where` hook.
* Fix - Use `add_filter` for `comment_feed_where` hook.
* Fix - Change nocache_headers hook firing in the cache helper.
* Fix - Coupon min/max spend based on displayed subtotal.
* Fix - Fix event propagation on click in setup wizard and improve validation.
* Fix - API - Change how line items are saved in API so calculations are correct.
* Tweak - Hide downloads from admin emails.
* Tweak - Hide downloads from admin emails.
* Tweak - Set placeholder for variation lxwxh field to that of the parent.
* Tweak - Improve the Add Payment Methods display so buttons are not shown when no payment methods support the feature.
* Localization - Update NJ tax rate.
* Localization - Add Belarusian ruble BYN.
= 3.2.3 - 2017-11-02 =
* Fix - Fixed a conflict with some slider plugins due to sanitization of archive/term descriptions.
* Fix - Fixed a conflict with some slider plugins due to sanitization of archive/term descriptions.
* Fix - Fixed a flexslider bug when there is only 1 image on the product page (no gallery).
* Fix - Prevent potential notices when someone extends product tabs wrongly.
* Fix - Fixed display of shipping calculator under some conditions.

View File

@ -3,7 +3,7 @@
"MD003": { "style": "atx" },
"MD007": { "indent": 4 },
"MD013": { "line_length": 9999 },
"MD024": { "allow_different_nesting": true },
"MD024": { "siblings_only": true },
"MD033": { "allowed_elements": ["video"] },
"MD035": false,
"MD041": false,

View File

@ -0,0 +1,5 @@
---
category_title: Block Theme Development
category_slug: block-theme-development
post_title: Block theme development
---

View File

@ -0,0 +1,84 @@
---
post_title: Cart and checkout blocks theming
menu_title: Cart and Checkout Blocks Theming
tags: reference
---
> [!IMPORTANT]
> We strongly discourage writing CSS code based on existing block class names and prioritize using global styles when possible. We especially discourage writing CSS selectors that rely on a specific block being a descendant of another one, as users can move blocks around freely, so they are prone to breaking. Similar to WordPress itself, we consider the HTML structure within components, blocks, and block templates to be "private", and subject to further change in the future, so using CSS to target the internals of a block or a block template is _not recommended or supported_.
## Buttons
WC Blocks introduces the button component, it differs from a generic `button` in that it has some default styles to make it correctly fit in the Blocks design.
![Button screenshot](https://user-images.githubusercontent.com/3616980/86381945-e6fd6c00-bc8d-11ea-8811-7e546bea69b9.png)
Themes can still style them to match theme colors or styles as follows:
```css
.wc-block-components-button {
background-color: #d5502f;
color: #fff;
/* More rules can be added to modify the border, shadow, etc. */
}
/* It might be needed to modify the hover, focus, active and disabled states too */
```
![Button screenshot with custom styles](https://user-images.githubusercontent.com/3616980/86381505-b6b5cd80-bc8d-11ea-8ceb-cfbe84b411d4.png)
Notice the button component doesn't have the `.button` class name. So themes that wrote some styles for buttons might want to apply some (or all) of those styles to the button component as well.
## Mobile submit container
In small viewports, the Cart block displays the _Proceed to Checkout_ button inside a container fixed at the bottom of the screen.
![Submit container screenshot](https://user-images.githubusercontent.com/3616980/86382876-393e8d00-bc8e-11ea-8d0b-e4e347ea4773.png)
By default, the container has a white background so it plays well with the button component default colors. Themes that want to apply the same background color as the rest of the page can do it with the following code snippet:
```css
.wc-block-cart__submit-container {
background-color: #f9f4ee;
}
```
Take into consideration the container has a top box shadow that might not play well with some dark background colors. If needed, it can be modified directly setting the `color` property (internally, shadow color uses `currentColor`, so it honors the `color` property):
```css
.wc-block-cart__submit-container::before {
color: rgba( 214, 209, 203, 0.5 );
}
```
Alternatively, themes can override the `box-shadow` property completely:
```css
.wc-block-cart__submit-container::before {
box-shadow: 0 -10px 20px 10px rgba( 214, 209, 203, 0.5 );
}
```
![Submit container screenshot with custom styles](https://user-images.githubusercontent.com/3616980/86382693-27f58080-bc8e-11ea-894e-de378af3e2bb.png)
## Item quantity badge
The item quantity badge is the number that appears next to the image in the _Order summary_ section of the _Checkout_ block sidebar.
![Order summary screenshot](https://user-images.githubusercontent.com/3616980/83862844-c8559500-a722-11ea-9653-2fc8bcd544d2.png)
By default, it uses a combination of black and white borders and shadows so it has enough contrast with themes with light and dark backgrounds. Themes can modify the colors with their own palette with a single CSS selector and four properties. For example:
```css
.wc-block-components-order-summary-item__quantity {
background-color: #f9f4ee;
border-color: #4b3918;
box-shadow: 0 0 0 2px #f9f4ee;
color: #4b3918;
}
```
![Order summary screenshot with custom styles for the item quantity badge](https://user-images.githubusercontent.com/3616980/83863109-2e421c80-a723-11ea-9bf7-2033a96cf5b2.png)

View File

@ -0,0 +1,72 @@
---
post_title: CSS styling for themes
menu_title: CSS Styling for Themes
tags: reference
---
## Block and component class names
> [!IMPORTANT]
> We strongly discourage writing CSS code based on existing block class names and prioritize using global styles when possible. We especially discourage writing CSS selectors that rely on a specific block being a descendant of another one, as users can move blocks around freely, so they are prone to breaking. Similar to WordPress itself, we consider the HTML structure within components, blocks, and block templates to be "private", and subject to further change in the future, so using CSS to target the internals of a block or a block template is _not recommended or supported_.
WooCommerce Blocks follows BEM for class names, as [stated in our coding guidelines](https://github.com/woocommerce/woocommerce/blob/trunk/plugins/woocommerce-blocks/docs/contributors/coding-guidelines.md). All classes start with one of these two prefixes:
* `.wc-block-`: class names specific to a single block.
* `.wc-block-components-`: class names specific to a component. The component might be reused by different blocks.
The combination of block class names and component class names allows themes to style each component either globally or only in specific blocks. As an example, you could style all prices to be italics with:
```css
/* This will apply to all block prices */
.wc-block-components-formatted-money-amount {
font-style: italic;
}
```
But if you only wanted to make it italic in the Checkout block, that could be done adding the block selector:
```css
/* This will apply to prices in the checkout block */
.wc-block-checkout .wc-block-components-formatted-money-amount {
font-style: italic;
}
```
**Note:** for backwards compatibility, some components might have class names with both prefixes (ie: `wc-block-sort-select` and `wc-block-components-sort-select`). In those cases, the class name with `.wc-block-` prefix is deprecated and shouldn't be used in new code. It will be removed in future versions. If an element has both classes always style the one with `.wc-block-components-` prefix.
## Container query class names
Some of our components have responsive classes depending on the container width. The reason to use these classes instead of CSS media queries is to adapt to the container where the block is added (CSS media queries only allow reacting to viewport sizes).
Those classes are:
Container width | Class name
----------------|------------
\&gt;700px | `is-large`
521px-700px | `is-medium`
401px-520px | `is-small`
&lt;=400px | `is-mobile`
As an example, if we wanted to do the Checkout font size 10% larger when the container has a width of 521px or wider, we could do so with this code:
```css
.wc-block-checkout.is-medium,
.wc-block-checkout.is-large {
font-size: 1.1em;
}
```
## WC Blocks _vs._ theme style conflicts for semantic elements
WooCommerce Blocks uses HTML elements according to their semantic meaning, not their default layout. That means that some times blocks might use an anchor link (`&lt;a&gt;`) but display it as a button. Or the other way around, a `&lt;button&gt;` might be displayed as a text link. Similarly, headings might be displayed as regular text.
In these cases, Blocks include some CSS resets to undo most default styles introduced by themes. A `&lt;button&gt;` that is displayed as a text link will probably have resets for the background, border, etc. That will solve most conflicts out-of-the-box but in some occasions those CSS resets might not have effect if the theme has a specific CSS selector with higher specificity. When that happens, we really encourage theme developers to decrease their selectors specificity so Blocks styles have preference, if that's not possible, themes can write CSS resets on top.
## Hidden elements
WC Blocks use the [`hidden` HTML attribute](https://developer.mozilla.org/en-US/docs/Web/HTML/Global_attributes/hidden) to hide some elements from the UI so they are not displayed in screens neither read by assistive technologies. If your theme has some generic styles that tweak the CSS display property of blocks elements (ie: `div { display: block; }`), make sure you correctly handle the hidden attribute: `div[hidden] { display: none; }`.
## Legacy classes from WooCommerce (.price, .star-rating, .button...)
WooCommerce Blocks avoids using legacy unprefixed classes as much as possible. However, you might find some of them that have been added for backwards compatibility. We still encourage themes to use the prefixed classes when possible, this avoids conflicts with other plugins, the editor, etc.

View File

@ -0,0 +1,85 @@
---
post_title: Theming for Woo blocks
menu_title: Theming for Woo Blocks
tags: reference
---
This page includes documentation about theming WooCommerce blocks and block themes.
**Note:** this document assumes some previous knowledge about block theme development and some WordPress concepts. If you are completely new to block theme development, please check [Develop Your First Low-Code Block Theme](https://learn.wordpress.org/course/develop-your-first-low-code-block-theme/)
to learn about block theme development, and explore
the [Create Block Theme plugin](https://wordpress.org/plugins/create-block-theme/) tool when you're ready to create a
new theme.
## General concepts
### Block templates
WooCommerce comes with several [block templates](https://github.com/woocommerce/woocommerce/tree/trunk/plugins/woocommerce/templates/templates/blockified) by default. Those are:
- Single Product (`single-product.html`)
- Product Catalog (`archive-product.html`)
- Products by Category (`taxonomy-product_cat.html`)
- Products by Tag (`taxonomy-product_tag.html`)
- Products by Attribute (`taxonomy-product_attribute.html`)
- Product Search Results (`product-search-results.html`)
- Page: Coming soon (`page-coming-soon.html`)
- Page: Cart (`page-cart.html`)
- Page: Checkout (`page-checkout.html`)
- Order Confirmation (`order-confirmation.html`)
Block themes can customize those templates in the following ways:
- It's possible to override the templates by creating a file with the same file name under the `/templates` folder. For example, if a block theme contains a `wp-content/themes/yourtheme/templates/single-product.html` template, it will take priority over the WooCommerce default Single Product template.
- Products by Category, Products by Tag and Products by Attribute templates fall back to the Product Catalog template. In other words, if a theme provides an `archive-product.html` template but doesn't provide a `taxonomy-product_cat.html` template, the Products by Category template will use the `archive-product.html` template. Same for the Products by Tag and Products by Attribute templates.
- It's possible to create templates for specific products and taxonomies. For example, if the theme provides a template with file name of `single-product-cap.html`, that template will be used when rendering the product with slug `cap`. Similarly, themes can provide specific taxonomy templates: `taxonomy-product_cat-clothing.html` would be used in the product category with slug `clothing`.
- Always keep in mind users can make modifications to the templates provided by the theme via the Site Editor.
### Block template parts
WooCommerce also comes with two specific [block template parts](https://github.com/woocommerce/woocommerce/tree/trunk/plugins/woocommerce/templates/parts):
- Mini-Cart (`mini-cart.html`): used inside the Mini-Cart block drawer.
- Checkout header (`checkout-header.html`): used as the header in the Checkout template.
Similarly to the templates, they can be overridden by themes by adding a file with the same file name under the `/parts` folder.
### Global styles
WooCommerce blocks rely on [global styles](https://developer.wordpress.org/themes/global-settings-and-styles/styles/) for their styling. Global styles can be defined by themes via `theme.json` or by users via Appearance > Editor > Styles and offer several advantages over plain CSS:
- Better performance, as only the required CSS is printed into the page, reducing the bundle size to render a page.
- Can be easily customized by users via the UI.
- Gracefully handle conflicts between plugins and themes.
- Are not affected by markup or class name updates into individual blocks or components.
- Don't depend on a specific nesting order of blocks: users can freely move blocks around without styles breaking.
#### Example
For example, let's imagine you are building a theme and would like to customize the Product Price block styles, you can do so by adding these properties in your `theme.json`:
```JSON
"styles": {
"blocks": {
"woocommerce/product-price": {
"color": {
"background": "#00cc00",
"text": "#fff"
},
"typography": {
"fontStyle": "italic",
"fontWeight": "700"
}
}
...
}
...
}
```
Before | After
------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
<img src="https://github.com/woocommerce/woocommerce/assets/3616980/fbc11b83-f47b-4b25-bdeb-df798b251cce" width="210" alt="Product Collection block showing the Product Price block with default styles" /> | <img src="https://github.com/woocommerce/woocommerce/assets/3616980/c9730445-b9df-4e96-8204-a10896ac2c5a" width="210" alt="Product Collection block showing the Product Price styled with background and text colors and italic and bold typography" /> <!-- markdownlint-disable-line no-inline-html -->
You can find more [documentation on global styles](https://developer.wordpress.org/themes/global-settings-and-styles/styles/) in developer.wordpress.org. You can also find the [list of WooCommerce blocks and their names in the docs](https://github.com/woocommerce/woocommerce/blob/trunk/plugins/woocommerce-blocks/docs/block-references/block-references.md).

View File

@ -1,6 +1,6 @@
---
post_title: How to add a custom field to simple and variable products
menu_title: Add custom fields to products
menu_title: Add Custom Fields to Products
tags: how-to
---

File diff suppressed because it is too large Load Diff

View File

@ -85,7 +85,7 @@ return (pass);
}
# Block access to php admin pages via website
if (req.url ~ "^/phpmyadmin/.*$" || req.url ~ "^/phppgadmin/.*$" || req.url ~ "^/server-status.*$") {
error 403 "For security reasons, this URL is only accesible using localhost (127.0.0.1) as the hostname";
error 403 "For security reasons, this URL is only accessible using localhost (127.0.0.1) as the hostname";
}
Add this to vcl_fetch:

View File

@ -0,0 +1,5 @@
---
category_title: Cart and Checkout Blocks
category_slug: cart-and-checkout-blocks
post_title: Cart and Checkout blocks - Extensibility
---

View File

@ -0,0 +1,725 @@
---
post_title: Cart and Checkout - Additional checkout fields
menu_title: Additional Checkout Fields
tags: reference
---
A common use-case for developers and merchants is to add a new field to the Checkout form to collect additional data about a customer or their order.
This document will outline the steps an extension should take to register some additional checkout fields.
## Available field locations
Additional checkout fields can be registered in three different places:
- Contact information
- Addresses (Shipping **and** Billing)
- Order information
A field can only be shown in one location, it is not possible to render the same field in multiple locations in the same registration.
### Contact information
The contact information section currently renders at the top of the form. It contains the `email` field and any other additional fields.
![Showing the contact information section with two fields rendered, email and an additional checkout field (optional)](https://github.com/woocommerce/woocommerce/assets/5656702/097c2596-c629-4eab-9604-577ee7a14cfe)
Fields rendered here will be saved to the shopper's account. They will be visible and editable render in the shopper's "Account details" section.
### Address
The "Address" section currently contains a form for the shipping address and the billing address. Additional checkout fields can be registered to appear within these forms.
![The shipping address form showing the additional checkout field at the bottom](https://github.com/woocommerce/woocommerce/assets/5656702/746d280f-3354-4d37-a78a-a2518eb0e5de)
Fields registered here will be saved to both the customer _and_ the order, so returning customers won't need to refill those values again.
If a field is registered in the `address` location it will appear in both the shipping **and** the billing address. It is not possible to have the field in only one of the addresses.
You will also end up collecting two values for this field, one for shipping and one for billing.
### Order information
As part of the additional checkout fields feature, the checkout block has a new inner block called the "Order information block".
This block is used to render fields that aren't part of the contact information or address information, for example it may be a "How did you hear about us" field or a "Gift message" field.
Fields rendered here will be saved to the order. They will not be part of the customer's saved address or account information. New orders will not have any previously used values pre-filled.
![The order information section containing an additional checkout field](https://github.com/woocommerce/woocommerce/assets/5656702/295b3048-a22a-4225-96b0-6b0371a7cd5f)
By default, this block will render as the last step in the Checkout form, however it can be moved using the Gutenberg block controls in the editor.
![The order information block in the post editor"](https://github.com/woocommerce/woocommerce/assets/5656702/05a3d7d9-b3af-4445-9318-443ae2c4d7d8)
## Accessing values
Additional fields are saved to individual meta keys in both the customer meta and order meta, you can access them using helper methods, or using the meta keys directly, we recommend using the helper methods, as they're less likely to change, can handle future migrations, and will support future enhancements (e.g. reading from different locations).
For address fields, two values are saved: one for shipping, and one for billing. If the customer has selected 'Use same address for billing` then the values will be the same, but still saved independently of each other.
For contact and order fields, only one value is saved per field.
### Helper methods
`CheckoutFields` provides a function to access values from both customers and orders, it's are `get_field_from_object`.
To access a customer billing and/or shipping value:
```php
use Automattic\WooCommerce\Blocks\Package;
use Automattic\WooCommerce\Blocks\Domain\Services\CheckoutFields;
$field_id = 'my-plugin-namespace/my-field';
$customer = wc()->customer; // Or new WC_Customer( $id )
$checkout_fields = Package::container()->get( CheckoutFields::class );
$my_customer_billing_field = $checkout_fields->get_field_from_object( $field_id, $customer, 'billing' );
$my_customer_shipping_field = $checkout_fields->get_field_from_object( $field_id, $customer, 'shipping' );
```
To access an order field:
```php
use Automattic\WooCommerce\Blocks\Package;
use Automattic\WooCommerce\Blocks\Domain\Services\CheckoutFields;
$field_id = 'my-plugin-namespace/my-field';
$order = wc_get_order( 1234 );
$checkout_fields = Package::container()->get( CheckoutFields::class );
$my_order_billing_field = $checkout_fields->get_field_from_object( $field_id, $order, 'billing' );
$my_order_shipping_field = $checkout_fields->get_field_from_object( $field_id, $order, 'shipping' );
```
After an order is placed, the data saved to the customer and the data saved to the order will be the same. Customers can change the values for _future_ orders, or from within their My Account page. If you're looking at a customer value at a specific point in time (i.e. when the order was placed), access it from the order object, if you're looking for the most up to date value regardless, access it from the customer object.
#### Guest customers
When a guest customer places an order with additional fields, those fields will be saved to its session, so as long as the customer still has a valid session going, the values will always be there.
#### Logged-in customers
For logged-in customers, the value is only persisted once they place an order. Accessing a logged-in customer object during the place order lifecycle will return null or stale data.
If you're at a place order hook, doing this will return previous data (not the currently inserted one):
```php
$customer = new WC_Customer( $order->customer_id ); // Or new WC_Customer( 1234 )
$my_customer_billing_field = $checkout_fields->get_field_from_object( $field_id, $customer, 'billing' );
```
Instead, always access the latest data if you want to run some extra validation/data-moving:
```php
$customer = wc()->customer // This will return the current customer with its session.
$my_customer_billing_field = $checkout_fields->get_field_from_object( $field_id, $customer, 'billing' );
```
#### Accessing all fields
You can use `get_all_fields_from_object` to access all additional fields saved to an order or a customer.
```php
use Automattic\WooCommerce\Blocks\Package;
use Automattic\WooCommerce\Blocks\Domain\Services\CheckoutFields;
$order = wc_get_order( 1234 );
$checkout_fields = Package::container()->get( CheckoutFields::class );
$order_additional_billing_fields = $checkout_fields->get_all_fields_from_object( $order, 'billing' );
$order_additional_shipping_fields = $checkout_fields->get_all_fields_from_object( $order, 'shipping' );
$order_other_additional_fields = $checkout_fields->get_all_fields_from_object( $order, 'other' ); // Contact and Order are saved in the same place under the additional group.
```
This will return an array of all values, it will only include fields currently registered, if you want to include fields no longer registered, you can pass a third `true` parameter.
```php
$order = wc_get_order( 1234 );
$checkout_fields = Package::container()->get( CheckoutFields::class );
$order_additional_billing_fields = $checkout_fields->get_all_fields_from_object( $order, 'billing' ); // array( 'my-plugin-namespace/my-field' => 'my-value' );
$order_additional_billing_fields = $checkout_fields->get_all_fields_from_object( $order, 'billing', true ); // array( 'my-plugin-namespace/my-field' => 'my-value', 'old-namespace/old-key' => 'old-value' );
```
### Accessing values directly
While not recommended, you can use the direct meta key to access certain values, this is useful for external engines or page/email builders who only provide access to meta values.
Values are saved under a predefined prefix, this is needed to able to query fields without knowing which ID the field was registered under, for a field with key `'my-plugin-namespace/my-field'`, it's meta key will be the following if it's an address field:
- `_wc_billing/my-plugin-namespace/my-field`
- `_wc_shipping/my-plugin-namespace/my-field`
Or the following if it's a contact/order field:
- `_wc_other/my-plugin-namespace/my-field`.
Those prefixes are part of `CheckoutFields` class, and can be accessed using the following constants:
```php
echo ( CheckoutFields::BILLING_FIELDS_PREFIX ); // _wc_billing/
echo ( CheckoutFields::SHIPPING_FIELDS_PREFIX ); // _wc_shipping/
echo ( CheckoutFields::OTHER_FIELDS_PREFIX ); // _wc_other/
```
`CheckoutFields` provides a couple of helpers to get the group name or key based on one or the other:
```php
CheckoutFields::get_group_name( "_wc_billing" ); // "billing"
CheckoutFields::get_group_name( "_wc_billing/" ); // "billing"
CheckoutFields::get_group_key( "shipping" ); // "_wc_shipping/"
```
Use cases here would be to build the key name to access the meta directly:
```php
$key = CheckoutFields::get_group_key( "other" ) . 'my-plugin/is-opt-in';
$opted_in = get_user_meta( 123, $key, true ) === "1" ? true : false;
```
#### Checkboxes values
When accessing a checkbox values directly, it will either return `"1"` for true, `"0"` for false, or `""` if the value doesn't exist, only the provided functions will sanitize that to a boolean.
## Supported field types
The following field types are supported:
- `select`
- `text`
- `checkbox`
There are plans to expand this list, but for now these are the types available.
## Using the API
To register additional checkout fields you must use the `woocommerce_register_additional_checkout_field` function.
It is recommended to run this function after the `woocommerce_init` action.
The registration function takes an array of options describing your field. Some field types take additional options.
### Options
#### General options
These options apply to all field types (except in a few circumstances which are noted inline).
| Option name | Description | Required? | Example | Default value |
|---------------------|-------------------------------------------------------------------------------------------------------------------------------------|-------------------------------------------------------------------------------------------------------------------------------------|----------------------------------------------|------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
| `id` | The field's ID. This should be a unique identifier for your field. It is composed of a namespace and field name separated by a `/`. | Yes | `plugin-namespace/how-did-you-hear` | No default - this must be provided. |
| `label` | The label shown on your field. This will be the placeholder too. | Yes | `How did you hear about us?` | No default - this must be provided. |
| `optionalLabel` | The label shown on your field if it is optional. This will be the placeholder too. | No | `How did you hear about us? (Optional)` | The default value will be the value of `label` with `(optional)` appended. |
| `location` | The location to render your field. | Yes | `contact`, `address`, or `order` | No default - this must be provided. |
| `type` | The type of field you're rendering. It defaults to `text` and must match one of the supported field types. | No | `text`, `select`, or `checkbox` | `text` |
| `attributes` | An array of additional attributes to render on the field's input element. This is _not_ supported for `select` fields. | No | `[ 'data-custom-data' => 'my-custom-data' ]` | `[]` |
| `sanitize_callback` | A function called to sanitize the customer provided value when posted. | No | See example below | By default the field's value is returned unchanged. |
| `validate_callback` | A function called to validate the customer provided value when posted. This runs _after_ sanitization. | No | See example below | The default validation function will add an error to the response if the field is required and does not have a value. [See the default validation function.](https://github.com/woocommerce/woocommerce/blob/trunk/plugins/woocommerce/src/Blocks/Domain/Services/CheckoutFields.php#L270-L281) |
##### Example of `sanitize_callback`. This function will remove spaces from the value <!-- omit from toc -->
```php
'sanitize_callback' => function( $field_value ) {
return str_replace( ' ', '', $field_value );
},
```
##### Example of `validate_callback`. This function will check if the value is an email <!-- omit from toc -->
```php
'validate_callback' => function( $field_value ) {
if ( ! is_email( $field_value ) ) {
return new WP_Error( 'invalid_alt_email', 'Please ensure your alternative email matches the correct format.' );
}
},
```
#### Options for `text` fields
As well as the options above, text fields also support a `required` option. If this is `true` then the shopper _must_ provide a value for this field during the checkout process.
| Option name | Description | Required? | Example | Default value |
|-----------------|-------------------------------------------------------------------------------------------------------------------------------------|-----------|----------------------------------------------|---|
| `required` | If this is `true` then the shopper _must_ provide a value for this field during the checkout process. | No | `true` | `false` |
#### Options for `select` fields
As well as the options above, select fields must also be registered with an `options` option. This is used to specify what options the shopper can select.
Select fields will mount with no value selected by default, if the field is required, the user will be required to select a value.
You can set a placeholder to be shown on the select by passing a `placeholder` value when registering the field. This will be the first option in the select and will not be selectable if the field is required.
| Option name | Description | Required? | Example | Default value |
|-----|-----|-----|----------------|--------------|
| `options` | An array of options to show in the select input. Each options must be an array containing a `label` and `value` property. Each entry must have a unique `value`. Any duplicate options will be removed. The `value` is what gets submitted to the server during checkout and the `label` is simply a user-friendly representation of this value. It is not transmitted to the server in any way. | Yes | see below | No default - this must be provided. |
| `required` | If this is `true` then the shopper _must_ provide a value for this field during the checkout process. | No | `true` | `false` |
| `placeholder` | If this value is set, the shopper will see this option in the select. If the select is required, the shopper cannot select this option. | No | `Select a role | Select a $label |
##### Example of `options` value
```php
[
[
'value' => 'store_1',
'label' => 'Our London Store'
],
[
'value' => 'store_2',
'label' => 'Our Paris Store'
],
[
'value' => 'store_3',
'label' => 'Our New York Store'
]
]
```
#### Options for `checkbox` fields
The checkbox field type does not have any specific options, however `required` will always be `false` for a checkbox field. Making a checkbox field required is not supported.
### Attributes
Adding additional attributes to checkbox and text fields is supported. Adding them to select fields is **not possible for now**.
These attributes have a 1:1 mapping to the HTML attributes on `input` elements (except `pattern` on checkbox).
The supported attributes are:
- `data-*` attributes
- `aria-*` attributes
- `autocomplete`
- `autocapitalize`
- `pattern` (not supported on checkbox fields)
- `title`
- `maxLength` (equivalent to `maxlength` HTML attribute)
- `readOnly` (equivalent to `readonly` HTML attribute)
`maxLength` and `readOnly` are in camelCase because the attributes are rendered on a React element which must receive them in this format.
Certain attributes are not passed through to the field intentionally, these are `autofocus` and `disabled`. We are welcome to hear feedback and adjust this behaviour if valid use cases are provided.
## Usage examples
### Rendering a text field
This example demonstrates rendering a text field in the address section:
```php
add_action(
'woocommerce_init',
function() {
woocommerce_register_additional_checkout_field(
array(
'id' => 'namespace/gov-id',
'label' => 'Government ID',
'optionalLabel' => 'Government ID (optional)',
'location' => 'address',
'required' => true,
'attributes' => array(
'autocomplete' => 'government-id',
'aria-describedby' => 'some-element',
'aria-label' => 'custom aria label',
'pattern' => '[A-Z0-9]{5}', // A 5-character string of capital letters and numbers.
'title' => 'Title to show on hover',
'data-custom' => 'custom data',
),
),
);
}
);
```
This results in the following address form (the billing form will be the same):
![The shipping address form with the Government ID field rendered at the bottom](https://github.com/woocommerce/woocommerce/assets/5656702/f6eb3c6f-9178-4978-8e74-e6b2ea353192)
The rendered markup looks like this:
```html
<input type="text" id="shipping-namespace-gov-id" autocapitalize="off"
autocomplete="government-id" aria-label="custom aria label"
aria-describedby="some-element" required="" aria-invalid="true"
title="Title to show on hover" pattern="[A-Z0-9]{5}"
data-custom="custom data" value="" >
```
### Rendering a checkbox field
This example demonstrates rendering a checkbox field in the contact information section:
```php
add_action(
'woocommerce_init',
function() {
woocommerce_register_additional_checkout_field(
array(
'id' => 'namespace/marketing-opt-in',
'label' => 'Do you want to subscribe to our newsletter?',
'location' => 'contact',
'type' => 'checkbox',
)
);
}
);
```
This results in the following contact information section:
![The contact information section with a newsletter subscription checkbox rendered inside it](https://github.com/woocommerce/woocommerce/assets/5656702/7444e41a-97cc-451d-b2c9-4eedfbe05724)
Note that because an `optionalLabel` was not supplied, the string `(optional)` is appended to the label. To remove that an `optionalLabel` property should be supplied to override this.
### Rendering a select field
This example demonstrates rendering a select field in the order information section:
```php
add_action(
'woocommerce_init',
function() {
woocommerce_register_additional_checkout_field(
array(
'id' => 'namespace/how-did-you-hear-about-us',
'label' => 'How did you hear about us?',
'placeholder' => 'Select a source',
'location' => 'order',
'type' => 'select',
'options' => [
[
'value' => 'google',
'label' => 'Google'
],
[
'value' => 'facebook',
'label' => 'Facebook'
],
[
'value' => 'friend',
'label' => 'From a friend'
],
[
'value' => 'other',
'label' => 'Other'
],
]
)
);
}
);
```
This results in the order information section being rendered like so:
### The select input before being focused
![The select input before being focused](https://github.com/woocommerce/woocommerce/assets/5656702/bbe17ad0-7c7d-419a-951d-315f56f8898a)
### The select input when focused
![The select input when focused](https://github.com/woocommerce/woocommerce/assets/5656702/bd943906-621b-404f-aa84-b951323e25d3)
If it is undesirable to force the shopper to select a value, mark the select as optional by setting the `required` option to `false`.
## Validation and sanitization
It is possible to add custom validation and sanitization for additional checkout fields using WordPress action hooks.
These actions happen in two places:
1. Updating and submitting the form during the checkout process and,
2. Updating address/contact information in the "My account" area.
### Sanitization
Sanitization is used to ensure the value of a field is in a specific format. An example is when taking a government ID, you may want to format it so that all letters are capitalized and there are no spaces. At this point, the value should **not** be checked for _validity_. That will come later. This step is only intended to set the field up for validation.
#### Using the `woocommerce_sanitize_additional_field` filter
To run a custom sanitization function for a field you can use the `sanitize_callback` function on registration, or the `woocommerce_sanitize_additional_field` filter.
| Argument | Type | Description |
|--------------|-------------------|-------------------------------------------------------------------------|
| `$field_value` | `boolean\|string` | The value of the field. |
| `$field_key` | `string` | The ID of the field. This is the same ID the field was registered with. |
##### Example of sanitization
This example shows how to remove whitespace and capitalize all letters in the example Government ID field we added above.
```php
add_action(
'woocommerce_sanitize_additional_field',
function ( $field_value, $field_key ) {
if ( 'namespace/gov-id' === $field_key ) {
$field_value = str_replace( ' ', '', $field_key );
$field_value = strtoupper( $field_value );
}
return $field_value;
},
10,
2
);
```
### Validation
There are two phases of validation in the additional checkout fields system. The first is validating a single field based on its key and value.
#### Single field validation
##### Using the `woocommerce_validate_additional_field` action
When the `woocommerce_validate_additional_field` action is fired the callback receives the field's key, the field's value, and a `WP_Error` object.
To add validation errors to the response, use the [`WP_Error::add`](https://developer.wordpress.org/reference/classes/wp_error/add/) method.
| Argument | Type | Description |
|--------------|-------------------|---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
| `$errors` | `WP_Error` | An error object containing errors that were already encountered while processing the request. If no errors were added yet, it will still be a `WP_Error` object but it will be empty. |
| `$field_key` | `string` | The id of the field. This is the ID the field was registered with. |
| `$field_value` | `boolean\|string` | The value of the field |
###### The `WP_Error` object
When adding your error to the `WP_Error` object, it should have a unique error code. You may want to prefix the error code with the plugin namespace to reduce the chance of collision. Using codes that are already in use across other plugins may result in the error message being overwritten or showing in a different location.
###### Example of single-field validation
The below example shows how to apply custom validation to the `namespace/gov-id` text field from above. The code here ensures the field is made up of 5 characters, either upper-case letters or numbers. The sanitization function from the example above ensures that all whitespace is removed and all letters are capitalized, so this check is an extra safety net to ensure the input matches the pattern.
```php
add_action(
'woocommerce_validate_additional_field',
function ( WP_Error $errors, $field_key, $field_value ) {
if ( 'namespace/gov-id' === $field_key ) {
$match = preg_match( '/[A-Z0-9]{5}/', $field_value );
if ( 0 === $match || false === $match ) {
$errors->add( 'invalid_gov_id', 'Please ensure your government ID matches the correct format.' );
}
}
},
10,
3
);
```
It is important to note that this action must _add_ errors to the `WP_Error` object it receives. Returning a new `WP_Error` object or any other value will result in the errors not showing.
If no validation errors are encountered the function can just return void.
#### Multiple field validation
There are cases where the validity of a field depends on the value of another field, for example validating the format of a government ID based on what country the shopper is in. In this case, validating only single fields (as above) is not sufficient as the country may be unknown during the `woocommerce_validate_additional_field` action.
To solve this, it is possible to validate a field in the context of the location it renders in. The other fields in that location will be passed to this action.
##### Using the `woocommerce_blocks_validate_location_{location}_fields` action
This action will be fired for each location that additional fields can render in (`address`, `contact`, and `order`). For `address` it fires twice, once for the billing address and once for the shipping address.
The callback receives the keys and values of the other additional fields in the same location.
It is important to note that any fields rendered in other locations will not be passed to this action, however it might be possible to get those values by accessing the customer or order object, however this is not supported and there are no guarantees regarding backward compatibility in future versions.
| Argument | Type | Description |
|----------|-----------------------------|---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
| `$errors` | `WP_Error` | An error object containing errors that were already encountered while processing the request. If no errors were added yet, it will still be a `WP_Error` object but it will be empty. |
| `$fields` | `array` | The fields rendered in this locations. |
| `$group` | `'billing'\|'shipping'\|'other'` | If the action is for the address location, the type of address will be set here. If it is for contact or order, this will be 'other'. |
There are several places where these hooks are fired.
- When checking out using the Checkout block or Store API.
- `woocommerce_blocks_validate_location_address_fields` (x2)
- `woocommerce_blocks_validate_location_contact_fields`
- `woocommerce_blocks_validate_location_other_fields`
- When updating addresses in the "My account" area
- `woocommerce_blocks_validate_location_address_fields` (**x1** - only the address being edited)
- When updating the "Account details" section in the "My account" area
- `woocommerce_blocks_validate_location_contact_fields`
##### Example of location validation
In this example, assume there is another field registered alongside the `namespace/gov-id` called `namespace/confirm-gov-id`. This field will be a confirmation for the Government ID field.
The example below illustrates how to verify that the value of the confirmation field matches the value of the main field.
```php
add_action(
'woocommerce_blocks_validate_location_address_fields',
function ( \WP_Error $errors, $fields, $group ) {
if ( $fields['namespace/gov-id'] !== $fields['namespace/confirm-gov-id'] ) {
$errors->add( 'gov_id_mismatch', 'Please ensure your government ID matches the confirmation.' );
}
},
10,
3
);
```
If these fields were rendered in the "contact" location instead, the code would be the same except the hook used would be: `woocommerce_blocks_validate_location_contact_fields`.
## Backward compatibility
Due to technical reasons, it's not yet possible to specify the meta key for fields, as we want them to be prefixed and managed. Plugins with existing fields in shortcode Checkout can be compatible and react to reading and saving fields using hooks.
Assuming 2 fields, named `my-plugin-namespace/address-field` in the address step and `my-plugin-namespace/my-other-field` in the order step, you can:
### React to to saving fields
You can react to those fields being saved by hooking into `woocommerce_set_additional_field_value` action.
```php
add_action(
'woocommerce_set_additional_field_value',
function ( $key, $value, $group, $wc_object ) {
if ( 'my-plugin-namespace/address-field' !== $key ) {
return;
}
if ( 'billing' === $group ) {
$my_plugin_address_key = 'existing_billing_address_field_key';
} else {
$my_plugin_address_key = 'existing_shipping_address_field_key';
}
$wc_object->update_meta_data( $my_plugin_address_key, $value, true );
},
10,
4
);
add_action(
'woocommerce_set_additional_field_value',
function ( $key, $value, $group, $wc_object ) {
if ( 'my-plugin-namespace/my-other-field' !== $key ) {
return;
}
$my_plugin_key = 'existing_order_field_key';
$wc_object->update_meta_data( $my_plugin_key, $value, true );
},
10,
4
);
```
This way, you can ensure existing systems will continue working and your integration will continue to work. However, ideally, you should migrate your existing data and systems to use the new meta fields.
### React to reading fields
You can use the `woocommerce_get_default_value_for_{$key}` filters to provide a different default value (a value coming from another meta field for example):
```php
add_filter(
"woocommerce_get_default_value_for_my-plugin-namespace/address-field",
function ( $value, $group, $wc_object ) {
if ( 'billing' === $group ) {
$my_plugin_key = 'existing_billing_address_field_key';
} else {
$my_plugin_key = 'existing_shipping_address_field_key';
}
return $wc_object->get_meta( $my_plugin_key );
},
10,
3
);
add_filter(
"woocommerce_get_default_value_for_my-plugin-namespace/my-other-field",
function ( $value, $group, $wc_object ) {
$my_plugin_key = 'existing_order_field_key';
return $wc_object->get_meta( $my_plugin_key );
},
10,
3
);
```
## A full example
In this full example we will register the Government ID text field and verify that it conforms to a specific pattern.
This example is just a combined version of the examples shared above.
```php
add_action(
'woocommerce_init',
function() {
woocommerce_register_additional_checkout_field(
array(
'id' => 'namespace/gov-id',
'label' => 'Government ID',
'location' => 'address',
'required' => true,
'attributes' => array(
'autocomplete' => 'government-id',
'pattern' => '[A-Z0-9]{5}', // A 5-character string of capital letters and numbers.
'title' => 'Your 5-digit Government ID',
),
),
);
woocommerce_register_additional_checkout_field(
array(
'id' => 'namespace/confirm-gov-id',
'label' => 'Confirm government ID',
'location' => 'address',
'required' => true,
'attributes' => array(
'autocomplete' => 'government-id',
'pattern' => '[A-Z0-9]{5}', // A 5-character string of capital letters and numbers.
'title' => 'Confirm your 5-digit Government ID',
),
),
);
add_action(
'woocommerce_sanitize_additional_field',
function ( $field_value, $field_key ) {
if ( 'namespace/gov-id' === $field_key || 'namespace/confirm-gov-id' === $field_key ) {
$field_value = str_replace( ' ', '', $field_key );
$field_value = strtoupper( $field_value );
}
return $field_value;
},
10,
2
);
add_action(
'woocommerce_validate_additional_field',
function ( WP_Error $errors, $field_key, $field_value ) {
if ( 'namespace/gov-id' === $field_key ) {
$match = preg_match( '/[A-Z0-9]{5}/', $field_value );
if ( 0 === $match || false === $match ) {
$errors->add( 'invalid_gov_id', 'Please ensure your government ID matches the correct format.' );
}
}
return $error;
},
10,
3
);
}
);
add_action(
'woocommerce_blocks_validate_location_address_fields',
function ( \WP_Error $errors, $fields, $group ) {
if ( $fields['namespace/gov-id'] !== $fields['namespace/confirm-gov-id'] ) {
$errors->add( 'gov_id_mismatch', 'Please ensure your government ID matches the confirmation.' );
}
},
10,
3
);
```

View File

@ -0,0 +1,118 @@
---
category_title: Available Filters
category_slug: cart-and-checkout-available-filters
post_title: Cart and Checkout - Available Filters
---
This document lists the filters that are currently available to extensions and offers usage information for each one of them. Information on registering filters can be found on the [Checkout - Filter Registry](https://github.com/woocommerce/woocommerce/blob/trunk/plugins/woocommerce-blocks/packages/checkout/filter-registry/README.md) page.
## Cart Line Items filters
The following [Cart Line Items filters](./cart-line-items.md) are available:
- `cartItemClass`
- `cartItemPrice`
- `itemName`
- `saleBadgePriceFormat`
- `showRemoveItemLink`
- `subtotalPriceFormat`
The following screenshot shows which parts the individual filters affect:
![Cart Line Items](https://woocommerce.com/wp-content/uploads/2023/10/Screenshot-2023-10-26-at-13.12.33.png)
## Order Summary Items filters
The following [Order Summary Items filters](./order-summary-items.md) are available:
- `cartItemClass`
- `cartItemPrice`
- `itemName`
- `subtotalPriceFormat`
The following screenshot shows which parts the individual filters affect:
![Order Summary Items](https://woocommerce.com/wp-content/uploads/2023/10/Screenshot-2023-10-26-at-16.29.45.png)
## Totals Footer Item filter
The following [Totals Footer Item filter](./totals-footer-item.md) is available:
- `totalLabel`
- `totalValue`
## Checkout and place order button filters
The following [Checkout and place order button filters](./checkout-and-place-order-button.md) are available:
- `proceedToCheckoutButtonLabel`
- `proceedToCheckoutButtonLink`
- `placeOrderButtonLabel`
## Coupon filters
The following [Coupon filters](./coupons.md) are available:
- `coupons`
- `showApplyCouponNotice`
- `showRemoveCouponNotice`
## Additional Cart and Checkout inner block types filter
The following [Additional Cart and Checkout inner block types filter](./additional-cart-checkout-inner-block-types.md) is available:
- `additionalCartCheckoutInnerBlockTypes`
## Combined filters
Filters can also be combined. The following example shows how to combine some of the available filters.
```tsx
const { registerCheckoutFilters } = window.wc.blocksCheckout;
const isOrderSummaryContext = ( args ) => args?.context === 'summary';
const modifyCartItemClass = ( defaultValue, extensions, args ) => {
if ( isOrderSummaryContext( args ) ) {
return 'my-custom-class';
}
return defaultValue;
};
const modifyCartItemPrice = ( defaultValue, extensions, args ) => {
if ( isOrderSummaryContext( args ) ) {
return '<price/> for all items';
}
return defaultValue;
};
const modifyItemName = ( defaultValue, extensions, args ) => {
if ( isOrderSummaryContext( args ) ) {
return `${ defaultValue }`;
}
return defaultValue;
};
const modifySubtotalPriceFormat = ( defaultValue, extensions, args ) => {
if ( isOrderSummaryContext( args ) ) {
return '<price/> per item';
}
return defaultValue;
};
registerCheckoutFilters( 'example-extension', {
cartItemClass: modifyCartItemClass,
cartItemPrice: modifyCartItemPrice,
itemName: modifyItemName,
subtotalPriceFormat: modifySubtotalPriceFormat,
} );
```
## Troubleshooting
If you are logged in to the store as an administrator, you should be shown an error like this if your filter is not
working correctly. The error will also be shown in your console.
![Troubleshooting](https://woocommerce.com/wp-content/uploads/2023/10/Screenshot-2023-10-30-at-10.52.53.png)

View File

@ -0,0 +1,75 @@
---
post_title: Cart and Checkout Filters - Inner block types
menu_title: Inner Block Types
tags: reference
---
The following Additional Cart and Checkout inner block types filter is available:
- `additionalCartCheckoutInnerBlockTypes`
## `additionalCartCheckoutInnerBlockTypes`
### Description <!-- omit in toc -->
The Cart and Checkout blocks are made up of inner blocks. These inner blocks areas allow certain block types to be added as children. By default, only `core/paragraph`, `core/image`, and `core/separator` are available to add.
By using the `additionalCartCheckoutInnerBlockTypes` filter it is possible to add items to this array to control what the editor can into an inner block.
This filter is called once for each inner block area, so it is possible to be very granular when determining what blocks can be added where.
### Parameters <!-- omit in toc -->
- _defaultValue_ `array` (default: `[]`) - The default value of the filter.
- _extensions_ `object` (default: `{}`) - The extensions object.
- _args_ `object` - The arguments object with the following key:
- _block_ `string` - The block name of the inner block area, e.g. `woocommerce/checkout-shipping-address-block`.
- _validation_ `boolean` or `Error` - Checks if the returned value is an array of strings. If an error occurs, it will be thrown.
### Returns <!-- omit in toc -->
- `array` - The modified array with allowed block types for the corresponding inner block area.
### Code example <!-- omit in toc -->
Let's suppose we want to allow the editor to add some blocks in specific places in the Cart and Checkout blocks.
1. Allow `core/quote` to be inserted in every block area in the Cart and Checkout blocks.
2. Allow `core/table` to be inserted in the Shipping Address block in the Checkout.
In our extension we could register a filter satisfy both of these conditions like so:
```tsx
document.addEventListener( 'DOMContentLoaded', function () {
const { registerCheckoutFilters } = window.wc.blocksCheckout;
const modifyAdditionalInnerBlockTypes = (
defaultValue,
extensions,
args,
validation
) => {
defaultValue.push( 'core/quote' );
if ( args?.block === 'woocommerce/checkout-shipping-address-block' ) {
defaultValue.push( 'core/table' );
}
return defaultValue;
};
registerCheckoutFilters( 'example-extension', {
additionalCartCheckoutInnerBlockTypes: modifyAdditionalInnerBlockTypes,
} );
} );
```
To call this filter within the editor, wrap the filter registration in a `DOMContentLoaded` event listener and ensure the code runs in the admin panel.
> Filters can be also combined. See [Combined filters](./category/cart-and-checkout-blocks/available-filters/) for an example.
### Screenshots <!-- omit in toc -->
| Before | After |
|:---------------------------------------------------------------------:|:---------------------------------------------------------------------:|
|![Before applying the Additional Cart and Checkout inner block types filter](https://github.com/woocommerce/woocommerce-blocks/assets/3323310/0d4560c8-c2b1-4ed8-8aee-469b248ccb08) |![After applying the Additional Cart and Checkout inner block types filter](https://github.com/woocommerce/woocommerce-blocks/assets/3323310/d38cd568-6c8c-4158-9269-d8dffdf66988) |

View File

@ -0,0 +1,626 @@
---
post_title: Cart and Checkout Filters - Cart line items
menu_title: Cart Line Items
tags: reference
---
<!-- markdownlint-disable MD024 -->
The following Cart Line Items filters are available:
- `cartItemClass`
- `cartItemPrice`
- `itemName`
- `saleBadgePriceFormat`
- `showRemoveItemLink`
- `subtotalPriceFormat`
The following objects are shared between the filters:
- Cart object
- Cart Item object
The following screenshot shows which parts the individual filters affect:
![Cart Line Items](https://woocommerce.com/wp-content/uploads/2023/10/Screenshot-2023-10-26-at-13.12.33.png)
## `cartItemClass`
### Description <!-- omit in toc -->
The `cartItemClass` filter allows to change the cart item class.
### Parameters <!-- omit in toc -->
- _defaultValue_ `object` (default: `''`) - The default cart item class.
- _extensions_ `object` (default: `{}`) - The extensions object.
- _args_ `object` - The arguments object with the following keys:
- _cart_ `object` - The cart object from `wc/store/cart`, see Cart object.
- _cartItem_ `object` - The cart item object from `wc/store/cart`, see Cart Item object.
- _context_ `string` (allowed values: `cart` or `summary`) - The context of the item.
### Returns <!-- omit in toc -->
- `string` - The modified cart item class, or an empty string.
### Code examples <!-- omit in toc -->
#### Basic example <!-- omit in toc -->
```tsx
const { registerCheckoutFilters } = window.wc.blocksCheckout;
const modifyCartItemClass = ( defaultValue, extensions, args ) => {
const isCartContext = args?.context === 'cart';
if ( ! isCartContext ) {
return defaultValue;
}
return 'my-custom-class';
};
registerCheckoutFilters( 'example-extension', {
cartItemClass: modifyCartItemClass,
} );
```
#### Advanced example <!-- omit in toc -->
```tsx
const { registerCheckoutFilters } = window.wc.blocksCheckout;
const modifyCartItemClass = ( defaultValue, extensions, args ) => {
const isCartContext = args?.context === 'cart';
if ( ! isCartContext ) {
return defaultValue;
}
if ( args?.cartItem?.name === 'Beanie with Logo' ) {
return 'cool-class';
}
if ( args?.cartItem?.name === 'Sunglasses' ) {
return 'hot-class';
}
return 'my-custom-class';
};
registerCheckoutFilters( 'example-extension', {
cartItemClass: modifyCartItemClass,
} );
```
> Filters can be also combined. See [Combined filters](./category/cart-and-checkout-blocks/available-filters/) for an example.
### Screenshots <!-- omit in toc -->
| Before | After |
|:---------------------------------------------------------------------:|:---------------------------------------------------------------------:|
|![Before applying the Cart Item Class filter](https://github.com/woocommerce/woocommerce-blocks/assets/3323310/a587a6ce-d051-4ed0-bba5-815b5d72179d) |![After applying the Cart Item Class filter](https://github.com/woocommerce/woocommerce-blocks/assets/3323310/9b25eeae-6d81-4e28-b177-32f942e1d0c2) |
## `cartItemPrice`
### Description <!-- omit in toc -->
The `cartItemPrice` filter allows to format the cart item price.
### Parameters <!-- omit in toc -->
- _defaultValue_ `string` (default: `&lt;price/&gt;`) - The default cart item price.
- _extensions_ `object` (default: `{}`) - The extensions object.
- _args_ `object` - The arguments object with the following keys:
- _cart_ `object` - The cart object from `wc/store/cart`, see Cart object.
- _cartItem_ `object` - The cart item object from `wc/store/cart`, see Cart Item object.
- _context_ `string` (allowed values: `cart` or `summary`) - The context of the item.
- _validation_ `boolean` - Checks if the return value contains the substring `&lt;price/&gt;`.
### Returns <!-- omit in toc -->
- `string` - The modified format of the cart item price, which must contain the substring `&lt;price/&gt;`, or the original price format.
### Code examples <!-- omit in toc -->
#### Basic example <!-- omit in toc -->
```tsx
const { registerCheckoutFilters } = window.wc.blocksCheckout;
const modifyCartItemPrice = ( defaultValue, extensions, args, validation ) => {
const isCartContext = args?.context === 'cart';
if ( ! isCartContext ) {
return defaultValue;
}
return '&lt;price/&gt; for all items';
};
registerCheckoutFilters( 'example-extension', {
cartItemPrice: modifyCartItemPrice,
} );
```
#### Advanced example <!-- omit in toc -->
```tsx
const { registerCheckoutFilters } = window.wc.blocksCheckout;
const modifyCartItemPrice = ( defaultValue, extensions, args, validation ) => {
const isCartContext = args?.context === 'cart';
if ( ! isCartContext ) {
return defaultValue;
}
if ( args?.cartItem?.name === 'Beanie with Logo' ) {
return '&lt;price/&gt; to keep you warm';
}
if ( args?.cartItem?.name === 'Sunglasses' ) {
return '&lt;price/&gt; to keep you cool';
}
return '&lt;price/&gt; for all items';
};
registerCheckoutFilters( 'example-extension', {
cartItemPrice: modifyCartItemPrice,
} );
```
> Filters can be also combined. See [Combined filters](./category/cart-and-checkout-blocks/available-filters/) for an example.
### Screenshots <!-- omit in toc -->
| Before | After |
|:---------------------------------------------------------------------:|:---------------------------------------------------------------------:|
|![Before applying the Cart Item Price filter](https://github.com/woocommerce/woocommerce-blocks/assets/3323310/bbaeb68a-492e-41e7-87b7-4b8b05ca3709) |![After applying the Cart Item Price filter](https://github.com/woocommerce/woocommerce-blocks/assets/3323310/bbaeb68a-492e-41e7-87b7-4b8b05ca3709) |
## `itemName`
### Description <!-- omit in toc -->
The `itemName` filter allows to change the cart item name.
### Parameters <!-- omit in toc -->
- _defaultValue_ `string` - The default cart item name.
- _extensions_ `object` (default: `{}`) - The extensions object.
- _args_ `object` - The arguments object with the following keys:
- _cart_ `object` - The cart object from `wc/store/cart`, see Cart object.
- _cartItem_ `object` - The cart item object from `wc/store/cart`, see Cart Item object.
- _context_ `string` (allowed values: `cart` or `summary`) - The context of the item.
### Returns <!-- omit in toc -->
- `string` - The original or modified cart item name.
### Code examples <!-- omit in toc -->
#### Basic example <!-- omit in toc -->
```tsx
const { registerCheckoutFilters } = window.wc.blocksCheckout;
const modifyItemName = ( defaultValue, extensions, args ) => {
const isCartContext = args?.context === 'cart';
if ( ! isCartContext ) {
return defaultValue;
}
return `🪴 ${ defaultValue } 🪴`;
};
registerCheckoutFilters( 'example-extension', {
itemName: modifyItemName,
} );
```
#### Advanced example <!-- omit in toc -->
```tsx
const { registerCheckoutFilters } = window.wc.blocksCheckout;
const modifyItemName = ( defaultValue, extensions, args ) => {
const isCartContext = args?.context === 'cart';
if ( ! isCartContext ) {
return defaultValue;
}
if ( args?.cartItem?.name === 'Beanie with Logo' ) {
return `⛷️ ${ defaultValue } ⛷️`;
}
if ( args?.cartItem?.name === 'Sunglasses' ) {
return `🏄‍♂️ ${ defaultValue } 🏄‍♂️`;
}
return `🪴 ${ defaultValue } 🪴`;
};
registerCheckoutFilters( 'example-extension', {
itemName: modifyItemName,
} );
```
> Filters can be also combined. See [Combined filters](./category/cart-and-checkout-blocks/available-filters/) for an example.
### Screenshots <!-- omit in toc -->
| Before | After |
|:---------------------------------------------------------------------:|:---------------------------------------------------------------------:|
|![Before applying the Item Name filter](https://github.com/woocommerce/woocommerce-blocks/assets/3323310/97d0f501-138e-4448-93df-a4d865b524e6) |![After applying the Item Name filter](https://github.com/woocommerce/woocommerce-blocks/assets/3323310/69381932-d064-4e8f-b378-c2477fef56ae) |
## `saleBadgePriceFormat`
### Description <!-- omit in toc -->
The `saleBadgePriceFormat` filter allows to format the cart item sale badge price.
### Parameters <!-- omit in toc -->
- _defaultValue_ `string` (default: `&lt;price/&gt;`) - The default cart item sale badge price.
- _extensions_ `object` (default: `{}`) - The extensions object.
- _args_ `object` - The arguments object with the following keys:
- _cart_ `object` - The cart object from `wc/store/cart`, see Cart object.
- _cartItem_ `object` - The cart item object from `wc/store/cart`, see Cart Item object.
- _context_ `string` (allowed values: `cart` or `summary`) - The context of the item.
- _validation_ `boolean` - Checks if the return value contains the substring `&lt;price/&gt;`.
### Returns <!-- omit in toc -->
- `string` - The modified format of the cart item sale badge price, which must contain the substring `&lt;price/&gt;`, or the original price format.
### Code examples <!-- omit in toc -->
```tsx
const { registerCheckoutFilters } = window.wc.blocksCheckout;
const modifySaleBadgePriceFormat = (
defaultValue,
extensions,
args,
validation
) => {
const isCartContext = args?.context === 'cart';
if ( ! isCartContext ) {
return defaultValue;
}
return '&lt;price/&gt; per item';
};
registerCheckoutFilters( 'example-extension', {
saleBadgePriceFormat: modifySaleBadgePriceFormat,
} );
```
#### Advanced example <!-- omit in toc -->
```tsx
const { registerCheckoutFilters } = window.wc.blocksCheckout;
const modifySaleBadgePriceFormat = (
defaultValue,
extensions,
args,
validation
) => {
const isCartContext = args?.context === 'cart';
if ( ! isCartContext ) {
return defaultValue;
}
if ( args?.cartItem?.name === 'Beanie with Logo' ) {
return '&lt;price/&gt; per item while keeping warm';
}
if ( args?.cartItem?.name === 'Sunglasses' ) {
return '&lt;price/&gt; per item while looking cool';
}
return '&lt;price/&gt; per item';
};
registerCheckoutFilters( 'example-extension', {
saleBadgePriceFormat: modifySaleBadgePriceFormat,
} );
```
> Filters can be also combined. See [Combined filters](./category/cart-and-checkout-blocks/available-filters/) for an example.
### Screenshots <!-- omit in toc -->
| Before | After |
|:---------------------------------------------------------------------:|:---------------------------------------------------------------------:|
|![Before applying the Sale Badge Price Format filter](https://github.com/woocommerce/woocommerce-blocks/assets/3323310/d2aeb206-e620-44e0-93c1-31484cfcdca6) |![After applying the Sale Badge Price Format filter](https://github.com/woocommerce/woocommerce-blocks/assets/3323310/6b929695-5d89-433b-8694-b9201a7c0519) |
## `showRemoveItemLink`
### Description <!-- omit in toc -->
The `showRemoveItemLink` is used to show or hide the cart item remove link.
### Parameters <!-- omit in toc -->
- _defaultValue_ (type: `boolean`, default: `true`) - The default value of the remove link.
- _extensions_ `object` (default: `{}`) - The extensions object.
- _args_ `object` - The arguments object with the following keys:
- _cart_ `object` - The cart object from `wc/store/cart`, see Cart object.
- _cartItem_ `object` - The cart item object from `wc/store/cart`, see Cart Item object.
- _context_ `string` (allowed values: `cart` or `summary`) - The context of the item.
### Returns <!-- omit in toc -->
- `boolean` - `true` if the cart item remove link should be shown, `false` otherwise.
### Code examples <!-- omit in toc -->
#### Basic example <!-- omit in toc -->
```tsx
const { registerCheckoutFilters } = window.wc.blocksCheckout;
const modifyShowRemoveItemLink = ( defaultValue, extensions, args ) => {
const isCartContext = args?.context === 'cart';
if ( ! isCartContext ) {
return defaultValue;
}
return false;
};
registerCheckoutFilters( 'example-extension', {
showRemoveItemLink: modifyShowRemoveItemLink,
} );
```
#### Advanced example <!-- omit in toc -->
```tsx
const { registerCheckoutFilters } = window.wc.blocksCheckout;
const modifyShowRemoveItemLink = ( defaultValue, extensions, args ) => {
const isCartContext = args?.context === 'cart';
if ( ! isCartContext ) {
return defaultValue;
}
if ( args?.cartItem?.name === 'Beanie with Logo' ) {
return false;
}
if ( args?.cartItem?.name === 'Sunglasses' ) {
return false;
}
return true;
};
registerCheckoutFilters( 'example-extension', {
showRemoveItemLink: modifyShowRemoveItemLink,
} );
```
> Filters can be also combined. See [Combined filters](./category/cart-and-checkout-blocks/available-filters/) for an example.
### Screenshots <!-- omit in toc -->
| Before | After |
|:---------------------------------------------------------------------:|:---------------------------------------------------------------------:|
|![Before applying the Show Remove Item Link filter](https://github.com/woocommerce/woocommerce-blocks/assets/3323310/a4254f3b-f056-47ad-b34a-d5f6d5500e56) |![After applying the Show Remove Item Link filter](https://github.com/woocommerce/woocommerce-blocks/assets/3323310/32c55dc7-ef65-4f35-ab90-9533bc79d362) |
## `subtotalPriceFormat`
### Description <!-- omit in toc -->
The `subtotalPriceFormat` filter allows to format the cart item subtotal price.
### Parameters <!-- omit in toc -->
- _defaultValue_ `string` (default: `&lt;price/&gt;`) - The default cart item subtotal price.
- _extensions_ `object` (default: `{}`) - The extensions object.
- _args_ `object` - The arguments object with the following keys:
- _cart_ `object` - The cart object from `wc/store/cart`, see Cart object.
- _cartItem_ `object` - The cart item object from `wc/store/cart`, see Cart Item object.
- _context_ `string` (allowed values: `cart` or `summary`) - The context of the item.
- _validation_ `boolean` - Checks if the return value contains the substring `&lt;price/&gt;`.
### Returns <!-- omit in toc -->
- `string` - The modified format of the cart item subtotal price, which must contain the substring `&lt;price/&gt;`, or the original price format.
### Code examples <!-- omit in toc -->
#### Basic example <!-- omit in toc -->
```tsx
const { registerCheckoutFilters } = window.wc.blocksCheckout;
const modifySubtotalPriceFormat = (
defaultValue,
extensions,
args,
validation
) => {
const isCartContext = args?.context === 'cart';
if ( ! isCartContext ) {
return defaultValue;
}
return '&lt;price/&gt; per item';
};
registerCheckoutFilters( 'example-extension', {
subtotalPriceFormat: modifySubtotalPriceFormat,
} );
```
#### Advanced example <!-- omit in toc -->
```tsx
const { registerCheckoutFilters } = window.wc.blocksCheckout;
const modifySubtotalPriceFormat = (
defaultValue,
extensions,
args,
validation
) => {
const isCartContext = args?.context === 'cart';
if ( ! isCartContext ) {
return defaultValue;
}
if ( args?.cartItem?.name === 'Beanie with Logo' ) {
return '&lt;price/&gt; per warm beanie';
}
if ( args?.cartItem?.name === 'Sunglasses' ) {
return '&lt;price/&gt; per cool sunglasses';
}
return '&lt;price/&gt; per item';
};
registerCheckoutFilters( 'example-extension', {
subtotalPriceFormat: modifySubtotalPriceFormat,
} );
```
> Filters can be also combined. See [Combined filters](./category/cart-and-checkout-blocks/available-filters/) for an example.
### Screenshots <!-- omit in toc -->
| Before | After |
|:---------------------------------------------------------------------:|:---------------------------------------------------------------------:|
|![Before applying the Subtotal Price Format filter](https://github.com/woocommerce/woocommerce-blocks/assets/3323310/a392cb24-4c40-4e25-8396-bf4971830e22) |![After applying the Subtotal Price Format filter](https://github.com/woocommerce/woocommerce-blocks/assets/3323310/af69b26f-662a-4ef9-a288-3713b6e46373) |
## Cart object
The Cart object of the filters above has the following keys:
- _billingAddress_ `object` - The billing address object with the following keys:
- _address_1_ `string` - The first line of the address.
- _address_2_ `string` - The second line of the address.
- _city_ `string` - The city of the address.
- _company_ `string` - The company of the address.
- _country_ `string` - The country of the address.
- _email_ `string` - The email of the address.
- _first_name_ `string` - The first name of the address.
- _last_name_ `string` - The last name of the address.
- _phone_ `string` - The phone of the address.
- _postcode_ `string` - The postcode of the address.
- _state_ `string` - The state of the address.
- ~~_billingData_~~ `object` - The billing data object with the same keys as the `billingAddress` object.
- _cartCoupons_ `array` - The cart coupons array.
- _cartErrors_ `array` - The cart errors array.
- _cartFees_ `array` - The cart fees array.
- _cartHasCalculatedShipping_ `boolean` - Whether the cart has calculated shipping.
- _cartIsLoading_ `boolean` - Whether the cart is loading.
- _cartItemErrors_ `array` - The cart item errors array.
- _cartItems_ `array` - The cart items array with cart item objects, see Cart Item object.
- _cartItemsCount_ `number` - The cart items count.
- _cartItemsWeight_ `number` - The cart items weight.
- _cartNeedsPayment_ `boolean` - Whether the cart needs payment.
- _cartNeedsShipping_ `boolean` - Whether the cart needs shipping.
- _cartTotals_ `object` - The cart totals object with the following keys:
- _currency_code_ `string` - The currency code.
- _currency_decimal_separator_ `string` - The currency decimal separator.
- _currency_minor_unit_ `number` - The currency minor unit.
- _currency_prefix_ `string` - The currency prefix.
- _currency_suffix_ `string` - The currency suffix.
- _currency_symbol_ `string` - The currency symbol.
- _currency_thousand_separator_ `string` - The currency thousand separator.
- _tax_lines_ `array` - The tax lines array with tax line objects with the following keys:
- _name_ `string` - The name of the tax line.
- _price_ `number` - The price of the tax line.
- _rate_ `string` - The rate ID of the tax line.
- _total_discount_ `string` - The total discount.
- _total_discount_tax_ `string` - The total discount tax.
- _total_fees_ `string` - The total fees.
- _total_fees_tax_ `string` - The total fees tax.
- _total_items_ `string` - The total items.
- _total_items_tax_ `string` - The total items tax.
- _total_price_ `string` - The total price.
- _total_shipping_ `string` - The total shipping.
- _total_shipping_tax_ `string` - The total shipping tax.
- _total_tax_ `string` - The total tax.
- _crossSellsProducts_ `array` - The cross sells products array with cross sells product objects.
- _extensions_ `object` (default: `{}`) - The extensions object.
- _isLoadingRates_ `boolean` - Whether the cart is loading rates.
- _paymentRequirements_ `array` - The payment requirements array.
- _shippingAddress_ `object` - The shipping address object with the same keys as the `billingAddress` object.
- _shippingRates_ `array` - The shipping rates array.
## Cart Item object
The Cart Item object of the filters above has the following keys:
- _backorders_allowed_ `boolean` - Whether backorders are allowed.
- _catalog_visibility_ `string` - The catalog visibility.
- _decsription_ `string` - The cart item description.
- _extensions_ `object` (default: `{}`) - The extensions object.
- _id_ `number` - The item ID.
- _images_ `array` - The item images array.
- _item_data_ `array` - The item data array.
- _key_ `string` - The item key.
- _low_stock_remaining_ `number` - The low stock remaining.
- _name_ `string` - The item name.
- _permalink_ `string` - The item permalink.
- _prices_ `object` - The item prices object with the following keys:
- _currency_code_ `string` - The currency code.
- _currency_decimal_separator_ `string` - The currency decimal separator.
- _currency_minor_unit_ `number` - The currency minor unit.
- _currency_prefix_ `string` - The currency prefix.
- _currency_suffix_ `string` - The currency suffix.
- _currency_symbol_ `string` - The currency symbol.
- _currency_thousand_separator_ `string` - The currency thousand separator.
- _price_ `string` - The price.
- _price_range_ `string` - The price range.
- _raw_prices_ `object` - The raw prices object with the following keys:
- _precision_ `number` - The precision.
- _price_ `number` - The price.
- _regular_price_ `number` - The regular price.
- _sale_price_ `number` - The sale price.
- _regular_price_ `string` - The regular price.
- _sale_price_ `string` - The sale price.
- _quantity_ `number` - The item quantity.
- _quantity_limits_ `object` - The item quantity limits object with the following keys:
- _editable_ `boolean` - Whether the quantity is editable.
- _maximum_ `number` - The maximum quantity.
- _minimum_ `number` - The minimum quantity.
- _multiple_of_ `number` - The multiple of quantity.
- _short_description_ `string` - The item short description.
- _show_backorder_badge_ `boolean` - Whether to show the backorder badge.
- _sku_ `string` - The item SKU.
- _sold_individually_ `boolean` - Whether the item is sold individually.
- _totals_ `object` - The item totals object with the following keys:
- _currency_code_ `string` - The currency code.
- _currency_decimal_separator_ `string` - The currency decimal separator.
- _currency_minor_unit_ `number` - The currency minor unit.
- _currency_prefix_ `string` - The currency prefix.
- _currency_suffix_ `string` - The currency suffix.
- _currency_symbol_ `string` - The currency symbol.
- _currency_thousand_separator_ `string` - The currency thousand separator.
- _line_subtotal_ `string` - The line subtotal.
- _line_subtotal_tax_ `string` - The line subtotal tax.
- _line_total_ `string` - The line total.
- _line_total_tax_ `string` - The line total tax.
- _type_ `string` - The item type.
- _variation_ `array` - The item variation array.

View File

@ -0,0 +1,325 @@
---
post_title: Cart and Checkout Filters - Checkout and place order button
menu_title: Checkout and Place Order Button
tags: reference
---
<!-- markdownlint-disable MD024 -->
The following Checkout and place order button filters are available:
- `proceedToCheckoutButtonLabel`
- `proceedToCheckoutButtonLink`
- `placeOrderButtonLabel`
The following objects are shared between the filters:
- Cart object
- Cart Item object
## `proceedToCheckoutButtonLabel`
### Description <!-- omit in toc -->
The `proceedToCheckoutButtonLabel` filter allows change the label of the "Proceed to checkout" button.
### Parameters <!-- omit in toc -->
- _defaultValue_ `string` (default: `Proceed to Checkout`) - The label of the "Proceed to checkout" button.
- _extensions_ `object` (default: `{}`) - The extensions object.
- _args_ `object` - The arguments object with the following keys:
- _cart_ `object` - The cart object from `wc/store/cart`, see [Cart object](#cart-object).
### Returns <!-- omit in toc -->
- `string` - The label of the "Proceed to checkout" button.
### Code examples <!-- omit in toc -->
#### Basic example <!-- omit in toc -->
```ts
const { registerCheckoutFilters } = window.wc.blocksCheckout;
const modifyProceedToCheckoutButtonLabel = (
defaultValue,
extensions,
args
) => {
if ( ! args?.cart.items ) {
return defaultValue;
}
return 'Go to checkout';
};
registerCheckoutFilters( 'example-extension', {
proceedToCheckoutButtonLabel: modifyProceedToCheckoutButtonLabel,
} );
```
#### Advanced example <!-- omit in toc -->
```ts
const { registerCheckoutFilters } = window.wc.blocksCheckout;
const modifyProceedToCheckoutButtonLabel = (
defaultValue,
extensions,
args
) => {
if ( ! args?.cart.items ) {
return defaultValue;
}
const isSunglassesInCart = args?.cart.items.some(
( item ) => item.name === 'Sunglasses'
);
if ( isSunglassesInCart ) {
return '😎 Proceed to checkout 😎';
}
return defaultValue;
};
registerCheckoutFilters( 'example-extension', {
proceedToCheckoutButtonLabel: modifyProceedToCheckoutButtonLabel,
} );
```
> Filters can be also combined. See [Combined filters](./category/cart-and-checkout-blocks/available-filters/) for an example.
### Screenshots <!-- omit in toc -->
| Before | After |
|:---------------------------------------------------------------------:|:---------------------------------------------------------------------:|
|![Before applying the Proceed To Checkout Button Label filter](https://github.com/woocommerce/woocommerce-blocks/assets/3323310/fb0216c1-a091-4d58-b443-f49ccff98ed8) |![After applying the Item Name filter](https://github.com/woocommerce/woocommerce-blocks/assets/3323310/ef15b6df-fbd7-43e7-a359-b4adfbba961a) |
## `proceedToCheckoutButtonLink`
### Description <!-- omit in toc -->
The `proceedToCheckoutButtonLink` filter allows change the link of the "Proceed to checkout" button.
### Parameters <!-- omit in toc -->
- _defaultValue_ `string` (default: `/checkout`) - The link of the "Proceed to checkout" button.
- _extensions_ `object` (default: `{}`) - The extensions object.
- _args_ `object` - The arguments object with the following keys:
- _cart_ `object` - The cart object from `wc/store/cart`, see [Cart object](./category/cart-and-checkout-blocks/available-filters/).
### Returns <!-- omit in toc -->
- `string` - The link of the "Proceed to checkout" button.
### Code examples <!-- omit in toc -->
#### Basic example <!-- omit in toc -->
```ts
const { registerCheckoutFilters } = window.wc.blocksCheckout;
const modifyProceedToCheckoutButtonLink = (
defaultValue,
extensions,
args
) => {
if ( ! args?.cart.items ) {
return defaultValue;
}
return '/custom-checkout';
};
registerCheckoutFilters( 'example-extension', {
proceedToCheckoutButtonLink: modifyProceedToCheckoutButtonLink,
} );
```
#### Advanced example <!-- omit in toc -->
```ts
const { registerCheckoutFilters } = window.wc.blocksCheckout;
const modifyProceedToCheckoutButtonLink = (
defaultValue,
extensions,
args
) => {
if ( ! args?.cart.items ) {
return defaultValue;
}
const isSunglassesInCart = args?.cart.items.some(
( item ) => item.name === 'Sunglasses'
);
if ( isSunglassesInCart ) {
return '/custom-checkout';
}
return defaultValue;
};
registerCheckoutFilters( 'example-extension', {
proceedToCheckoutButtonLink: modifyProceedToCheckoutButtonLink,
} );
```
> Filters can be also combined. See [Combined filters](./category/cart-and-checkout-blocks/available-filters/) for an example.
### Screenshots <!-- omit in toc -->
| Before | After |
|:---------------------------------------------------------------------:|:---------------------------------------------------------------------:|
|![Before applying the Proceed To Checkout Button Link filter](https://github.com/woocommerce/woocommerce-blocks/assets/3323310/3f657e0f-4fcc-4746-a554-64221e071b2e) |![After applying the Proceed To Checkout Button Link filter](https://github.com/woocommerce/woocommerce-blocks/assets/3323310/064df213-439e-4d8f-b29c-55962604cb97) |
## `placeOrderButtonLabel`
### Description <!-- omit in toc -->
The `placeOrderButtonLabel` filter allows change the label of the "Place order" button.
### Parameters <!-- omit in toc -->
- _defaultValue_ (type: `string`, default: `Place order`) - The label of the "Place order" button.
- _extensions_ `object` (default: `{}`) - The extensions object.
### Returns <!-- omit in toc -->
- `string` - The label of the "Place order" button.
### Code example <!-- omit in toc -->
```ts
const { registerCheckoutFilters } = window.wc.blocksCheckout;
const modifyPlaceOrderButtonLabel = ( defaultValue, extensions ) => {
return '😎 Pay now 😎';
};
registerCheckoutFilters( 'example-extension', {
placeOrderButtonLabel: modifyPlaceOrderButtonLabel,
} );
```
> Filters can be also combined. See [Combined filters](./category/cart-and-checkout-blocks/available-filters/) for an example.
### Screenshots <!-- omit in toc -->
| Before | After |
|:---------------------------------------------------------------------:|:---------------------------------------------------------------------:|
|![Before applying the Place Order Button Label filter](https://github.com/woocommerce/woocommerce-blocks/assets/3323310/aa6d9b65-4d56-45f7-8162-a6bbfe171250) |![After applying the Place Order Button Label filter](https://github.com/woocommerce/woocommerce-blocks/assets/3323310/a5cc2572-16e7-4781-a5ab-5d6cdced2ff6) |
<!-- FEEDBACK -->
## Cart object
The Cart object of the filters above has the following keys:
- _billingAddress_ `object` - The billing address object with the following keys:
- _address_1_ `string` - The first line of the address.
- _address_2_ `string` - The second line of the address.
- _city_ `string` - The city of the address.
- _company_ `string` - The company of the address.
- _country_ `string` - The country of the address.
- _email_ `string` - The email of the address.
- _first_name_ `string` - The first name of the address.
- _last_name_ `string` - The last name of the address.
- _phone_ `string` - The phone of the address.
- _postcode_ `string` - The postcode of the address.
- _state_ `string` - The state of the address.
- _coupons_ `array` - The coupons array.
- _crossSells_ `array` - The cross sell items array.
- _errors_ `array` - The errors array.
- _extensions_ `object` (default: `{}`) - The extensions object.
- _fees_ `array` - The fees array.
- _hasCalculatedShipping_ `boolean` - Whether the cart has calculated shipping.
- _items_ `array` - The cart items array with cart item objects, see [Cart Item object](#cart-item-object).
- _itemsCount_ `number` - The number of items in the cart.
- _itemsWeight_ `number` - The total weight of the cart items.
- _needsPayment_ `boolean` - Whether the cart needs payment.
- _needsShipping_ `boolean` - Whether the cart needs shipping.
- _paymentMethods_ `array` - The payment methods array.
- _paymentRequirements_ `array` - The payment requirements array.
- _shippingAddress_ `object` - The shipping address object with the same keys as the billing address object.
- _shippingRates_ `array` - The shipping rates array.
- _totals_ `object` - The totals object with the following keys:
- _currency_code_ `string` - The currency code.
- _currency_decimal_separator_ `string` - The currency decimal separator.
- _currency_minor_unit_ `number` - The currency minor unit.
- _currency_prefix_ `string` - The currency prefix.
- _currency_suffix_ `string` - The currency suffix.
- _currency_symbol_ `string` - The currency symbol.
- _currency_thousand_separator_ `string` - The currency thousand separator.
- _tax_lines_ `array` - The tax lines array of objects with the following keys:
- _name_ `string` - The tax name.
- _price_ `string` - The tax price.
- _rate_ `string` - The tax rate.
- _total_discount_ `string` - The total discount.
- _total_discount_tax_ `string` - The total discount tax.
- _total_fee_ `string` - The total fee.
- _total_fee_tax_ `string` - The total fee tax.
- _total_items_ `string` - The total items.
- _total_items_tax_ `string` - The total items tax.
- _total_price_ `string` - The total price.
- _total_shipping_ `string` - The total shipping.
- _total_shipping_tax_ `string` - The total shipping tax.
- _total_tax_ `string` - The total tax.
## Cart Item object
The Cart Item object of the filters above has the following keys:
- _backorders_allowed_ `boolean` - Whether backorders are allowed.
- _catalog_visibility_ `string` - The catalog visibility.
- _decsription_ `string` - The cart item description.
- _extensions_ `object` (default: `{}`) - The extensions object.
- _id_ `number` - The item ID.
- _images_ `array` - The item images array.
- _item_data_ `array` - The item data array.
- _key_ `string` - The item key.
- _low_stock_remaining_ `number` - The low stock remaining.
- _name_ `string` - The item name.
- _permalink_ `string` - The item permalink.
- _prices_ `object` - The item prices object with the following keys:
- _currency_code_ `string` - The currency code.
- _currency_decimal_separator_ `string` - The currency decimal separator.
- _currency_minor_unit_ `number` - The currency minor unit.
- _currency_prefix_ `string` - The currency prefix.
- _currency_suffix_ `string` - The currency suffix.
- _currency_symbol_ `string` - The currency symbol.
- _currency_thousand_separator_ `string` - The currency thousand separator.
- _price_ `string` - The price.
- _price_range_ `string` - The price range.
- _raw_prices_ `object` - The raw prices object with the following keys:
- _precision_ `number` - The precision.
- _price_ `number` - The price.
- _regular_price_ `number` - The regular price.
- _sale_price_ `number` - The sale price.
- _regular_price_ `string` - The regular price.
- _sale_price_ `string` - The sale price.
- _quantity_ `number` - The item quantity.
- _quantity_limits_ `object` - The item quantity limits object with the following keys:
- _editable_ `boolean` - Whether the quantity is editable.
- _maximum_ `number` - The maximum quantity.
- _minimum_ `number` - The minimum quantity.
- _multiple_of_ `number` - The multiple of quantity.
- _short_description_ `string` - The item short description.
- _show_backorder_badge_ `boolean` - Whether to show the backorder badge.
- _sku_ `string` - The item SKU.
- _sold_individually_ `boolean` - Whether the item is sold individually.
- _totals_ `object` - The item totals object with the following keys:
- _currency_code_ `string` - The currency code.
- _currency_decimal_separator_ `string` - The currency decimal separator.
- _currency_minor_unit_ `number` - The currency minor unit.
- _currency_prefix_ `string` - The currency prefix.
- _currency_suffix_ `string` - The currency suffix.
- _currency_symbol_ `string` - The currency symbol.
- _currency_thousand_separator_ `string` - The currency thousand separator.
- _line_subtotal_ `string` - The line subtotal.
- _line_subtotal_tax_ `string` - The line subtotal tax.
- _line_total_ `string` - The line total.
- _line_total_tax_ `string` - The line total tax.
- _type_ `string` - The item type.
- _variation_ `array` - The item variation array.

View File

@ -0,0 +1,189 @@
---
post_title: Cart and Checkout Filters - Coupons
menu_title: Coupons
tags: reference
---
<!-- markdownlint-disable MD024 -->
The following Coupon filters are available:
- `coupons`
- `showApplyCouponNotice`
- `showRemoveCouponNotice`
## `coupons`
### Description <!-- omit in toc -->
The current functionality is to display the coupon codes in the Cart and Checkout sidebars. This could be undesirable if you dynamically generate a coupon code that is not user-friendly. It may, therefore, be desirable to change the way this code is displayed. To achieve this, the filter `coupons` exists. This filter could also be used to show or hide coupons. This filter must _not_ be used to alter the value/totals of a coupon. This will not carry through to the Cart totals.
### Parameters <!-- omit in toc -->
- _coupons_ `object` - The coupons object with the following keys:
- _code_ `string` - The coupon code.
- _discount_type_ `string` - The type of discount. Can be `percent` or `fixed_cart`.
- _totals_ `object` - The totals object with the following keys:
- _currency_code_ `string` - The currency code.
- _currency_decimal_separator_ `string` - The currency decimal separator.
- _currency_minor_unit_ `number` - The currency minor unit.
- _currency_prefix_ `string` - The currency prefix.
- _currency_suffix_ `string` - The currency suffix.
- _currency_symbol_ `string` - The currency symbol.
- _currency_thousand_separator_ `string` - The currency thousand separator.
- _total_discount_ `string` - The total discount.
- _total_discount_tax_ `string` - The total discount tax.
- _extensions_ `object` (default: `{}`) - The extensions object.
- _args_ `object` - The arguments object with the following key:
- _context_ `string` (default: `summary`) - The context of the item.
### Returns <!-- omit in toc -->
- `array` - The coupons array of objects with the same keys as above.
### Code example <!-- omit in toc -->
```ts
const { registerCheckoutFilters } = window.wc.blocksCheckout;
const modifyCoupons = ( coupons, extensions, args ) => {
return coupons.map( ( coupon ) => {
if ( ! coupon.label.match( /autocoupon(?:_\d+)+/ ) ) {
return coupon;
}
return {
...coupon,
label: 'Automatic coupon',
};
} );
};
registerCheckoutFilters( 'example-extension', {
coupons: modifyCoupons,
} );
```
> Filters can be also combined. See [Combined filters](./category/cart-and-checkout-blocks/available-filters/) for an example.
### Screenshots <!-- omit in toc -->
| Before | After |
|:---------------------------------------------------------------------:|:---------------------------------------------------------------------:|
|![Before applying the Coupons filter](https://github.com/woocommerce/woocommerce-blocks/assets/3323310/6cab1aff-e4b9-4909-b81c-5726c6a20c40) |![After applying the Coupons filter](https://github.com/woocommerce/woocommerce-blocks/assets/3323310/a5cc2572-16e7-4781-a5ab-5d6cdced2ff6) |
## `showApplyCouponNotice`
### Description <!-- omit in toc -->
### Parameters <!-- omit in toc -->
- _value_ `boolean` (default: `true`) - Weather to show the apply coupon notice.
- _extensions_ `object` (default: `{}`) - The extensions object.
- _args_ `object` - The arguments object with the following keys:
- _context_ `string` (allowed values: `wc/cart` and `wc/checkout`) - The context of the coupon notice.
- _code_ `string` - The coupon code.
### Returns <!-- omit in toc -->
- `boolean` - Weather to show the apply coupon notice.
### Code examples <!-- omit in toc -->
#### Basic example <!-- omit in toc -->
```ts
const { registerCheckoutFilters } = window.wc.blocksCheckout;
const modifyShowApplyCouponNotice = ( defaultValue, extensions, args ) => {
return false;
};
registerCheckoutFilters( 'example-extension', {
showApplyCouponNotice: modifyShowApplyCouponNotice,
} );
```
#### Advanced example <!-- omit in toc -->
```ts
const { registerCheckoutFilters } = window.wc.blocksCheckout;
const modifyShowApplyCouponNotice = ( defaultValue, extensions, args ) => {
if ( args?.couponCode === '10off' ) {
return false;
}
return defaultValue;
};
registerCheckoutFilters( 'example-extension', {
showApplyCouponNotice: modifyShowApplyCouponNotice,
} );
```
> Filters can be also combined. See [Combined filters](./category/cart-and-checkout-blocks/available-filters/) for an example.
### Screenshots <!-- omit in toc -->
| Before | After |
|:---------------------------------------------------------------------:|:---------------------------------------------------------------------:|
|![Before applying the Show Apply Coupon Notice filter](https://github.com/woocommerce/woocommerce-blocks/assets/3323310/374d4899-61f3-49b2-ae04-5541d4c130c2) |![After applying the Show Apply Coupon Notice filter](https://github.com/woocommerce/woocommerce-blocks/assets/3323310/c35dbd9b-eee4-4afe-9a29-9c554d467729) |
## `showRemoveCouponNotice`
### Description <!-- omit in toc -->
### Parameters <!-- omit in toc -->
- _value_ `boolean` (default: `true`) - Weather to show the remove coupon notice.
- _extensions_ `object` (default: `{}`) - The extensions object.
- _args_ `object` - The arguments object with the following keys:
- _context_ `string` (allowed values: `wc/cart` and `wc/checkout`) - The context of the coupon notice.
- _code_ `string` - The coupon code.
### Returns <!-- omit in toc -->
- `boolean` - Weather to show the apply coupon notice.
### Code examples <!-- omit in toc -->
#### Basic example <!-- omit in toc -->
```ts
const { registerCheckoutFilters } = window.wc.blocksCheckout;
const modifyShowRemoveCouponNotice = ( defaultValue, extensions, args ) => {
return false;
};
registerCheckoutFilters( 'example-extension', {
showRemoveCouponNotice: modifyShowRemoveCouponNotice,
} );
```
#### Advanced example <!-- omit in toc -->
```ts
const { registerCheckoutFilters } = window.wc.blocksCheckout;
const modifyShowRemoveCouponNotice = ( defaultValue, extensions, args ) => {
if ( args?.couponCode === '10off' ) {
return false;
}
return defaultValue;
};
registerCheckoutFilters( 'example-extension', {
showRemoveCouponNotice: modifyShowRemoveCouponNotice,
} );
```
> Filters can be also combined. See [Combined filters](./category/cart-and-checkout-blocks/available-filters/) for an example.
### Screenshots <!-- omit in toc -->
| Before | After |
|:---------------------------------------------------------------------:|:---------------------------------------------------------------------:|
|![Before applying the Show Remove Coupon Notice filter](https://github.com/woocommerce/woocommerce-blocks/assets/3323310/9d8607fa-ab20-4181-b70b-7954e7aa49cb) |![After applying the Show Remove Coupon Notice filter](https://github.com/woocommerce/woocommerce-blocks/assets/3323310/83d5f65f-c4f3-4707-a250-077952514931) |

View File

@ -0,0 +1,456 @@
---
post_title: Cart and Checkout Filters - Order summary items
menu_title: Order Summary Items
tags: reference
---
<!-- markdownlint-disable MD024 -->
The following Order Summary Items filters are available:
- `cartItemClass`
- `cartItemPrice`
- `itemName`
- `subtotalPriceFormat`
The following objects are shared between the filters:
- Cart object
- Cart Item object
The following screenshot shows which parts the individual filters affect:
![Order Summary Items](https://woocommerce.com/wp-content/uploads/2023/10/Screenshot-2023-10-26-at-16.29.45.png)
## `cartItemClass`
### Description <!-- omit in toc -->
The `cartItemClass` filter allows to change the order summary item class.
### Parameters <!-- omit in toc -->
- _defaultValue_ `string` (default: `''`) - The default order summary item class.
- _extensions_ `object` (default: `{}`) - The extensions object.
- _args_ `object` - The arguments object with the following keys:
- _cart_ `object` - The cart object from `wc/store/cart`, see [Cart object](#cart-object).
- _cartItem_ `object` - The order summary item object from `wc/store/cart`, see [order summary item object](#cart-item-object).
- _context_ `string` (allowed values: `cart` or `summary`) - The context of the item.
### Returns <!-- omit in toc -->
- `string` - The modified order summary item class, or an empty string.
### Code examples <!-- omit in toc -->
#### Basic example <!-- omit in toc -->
```tsx
const { registerCheckoutFilters } = window.wc.blocksCheckout;
const modifyCartItemClass = ( defaultValue, extensions, args ) => {
const isOrderSummaryContext = args?.context === 'summary';
if ( ! isOrderSummaryContext ) {
return defaultValue;
}
return 'my-custom-class';
};
registerCheckoutFilters( 'example-extension', {
cartItemClass: modifyCartItemClass,
} );
```
#### Advanced example <!-- omit in toc -->
```tsx
const { registerCheckoutFilters } = window.wc.blocksCheckout;
const modifyCartItemClass = ( defaultValue, extensions, args ) => {
const isOrderSummaryContext = args?.context === 'summary';
if ( ! isOrderSummaryContext ) {
return defaultValue;
}
if ( args?.cartItem?.name === 'Beanie with Logo' ) {
return 'cool-class';
}
if ( args?.cartItem?.name === 'Sunglasses' ) {
return 'hot-class';
}
return 'my-custom-class';
};
registerCheckoutFilters( 'example-extension', {
cartItemClass: modifyCartItemClass,
} );
```
> Filters can be also combined. See [Combined filters](./category/cart-and-checkout-blocks/available-filters/) for an example.
### Screenshots <!-- omit in toc -->
| Before | After |
|:---------------------------------------------------------------------:|:---------------------------------------------------------------------:|
|![Before applying the Cart Item Class filter](https://github.com/woocommerce/woocommerce-blocks/assets/3323310/ff555a84-8d07-4889-97e1-8f7d50d47350) |![After applying the Cart Item Class filter](https://github.com/woocommerce/woocommerce-blocks/assets/3323310/183809d8-03dc-466d-a415-d8d2062d880f) |
## `cartItemPrice`
### Description <!-- omit in toc -->
The `cartItemPrice` filter allows to format the order summary item price.
### Parameters <!-- omit in toc -->
- _defaultValue_ `string` (default: `<price/>`) - The default order summary item price.
- _extensions_ `object` (default: `{}`) - The extensions object.
- _args_ `object` - The arguments object with the following keys:
- _cart_ `object` - The cart object from `wc/store/cart`, see [Cart object](#cart-object).
- _cartItem_ `object` - The order summary item object from `wc/store/cart`, see [order summary item object](#cart-item-object).
- _context_ `string` (allowed values: `cart` or `summary`) - The context of the item.
- _validation_ `boolean` - Checks if the return value contains the substring `<price/>`.
### Returns <!-- omit in toc -->
- `string` - The modified format of the order summary item price, which must contain the substring `<price/>`, or the original price format.
### Code examples <!-- omit in toc -->
#### Basic example <!-- omit in toc -->
```tsx
const { registerCheckoutFilters } = window.wc.blocksCheckout;
const modifyCartItemPrice = ( defaultValue, extensions, args, validation ) => {
const isOrderSummaryContext = args?.context === 'summary';
if ( ! isOrderSummaryContext ) {
return defaultValue;
}
return '<price/> for all items';
};
registerCheckoutFilters( 'example-extension', {
cartItemPrice: modifyCartItemPrice,
} );
```
#### Advanced example <!-- omit in toc -->
```tsx
const { registerCheckoutFilters } = window.wc.blocksCheckout;
const modifyCartItemPrice = ( defaultValue, extensions, args, validation ) => {
const isOrderSummaryContext = args?.context === 'summary';
if ( ! isOrderSummaryContext ) {
return defaultValue;
}
if ( args?.cartItem?.name === 'Beanie with Logo' ) {
return '<price/> to keep you ☀️';
}
if ( args?.cartItem?.name === 'Sunglasses' ) {
return '<price/> to keep you ❄️';
}
return '<price/> for all items';
};
registerCheckoutFilters( 'example-extension', {
cartItemPrice: modifyCartItemPrice,
} );
```
> Filters can be also combined. See [Combined filters](./category/cart-and-checkout-blocks/available-filters/) for an example.
### Screenshots <!-- omit in toc -->
| Before | After |
|:---------------------------------------------------------------------:|:---------------------------------------------------------------------:|
|![Before applying the Cart Item Price filter](https://github.com/woocommerce/woocommerce-blocks/assets/3323310/58137fc4-884d-4783-9275-5f78abec1473) |![After applying the Cart Item Price filter](https://github.com/woocommerce/woocommerce-blocks/assets/3323310/fb502b74-6447-49a8-8d35-241e738f089d) |
## `itemName`
### Description <!-- omit in toc -->
The `itemName` filter allows to change the order summary item name.
### Parameters <!-- omit in toc -->
- _defaultValue_ `string` - The default order summary item name.
- _extensions_ `object` (default: `{}`) - The extensions object.
- _args_ `object` - The arguments object with the following keys:
- _cart_ `object` - The cart object from `wc/store/cart`, see [Cart object](#cart-object).
- _cartItem_ `object` - The order summary item object from `wc/store/cart`, see [order summary item object](#cart-item-object).
- _context_ `string` (allowed values: `cart` or `summary`) - The context of the item.
### Returns <!-- omit in toc -->
- `string` - The original or modified order summary item name.
### Code examples <!-- omit in toc -->
#### Basic example <!-- omit in toc -->
```tsx
const { registerCheckoutFilters } = window.wc.blocksCheckout;
const modifyItemName = ( defaultValue, extensions, args ) => {
const isOrderSummaryContext = args?.context === 'summary';
if ( ! isOrderSummaryContext ) {
return defaultValue;
}
return `🪴 ${ defaultValue } 🪴`;
};
registerCheckoutFilters( 'example-extension', {
itemName: modifyItemName,
} );
```
#### Advanced example <!-- omit in toc -->
```tsx
const { registerCheckoutFilters } = window.wc.blocksCheckout;
const modifyItemName = ( defaultValue, extensions, args ) => {
const isOrderSummaryContext = args?.context === 'summary';
if ( ! isOrderSummaryContext ) {
return defaultValue;
}
if ( args?.cartItem?.name === 'Beanie with Logo' ) {
return `⛷️ ${ defaultValue } ⛷️`;
}
if ( args?.cartItem?.name === 'Sunglasses' ) {
return `🏄‍♂️ ${ defaultValue } 🏄‍♂️`;
}
return `🪴 ${ defaultValue } 🪴`;
};
registerCheckoutFilters( 'example-extension', {
itemName: modifyItemName,
} );
```
> Filters can be also combined. See [Combined filters](./category/cart-and-checkout-blocks/available-filters/) for an example.
### Screenshots <!-- omit in toc -->
| Before | After |
|:---------------------------------------------------------------------:|:---------------------------------------------------------------------:|
|![Before applying the Item Name filter](https://github.com/woocommerce/woocommerce-blocks/assets/3323310/3dc0bda7-fccf-4f35-a2e2-aa04e616563a) |![After applying the Item Name filter](https://github.com/woocommerce/woocommerce-blocks/assets/3323310/c96b8394-03a7-45f6-813b-5335f4bf83b5) |
## `subtotalPriceFormat`
### Description <!-- omit in toc -->
The `subtotalPriceFormat` filter allows to format the order summary item subtotal price.
### Parameters <!-- omit in toc -->
- _defaultValue_ `string` (default: `<price/>`) - The default order summary item subtotal price.
- _extensions_ `object` (default: `{}`) - The extensions object.
- _args_ `object` - The arguments object with the following keys:
- _cart_ `object` - The cart object from `wc/store/cart`, see [Cart object](#cart-object).
- _cartItem_ `object` - The order summary item object from `wc/store/cart`, see [order summary item object](#cart-item-object).
- _context_ `string` (allowed values: `cart` or `summary`) - The context of the item.
- _validation_ `boolean` - Checks if the return value contains the substring `<price/>`.
### Returns <!-- omit in toc -->
- `string` - The modified format of the order summary item subtotal price, which must contain the substring `<price/>`, or the original price format.
### Code examples <!-- omit in toc -->
#### Basic example <!-- omit in toc -->
```tsx
const { registerCheckoutFilters } = window.wc.blocksCheckout;
const modifySubtotalPriceFormat = (
defaultValue,
extensions,
args,
validation
) => {
const isOrderSummaryContext = args?.context === 'summary';
if ( ! isOrderSummaryContext ) {
return defaultValue;
}
return '<price/> per item';
};
registerCheckoutFilters( 'example-extension', {
subtotalPriceFormat: modifySubtotalPriceFormat,
} );
```
#### Advanced example <!-- omit in toc -->
```tsx
const { registerCheckoutFilters } = window.wc.blocksCheckout;
const modifySubtotalPriceFormat = (
defaultValue,
extensions,
args,
validation
) => {
const isOrderSummaryContext = args?.context === 'summary';
if ( ! isOrderSummaryContext ) {
return defaultValue;
}
if ( args?.cartItem?.name === 'Beanie with Logo' ) {
return '<price/> per warm beanie';
}
if ( args?.cartItem?.name === 'Sunglasses' ) {
return '<price/> per cool sunglasses';
}
return '<price/> per item';
};
registerCheckoutFilters( 'example-extension', {
subtotalPriceFormat: modifySubtotalPriceFormat,
} );
```
> Filters can be also combined. See [Combined filters](./category/cart-and-checkout-blocks/available-filters/) for an example.
### Screenshots <!-- omit in toc -->
| Before | After |
|:---------------------------------------------------------------------:|:---------------------------------------------------------------------:|
|![Before applying the Subtotal Price Format filter](https://github.com/woocommerce/woocommerce-blocks/assets/3323310/3574e7ae-9857-4651-ac9e-e6b597e3a589) |![After applying the Subtotal Price Format filter](https://github.com/woocommerce/woocommerce-blocks/assets/3323310/94e18439-6d6b-44a4-ade1-8302c5984641) |
## Cart object
The Cart object of the filters above has the following keys:
- _billingAddress_ `object` - The billing address object with the following keys:
- _address_1_ `string` - The first line of the address.
- _address_2_ `string` - The second line of the address.
- _city_ `string` - The city of the address.
- _company_ `string` - The company of the address.
- _country_ `string` - The country of the address.
- _email_ `string` - The email of the address.
- _first_name_ `string` - The first name of the address.
- _last_name_ `string` - The last name of the address.
- _phone_ `string` - The phone of the address.
- _postcode_ `string` - The postcode of the address.
- _state_ `string` - The state of the address.
- ~~_billingData_~~ `object` - The billing data object with the same keys as the `billingAddress` object.
- _cartCoupons_ `array` - The cart coupons array.
- _cartErrors_ `array` - The cart errors array.
- _cartFees_ `array` - The cart fees array.
- _cartHasCalculatedShipping_ `boolean` - Whether the cart has calculated shipping.
- _cartIsLoading_ `boolean` - Whether the cart is loading.
- _cartItemErrors_ `array` - The cart item errors array.
- _cartItems_ `array` - The cart items array with cart item objects, see [Cart Item object](#cart-item-object).
- _cartItemsCount_ `number` - The cart items count.
- _cartItemsWeight_ `number` - The cart items weight.
- _cartNeedsPayment_ `boolean` - Whether the cart needs payment.
- _cartNeedsShipping_ `boolean` - Whether the cart needs shipping.
- _cartTotals_ `object` - The cart totals object with the following keys:
- _currency_code_ `string` - The currency code.
- _currency_decimal_separator_ `string` - The currency decimal separator.
- _currency_minor_unit_ `number` - The currency minor unit.
- _currency_prefix_ `string` - The currency prefix.
- _currency_suffix_ `string` - The currency suffix.
- _currency_symbol_ `string` - The currency symbol.
- _currency_thousand_separator_ `string` - The currency thousand separator.
- _tax_lines_ `array` - The tax lines array with tax line objects with the following keys:
- _name_ `string` - The name of the tax line.
- _price_ `number` - The price of the tax line.
- _rate_ `string` - The rate ID of the tax line.
- _total_discount_ `string` - The total discount.
- _total_discount_tax_ `string` - The total discount tax.
- _total_fees_ `string` - The total fees.
- _total_fees_tax_ `string` - The total fees tax.
- _total_items_ `string` - The total items.
- _total_items_tax_ `string` - The total items tax.
- _total_price_ `string` - The total price.
- _total_shipping_ `string` - The total shipping.
- _total_shipping_tax_ `string` - The total shipping tax.
- _total_tax_ `string` - The total tax.
- _crossSellsProducts_ `array` - The cross sells products array with cross sells product objects.
- _extensions_ `object` (default: `{}`) - The extensions object.
- _isLoadingRates_ `boolean` - Whether the cart is loading rates.
- _paymentRequirements_ `array` - The payment requirements array.
- _shippingAddress_ `object` - The shipping address object with the same keys as the `billingAddress` object.
- _shippingRates_ `array` - The shipping rates array.
## Cart Item object
The Cart Item object of the filters above has the following keys:
- _backorders_allowed_ `boolean` - Whether backorders are allowed.
- _catalog_visibility_ `string` - The catalog visibility.
- _decsription_ `string` - The cart item description.
- _extensions_ `object` (default: `{}`) - The extensions object.
- _id_ `number` - The item ID.
- _images_ `array` - The item images array.
- _item_data_ `array` - The item data array.
- _key_ `string` - The item key.
- _low_stock_remaining_ `number` - The low stock remaining.
- _name_ `string` - The item name.
- _permalink_ `string` - The item permalink.
- _prices_ `object` - The item prices object with the following keys:
- _currency_code_ `string` - The currency code.
- _currency_decimal_separator_ `string` - The currency decimal separator.
- _currency_minor_unit_ `number` - The currency minor unit.
- _currency_prefix_ `string` - The currency prefix.
- _currency_suffix_ `string` - The currency suffix.
- _currency_symbol_ `string` - The currency symbol.
- _currency_thousand_separator_ `string` - The currency thousand separator.
- _price_ `string` - The price.
- _price_range_ `string` - The price range.
- _raw_prices_ `object` - The raw prices object with the following keys:
- _precision_ `number` - The precision.
- _price_ `number` - The price.
- _regular_price_ `number` - The regular price.
- _sale_price_ `number` - The sale price.
- _regular_price_ `string` - The regular price.
- _sale_price_ `string` - The sale price.
- _quantity_ `number` - The item quantity.
- _quantity_limits_ `object` - The item quantity limits object with the following keys:
- _editable_ `boolean` - Whether the quantity is editable.
- _maximum_ `number` - The maximum quantity.
- _minimum_ `number` - The minimum quantity.
- _multiple_of_ `number` - The multiple of quantity.
- _short_description_ `string` - The item short description.
- _show_backorder_badge_ `boolean` - Whether to show the backorder badge.
- _sku_ `string` - The item SKU.
- _sold_individually_ `boolean` - Whether the item is sold individually.
- _totals_ `object` - The item totals object with the following keys:
- _currency_code_ `string` - The currency code.
- _currency_decimal_separator_ `string` - The currency decimal separator.
- _currency_minor_unit_ `number` - The currency minor unit.
- _currency_prefix_ `string` - The currency prefix.
- _currency_suffix_ `string` - The currency suffix.
- _currency_symbol_ `string` - The currency symbol.
- _currency_thousand_separator_ `string` - The currency thousand separator.
- _line_subtotal_ `string` - The line subtotal.
- _line_subtotal_tax_ `string` - The line subtotal tax.
- _line_total_ `string` - The line total.
- _line_total_tax_ `string` - The line total tax.
- _type_ `string` - The item type.
- _variation_ `array` - The item variation array.

View File

@ -0,0 +1,215 @@
---
post_title: Cart and Checkout Filters - Totals footer item
menu_title: Totals Footer Item
tags: reference
---
<!-- markdownlint-disable MD024 -->
The following Totals Footer Item filter are available:
- `totalLabel`
- `totalValue`
## `totalLabel`
The following object is used in the filter:
- [Cart object](#cart-object)
### Description <!-- omit in toc -->
The `totalLabel` filter allows to change the label of the total item in the footer of the Cart and Checkout blocks.
### Parameters <!-- omit in toc -->
- _defaultValue_ `string` (default: `Total`) - The total label.
- _extensions_ `object` (default: `{}`) - The extensions object.
- _args_ `object` - The arguments object with the following keys:
- _cart_ `object` - The cart object from `wc/store/cart`, see [Cart object](#cart-object).
### Returns <!-- omit in toc -->
- `string` - The updated total label.
### Code example <!-- omit in toc -->
```ts
const { registerCheckoutFilters } = window.wc.blocksCheckout;
const modifyTotalLabel = ( defaultValue, extensions, args ) => {
return 'Deposit due today';
};
registerCheckoutFilters( 'example-extension', {
totalLabel: modifyTotalLabel,
} );
```
> Filters can be also combined. See [Combined filters](./category/cart-and-checkout-blocks/available-filters/) for an example.
### Screenshots <!-- omit in toc -->
| Before | After |
|:---------------------------------------------------------------------:|:---------------------------------------------------------------------:|
|![Before applying the Total Label filter](https://github.com/woocommerce/woocommerce-blocks/assets/3323310/5b2fb8ab-db84-4ed0-a676-d5203edc84d2) |![After applying the Total Label filter](https://github.com/woocommerce/woocommerce-blocks/assets/3323310/07955eea-cb17-48e9-9cb5-6548dd6a3b24) |
## `totalValue`
The following object is used in the filter:
- [Cart object](#cart-object)
### Description <!-- omit in toc -->
The `totalValue` filter allows to format the total price in the footer of the Cart and Checkout blocks.
### Parameters <!-- omit in toc -->
- _defaultValue_ `string` (default: `Total`) - The total label.
- _extensions_ `object` (default: `{}`) - The extensions object.
- _args_ `object` - The arguments object with the following keys:
- _cart_ `object` - The cart object from `wc/store/cart`, see [Cart object](#cart-object).
- _validation_ `boolean` - Checks if the return value contains the substring `<price/>`.
### Returns <!-- omit in toc -->
- `string` - The modified format of the total price, which must contain the substring `<price/>`, or the original price format.
### Code example <!-- omit in toc -->
```ts
const { registerCheckoutFilters } = window.wc.blocksCheckout;
const modifyTotalsPrice = ( defaultValue, extensions, args, validation ) => {
return 'Pay <price/> now';
};
registerCheckoutFilters( 'my-extension', {
totalValue: modifyTotalsPrice,
} );
```
> Filters can be also combined. See [Combined filters](./category/cart-and-checkout-blocks/available-filters/) for an example.
### Screenshots <!-- omit in toc -->
| Before | After |
|:---------------------------------------------------------------------:|:---------------------------------------------------------------------:|
|![Before applying the Total Value filter](https://github.com/woocommerce/woocommerce/assets/3323310/4b788bdd-6fbd-406c-a9ad-4fb13f901c23) |![After applying the Total Value filter](https://github.com/woocommerce/woocommerce/assets/3323310/1b1b5f72-7f2f-4ee5-b2a4-1d8eb2208deb) |
## Cart object
The Cart object of the filters above has the following keys:
- _billingAddress_ `object` - The billing address object with the following keys:
- _address_1_ `string` - The first line of the address.
- _address_2_ `string` - The second line of the address.
- _city_ `string` - The city of the address.
- _company_ `string` - The company of the address.
- _country_ `string` - The country of the address.
- _email_ `string` - The email of the address.
- _first_name_ `string` - The first name of the address.
- _last_name_ `string` - The last name of the address.
- _phone_ `string` - The phone of the address.
- _postcode_ `string` - The postcode of the address.
- _state_ `string` - The state of the address.
- ~~_billingData_~~ `object` - The billing data object with the same keys as the `billingAddress` object.
- _cartCoupons_ `array` - The cart coupons array.
- _cartErrors_ `array` - The cart errors array.
- _cartFees_ `array` - The cart fees array.
- _cartHasCalculatedShipping_ `boolean` - Whether the cart has calculated shipping.
- _cartIsLoading_ `boolean` - Whether the cart is loading.
- _cartItemErrors_ `array` - The cart item errors array.
- _cartItems_ `array` - The cart items array with cart item objects, see [Cart Item object](#cart-item-object).
- _cartItemsCount_ `number` - The cart items count.
- _cartItemsWeight_ `number` - The cart items weight.
- _cartNeedsPayment_ `boolean` - Whether the cart needs payment.
- _cartNeedsShipping_ `boolean` - Whether the cart needs shipping.
- _cartTotals_ `object` - The cart totals object with the following keys:
- _currency_code_ `string` - The currency code.
- _currency_decimal_separator_ `string` - The currency decimal separator.
- _currency_minor_unit_ `number` - The currency minor unit.
- _currency_prefix_ `string` - The currency prefix.
- _currency_suffix_ `string` - The currency suffix.
- _currency_symbol_ `string` - The currency symbol.
- _currency_thousand_separator_ `string` - The currency thousand separator.
- _tax_lines_ `array` - The tax lines array with tax line objects with the following keys:
- _name_ `string` - The name of the tax line.
- _price_ `number` - The price of the tax line.
- _rate_ `string` - The rate ID of the tax line.
- _total_discount_ `string` - The total discount.
- _total_discount_tax_ `string` - The total discount tax.
- _total_fees_ `string` - The total fees.
- _total_fees_tax_ `string` - The total fees tax.
- _total_items_ `string` - The total items.
- _total_items_tax_ `string` - The total items tax.
- _total_price_ `string` - The total price.
- _total_shipping_ `string` - The total shipping.
- _total_shipping_tax_ `string` - The total shipping tax.
- _total_tax_ `string` - The total tax.
- _crossSellsProducts_ `array` - The cross sells products array with cross sells product objects.
- _extensions_ `object` (default: `{}`) - The extensions object.
- _isLoadingRates_ `boolean` - Whether the cart is loading rates.
- _paymentRequirements_ `array` - The payment requirements array.
- _shippingAddress_ `object` - The shipping address object with the same keys as the `billingAddress` object.
- _shippingRates_ `array` - The shipping rates array.
## Cart Item object
The Cart Item object of the filters above has the following keys:
- _backorders_allowed_ `boolean` - Whether backorders are allowed.
- _catalog_visibility_ `string` - The catalog visibility.
- _decsription_ `string` - The cart item description.
- _extensions_ `object` (default: `{}`) - The extensions object.
- _id_ `number` - The item ID.
- _images_ `array` - The item images array.
- _item_data_ `array` - The item data array.
- _key_ `string` - The item key.
- _low_stock_remaining_ `number` - The low stock remaining.
- _name_ `string` - The item name.
- _permalink_ `string` - The item permalink.
- _prices_ `object` - The item prices object with the following keys:
- _currency_code_ `string` - The currency code.
- _currency_decimal_separator_ `string` - The currency decimal separator.
- _currency_minor_unit_ `number` - The currency minor unit.
- _currency_prefix_ `string` - The currency prefix.
- _currency_suffix_ `string` - The currency suffix.
- _currency_symbol_ `string` - The currency symbol.
- _currency_thousand_separator_ `string` - The currency thousand separator.
- _price_ `string` - The price.
- _price_range_ `string` - The price range.
- _raw_prices_ `object` - The raw prices object with the following keys:
- _precision_ `number` - The precision.
- _price_ `number` - The price.
- _regular_price_ `number` - The regular price.
- _sale_price_ `number` - The sale price.
- _regular_price_ `string` - The regular price.
- _sale_price_ `string` - The sale price.
- _quantity_ `number` - The item quantity.
- _quantity_limits_ `object` - The item quantity limits object with the following keys:
- _editable_ `boolean` - Whether the quantity is editable.
- _maximum_ `number` - The maximum quantity.
- _minimum_ `number` - The minimum quantity.
- _multiple_of_ `number` - The multiple of quantity.
- _short_description_ `string` - The item short description.
- _show_backorder_badge_ `boolean` - Whether to show the backorder badge.
- _sku_ `string` - The item SKU.
- _sold_individually_ `boolean` - Whether the item is sold individually.
- _totals_ `object` - The item totals object with the following keys:
- _currency_code_ `string` - The currency code.
- _currency_decimal_separator_ `string` - The currency decimal separator.
- _currency_minor_unit_ `number` - The currency minor unit.
- _currency_prefix_ `string` - The currency prefix.
- _currency_suffix_ `string` - The currency suffix.
- _currency_symbol_ `string` - The currency symbol.
- _currency_thousand_separator_ `string` - The currency thousand separator.
- _line_subtotal_ `string` - The line subtotal.
- _line_subtotal_tax_ `string` - The line subtotal tax.
- _line_total_ `string` - The line total.
- _line_total_tax_ `string` - The line total tax.
- _type_ `string` - The item type.
- _variation_ `array` - The item variation array.

View File

@ -0,0 +1,172 @@
---
post_title: Cart and Checkout - Available slots
menu_title: Available Slots
tags: reference
---
<!-- markdownlint-disable MD024 -->
This document presents the list of available Slots that you can use for adding your custom content (Fill).
If you want to add a new SlotFill component, check the [Checkout - Slot Fill document](https://github.com/woocommerce/woocommerce/blob/1675c63bba94c59703f57c7ef06e7deff8fd6bba/plugins/woocommerce-blocks/packages/checkout/slot/README.md). To read more about Slot and Fill, check the [Slot and Fill document](./cart-and-checkout-slot-and-fill/).
**Note About Naming:** Slots that are prefixed with `Experimental` are experimental and subject to change or remove. Once they graduate from the experimental stage, the naming would change and the `Experimental` prefix would be dropped. Check the [Feature Gating document](https://github.com/woocommerce/woocommerce/blob/1675c63bba94c59703f57c7ef06e7deff8fd6bba/plugins/woocommerce-blocks/docs/internal-developers/blocks/feature-flags-and-experimental-interfaces.md) from more information.
## ExperimentalOrderMeta
This Slot renders below the Checkout summary section and above the "Proceed to Checkout" button in the Cart.
```ts
const { __ } = window.wp.i18n;
const { registerPlugin } = window.wp.plugins;
const { ExperimentalOrderMeta } = window.wc.blocksCheckout;
const render = () => {
return (
<ExperimentalOrderMeta>
<div class="wc-block-components-totals-wrapper">
{ __( 'Yearly recurring total ...', 'YOUR-TEXTDOMAIN' ) }
</div>
</ExperimentalOrderMeta>
);
};
registerPlugin( 'slot-and-fill-examples', {
render,
scope: 'woocommerce-checkout',
} );
```
Cart:
![Example of ExperimentalOrderMeta in the Cart block](https://user-images.githubusercontent.com/1628454/154517779-117bb4e4-568e-413c-904c-855fc3450dfa.png)
Checkout:
![Example of ExperimentalOrderMeta in the Checkout block](https://user-images.githubusercontent.com/1628454/154697224-de245182-6783-4914-81ba-1dbcf77292eb.png)
### Passed parameters
- `cart`: `wc/store/cart` data but in `camelCase` instead of `snake_case`. [Object breakdown.](https://github.com/woocommerce/woocommerce-gutenberg-products-block/blob/c00da597efe4c16fcf5481c213d8052ec5df3766/assets/js/type-defs/cart.ts#L172-L188)
- `extensions`: external data registered by third-party developers using `ExtendSchema`. If you used `ExtendSchema` on `wc/store/cart` you would find your data under your namespace here.
- `context`, equal to the name of the Block in which the fill is rendered: `woocommerce/cart` or `woocommerce/checkout`
## ExperimentalOrderShippingPackages
This slot renders inside the shipping step of Checkout and inside the shipping options in Cart.
```ts
const { __ } = window.wp.i18n;
const { registerPlugin } = window.wp.plugins;
const { ExperimentalOrderShippingPackages } = window.wc.blocksCheckout;
const render = () => {
return (
<ExperimentalOrderShippingPackages>
<div>{ __( 'Express Shipping', 'YOUR-TEXTDOMAIN' ) }</div>
</ExperimentalOrderShippingPackages>
);
};
registerPlugin( 'slot-and-fill-examples', {
render,
scope: 'woocommerce-checkout',
} );
```
Cart:
![Example of ExperimentalOrderShippingPackages in the Cart block](https://user-images.githubusercontent.com/6165348/118399054-2b4dec80-b653-11eb-94a0-989e2e6e362a.png)
Checkout:
![Example of ExperimentalOrderShippingPackages in the Checkout block](https://user-images.githubusercontent.com/6165348/118399133-90094700-b653-11eb-8ff0-c917947c199f.png)
### Passed parameters
- `collapsible`: `Boolean|undefined` If a shipping package panel should be collapsible or not, this is false in Checkout and undefined in Cart.
- `collapse`: `Boolean` If a panel should be collapsed by default, this is true if if panels are collapsible.
- `showItems`: `Boolean|undefined` If we should show the content of each package, this is undefined in Cart and Checkout and is left to the actual package logic to decide.
- `noResultsMessage`: A React element that you can render if there are no shipping options.
- `renderOption`: a render function that takes a rate object and returns a render option.
- `cart`: `wc/store/cart` data but in `camelCase` instead of `snake_case`. [Object breakdown.](https://github.com/woocommerce/woocommerce-gutenberg-products-block/blob/c00da597efe4c16fcf5481c213d8052ec5df3766/assets/js/type-defs/cart.ts#L172-L188)
- `extensions`: external data registered by third-party developers using `ExtendSchema`, if you used `ExtendSchema` on `wc/store/cart` you would find your data under your namespace here.
- `components`: an object containing components you can use to render your own shipping rates, it contains `ShippingRatesControlPackage`.
- `context`, equal to the name of the Block in which the fill is rendered: `woocommerce/cart` or `woocommerce/checkout`
## ExperimentalOrderLocalPickupPackages
This slot renders inside the Checkout Pickup Options block in the Checkout block. It does not render in the Cart block.
```ts
const { __ } = window.wp.i18n;
const { registerPlugin } = window.wp.plugins;
const { ExperimentalOrderLocalPickupPackages } = window.wc.blocksCheckout;
const render = () => {
return (
<ExperimentalOrderLocalPickupPackages>
<div>
{ __(
'By using our convenient local pickup option, you can come to our store and pick up your order. We will send you and email when your order is ready for pickup.',
'YOUR-TEXTDOMAIN'
) }
</div>
</ExperimentalOrderLocalPickupPackages>
);
};
registerPlugin( 'slot-and-fill-examples', {
render,
scope: 'woocommerce-checkout',
} );
```
Checkout:
![Example of ExperimentalOrderLocalPickupPackages in the Checkout block](https://user-images.githubusercontent.com/5656702/222814945-a449d016-0621-4a70-b0f4-2ae1ce6487f1.png)
### Passed parameters
- `renderPickupLocation`: a render function that renders the address details of a local pickup option.
- `cart`: `wc/store/cart` data but in `camelCase` instead of `snake_case`. [Object breakdown.](https://github.com/woocommerce/woocommerce-gutenberg-products-block/blob/c00da597efe4c16fcf5481c213d8052ec5df3766/assets/js/type-defs/cart.ts#L172-L188)
- `extensions`: external data registered by third-party developers using `ExtendSchema`, if you used `ExtendSchema` on `wc/store/cart` you would find your data under your namespace here.
- `components`: an object containing components you can use to render your own pickup rates, it contains `ShippingRatesControlPackage` and `RadioControl`.
## ExperimentalDiscountsMeta
This slot renders below the `CouponCode` input.
```ts
const { __ } = window.wp.i18n;
const { registerPlugin } = window.wp.plugins;
const { ExperimentalDiscountsMeta } = window.wc.blocksCheckout;
const render = () => {
return (
<ExperimentalDiscountsMeta>
<div class="wc-block-components-totals-wrapper">
{ __( 'You have 98683 coins to spend ...', 'YOUR-TEXTDOMAIN' ) }
</div>
</ExperimentalDiscountsMeta>
);
};
registerPlugin( 'slot-and-fill-examples', {
render,
scope: 'woocommerce-checkout',
} );
```
Cart:
![Cart showing ExperimentalDiscountsMeta location](https://user-images.githubusercontent.com/5656702/122774218-ea27a880-d2a0-11eb-9450-11f119567f26.png)
Checkout:
![Checkout showing ExperimentalDiscountsMeta location](https://user-images.githubusercontent.com/5656702/122779606-efd3bd00-d2a5-11eb-8c84-6525eca5d704.png)
### Passed parameters
- `cart`: `wc/store/cart` data but in `camelCase` instead of `snake_case`. [Object breakdown.](https://github.com/woocommerce/woocommerce-gutenberg-products-block/blob/c00da597efe4c16fcf5481c213d8052ec5df3766/assets/js/type-defs/cart.ts#L172-L188)
- `extensions`: external data registered by third-party developers using `ExtendSchema`, if you used `ExtendSchema` on `wc/store/cart` you would find your data under your namespace here.
- `context`, equal to the name of the Block in which the fill is rendered: `woocommerce/cart` or `woocommerce/checkout`

View File

@ -0,0 +1,8 @@
---
category_title: Payment Methods
category_slug: checkout-payment-methods
post_title: Checkout payment methods
---

View File

@ -0,0 +1,469 @@
---
post_title: Cart and Checkout - Checkout flow and events
menu_title: Checkout Flow and Events
tags: reference
---
This document gives an overview of the flow for the checkout in the WooCommerce checkout block, and some general architectural overviews.
The architecture of the Checkout Block is derived from the following principles:
- A single source of truth for data within the checkout flow.
- Provide a consistent interface for extension integrations (eg Payment methods). This interface protects the integrity of the checkout process and isolates extension logic from checkout logic. The checkout block handles _all_ communication with the server for processing the order. Extensions are able to react to and communicate with the checkout block via the provided interface.
- Checkout flow state is tracked by checkout status.
- Extensions are able to interact with the checkout flow via subscribing to emitted events.
Here's a high level overview of the flow:
![checkout flow diagram](https://user-images.githubusercontent.com/1628454/113739726-f8c9df00-96f7-11eb-80f1-78e25ccc88cb.png)
## General Concepts
### Tracking flow through status
At any point in the checkout lifecycle, components should be able to accurately detect the state of the checkout flow. This includes things like:
- Is something loading? What is loading?
- Is there an error? What is the error?
- is the checkout calculating totals?
Using simple booleans can be fine in some cases, but in others it can lead to complicated conditionals and bug prone code (especially for logic behaviour that reacts to various flow state).
To surface the flow state, the block uses statuses that are tracked in the various contexts. _As much as possible_ these statuses are set internally in reaction to various actions so there's no implementation needed in children components (components just have to _consume_ the status not set status).
The following statuses exist in the Checkout.
#### Checkout Data Store Status
There are various statuses that are exposed on the Checkout data store via selectors. All the selectors are detailed below and in the [Checkout API docs](https://github.com/woocommerce/woocommerce-blocks/blob/trunk/docs/internal-developers/block-client-apis/checkout/checkout-api.md).
You can use them in your component like so
```jsx
const { useSelect } = window.wp.data;
const { CHECKOUT_STORE_KEY } = window.wc.wcBlocksData;
const MyComponent = ( props ) => {
const isComplete = useSelect( ( select ) =>
select( CHECKOUT_STORE_KEY ).isComplete()
);
// do something with isComplete
};
```
The following boolean flags available related to status are:
**isIdle**: When the checkout status is `IDLE` this flag is true. Checkout will be this status after any change to checkout state after the block is loaded. It will also be this status when retrying a purchase is possible after processing happens with an error.
**isBeforeProcessing**: When the checkout status is `BEFORE_PROCESSING` this flag is true. Checkout will be this status when the user submits checkout for processing.
**isProcessing**: When the checkout status is `PROCESSING` this flag is true. Checkout will be this status when all the observers on the event emitted with the `BEFORE_PROCESSING` status are completed without error. It is during this status that the block will be sending a request to the server on the checkout endpoint for processing the order. **Note:** there are some checkout payment status changes that happen during this state as well (outlined in the `PaymentProvider` exposed statuses section).
**isAfterProcessing**: When the checkout status is `AFTER_PROCESSING` this flag is true. Checkout will have this status after the block receives the response from the server side processing request.
**isComplete**: When the checkout status is `COMPLETE` this flag is true. Checkout will have this status after all observers on the events emitted during the `AFTER_PROCESSING` status are completed successfully. When checkout is at this status, the shopper's browser will be redirected to the value of `redirectUrl` at that point (usually the `order-received` route).
#### Special States
The following are booleans exposed via the checkout provider that are independent from each other and checkout statuses but can be used in combination to react to various state in the checkout.
**isCalculating:** This is true when the total is being re-calculated for the order. There are numerous things that might trigger a recalculation of the total: coupons being added or removed, shipping rates updated, shipping rate selected etc. This flag consolidates all activity that might be occurring (including requests to the server that potentially affect calculation of totals). So instead of having to check each of those individual states you can reliably just check if this boolean is true (calculating) or false (not calculating).
**hasError:** This is true when anything in the checkout has created an error condition state. This might be validation errors, request errors, coupon application errors, payment processing errors etc.
### `ShippingProvider` Exposed Statuses
The shipping context provider exposes everything related to shipping in the checkout. Included in this are a set of error statuses that inform what error state the shipping context is in and the error state is affected by requests to the server on address changes, rate retrieval and selection.
Currently the error status may be one of `NONE`, `INVALID_ADDRESS` or `UNKNOWN` (note, this may change in the future).
The status is exposed on the `currentErrorStatus` object provided by the `useShippingDataContext` hook. This object has the following properties on it:
- `isPristine` and `isValid`: Both of these booleans are connected to the same error status. When the status is `NONE` the values for these booleans will be `true`. It basically means there is no shipping error.
- `hasInvalidAddress`: When the address provided for shipping is invalid, this will be true.
- `hasError`: This is `true` when the error status for shipping is either `UNKNOWN` or `hasInvalidAddress`.
### Payment Method Data Store Status
The status of the payment lives in the payment data store. You can query the status with the following selectors:
```jsx
const { select } = window.wp.data;
const { PAYMENT_STORE_KEY } = window.wc.wcBlocksData;
const MyComponent = ( props ) => {
const isPaymentIdle = select( PAYMENT_STORE_KEY ).isPaymentIdle();
const isExpressPaymentStarted =
select( PAYMENT_STORE_KEY ).isExpressPaymentStarted();
const isPaymentProcessing =
select( PAYMENT_STORE_KEY ).isPaymentProcessing();
const isPaymentReady = select( PAYMENT_STORE_KEY ).isPaymentReady();
const hasPaymentError = select( PAYMENT_STORE_KEY ).hasPaymentError();
// do something with the boolean values
};
```
The status here will help inform the current state of _client side_ processing for the payment and are updated via the store actions at different points throughout the checkout processing cycle. _Client side_ means the state of processing any payments by registered and active payment methods when the checkout form is submitted via those payment methods registered client side components. It's still possible that payment methods might have additional server side processing when the order is being processed but that is not reflected by these statuses (more in the [payment method integration doc](./payment-method-integration.md)).
The possible _internal_ statuses that may be set are:
- `IDLE`: This is the status when checkout is initialized and there are payment methods that are not doing anything. This status is also set whenever the checkout status is changed to `IDLE`.
- `EXPRESS_STARTED`: **Express Payment Methods Only** - This status is used when an express payment method has been triggered by the user clicking it's button. This flow happens before processing, usually in a modal window.
- `PROCESSING`: This status is set when the checkout status is `PROCESSING`, checkout `hasError` is false, checkout is not calculating, and the current payment status is not `FINISHED`. When this status is set, it will trigger the payment processing event emitter.
- `READY`: This status is set after all the observers hooked into the payment processing event have completed successfully. The `CheckoutProcessor` component uses this along with the checkout `PROCESSING` status to signal things are ready to send the order to the server with data for processing and to take payment
- `ERROR`: This status is set after an observer hooked into the payment processing event returns an error response. This in turn will end up causing the checkout `hasError` flag to be set to true.
### Emitting Events
Another tricky thing for extensibility, is providing opinionated, yet flexible interfaces for extensions to act and react to specific events in the flow. For stability, it's important that the core checkout flow _controls_ all communication to and from the server specific to checkout/order processing and leave extension specific requirements for the extension to handle. This allows for extensions to predictably interact with the checkout data and flow as needed without impacting other extensions hooking into it.
One of the most reliable ways to implement this type of extensibility is via the usage of an events system. Thus the various context providers:
- expose subscriber APIs for extensions to subscribe _observers_ to the events they want to react to.
- emit events at specific points of the checkout flow that in turn will feed data to the registered observers and, in some cases, react accordingly to the responses from observers.
One _**very important rule**_ when it comes to observers registered to any event emitter in this system is that they _cannot_ update context state. Updating state local to a specific component is okay but not any context or global state. The reason for this is that the observer callbacks are run sequentially at a specific point and thus subsequent observers registered to the same event will not react to any change in global/context state in earlier executed observers.
```jsx
const unsubscribe = emitter( myCallback );
```
You could substitute in whatever emitter you are registering for the `emitter` function. So for example if you are registering for the `onCheckoutValidation` event emitter, you'd have something like:
```jsx
const unsubscribe = onCheckoutValidation( myCallback );
```
You can also indicate what priority you want your observer to execute at. Lower priority is run before higher priority, so you can affect when your observer will run in the stack of observers registered to an emitter. You indicate priority via an number on the second argument:
```jsx
const unsubscribe = onCheckoutValidation( myCallback, 10 );
```
In the examples, `myCallback`, is your subscriber function. The subscriber function could receive data from the event emitter (described in the emitter details below) and may be expected to return a response in a specific shape (also described in the specific emitter details). The subscriber function can be a `Promise` and when the event emitter cycles through the registered observers it will await for any registered Promise to resolve.
Finally, the return value of the call to the emitter function is an unsubscribe function that can be used to unregister your observer. This is especially useful in a React component context where you need to make sure you unsubscribe the observer on component unmount. An example is usage in a `useEffect` hook:
```jsx
const MyComponent = ( { onCheckoutValidation } ) => {
useEffect( () => {
const unsubscribe = onCheckoutValidation( () => true );
return unsubscribe;
}, [ onCheckoutValidation ] );
return null;
};
```
**`Event Emitter Utilities`**
There are a bunch of utility methods that can be used related to events. These are available in `assets/js/base/context/event-emit/utils.ts` and can be imported as follows:
```jsx
import {
isSuccessResponse,
isErrorResponse,
isFailResponse,
noticeContexts,
responseTypes,
shouldRetry,
} from '@woocommerce/base-context';
};
```
The helper functions are described below:
- `isSuccessResponse`, `isErrorResponse` and `isFailResponse`: These are helper functions that receive a value and report via boolean whether the object is a type of response expected. For event emitters that receive responses from registered observers, a `type` property on the returned object from the observer indicates what type of response it is and event emitters will react according to that type. So for instance if an observer returned `{ type: 'success' }` the emitter could feed that to `isSuccessResponse` and it would return `true`. You can see an example of this being implemented for the payment processing emitted event [here](https://github.com/woocommerce/woocommerce-gutenberg-products-block/blob/34e17c3622637dbe8b02fac47b5c9b9ebf9e3596/assets/js/base/context/cart-checkout/payment-methods/payment-method-data-context.js#L281-L307).
- `noticeContexts`: This is an object containing properties referencing areas where notices can be targeted in the checkout. The object has the following properties:
- `PAYMENTS`: This is a reference to the notice area in the payment methods step.
- `EXPRESS_PAYMENTS`: This is a reference to the notice area in the express payment methods step.
- `responseTypes`: This is an object containing properties referencing the various response types that can be returned by observers for some event emitters. It makes it easier for autocompleting the types and avoiding typos due to human error. The types are `SUCCESS`, `FAIL`, `ERROR`. The values for these types also correspond to the [payment status types](https://github.com/woocommerce/woocommerce-gutenberg-products-block/blob/34e17c3622637dbe8b02fac47b5c9b9ebf9e3596/src/Payments/PaymentResult.php#L21) from the [checkout endpoint response from the server](https://github.com/woocommerce/woocommerce-gutenberg-products-block/blob/34e17c3622637dbe8b02fac47b5c9b9ebf9e3596/src/RestApi/StoreApi/Schemas/CheckoutSchema.php#L103-L113).
- `shouldRetry`: This is a function containing the logic whether the checkout flow should allow the user to retry the payment after a previous payment failed. It receives the `response` object and by default checks whether the `retry` property is true/undefined or false. Refer to the [`onCheckoutSuccess`](#oncheckoutsuccess) documentation for more details.
Note: `noticeContexts` and `responseTypes` are exposed to payment methods via the `emitResponse` prop given to their component:
```jsx
const MyPaymentMethodComponent = ( { emitResponse } ) => {
const { noticeContexts, responseTypes } = emitResponse;
// other logic for payment method...
};
```
The following event emitters are available to extensions to register observers to:
### `onCheckoutValidation`
Observers registered to this event emitter will receive nothing as an argument. Also, all observers will be executed before the checkout handles the responses from the emitters. Observers registered to this emitter can return `true` if they have nothing to communicate back to checkout, `false` if they want checkout to go back to `IDLE` status state, or an object with any of the following properties:
- `errorMessage`: This will be added as an error notice on the checkout context.
- `validationErrors`: This will be set as inline validation errors on checkout fields. If your observer wants to trigger validation errors it can use the following shape for the errors:
- This is an object where keys are the property names the validation error is for (that correspond to a checkout field, eg `country` or `coupon`) and values are the error message describing the validation problem.
This event is emitted when the checkout status is `BEFORE_PROCESSING` (which happens at validation time, after the checkout form submission is triggered by the user - or Express Payment methods).
If all observers return `true` for this event, then the checkout status will be changed to `PROCESSING`.
This event emitter subscriber can be obtained via the checkout context using the `useCheckoutContext` hook or to payment method extensions as a prop on their registered component:
_For internal development:_
```jsx
import { useCheckoutContext } from '@woocommerce/base-contexts';
import { useEffect } from '@wordpress/element';
const Component = () => {
const { onCheckoutValidation } = useCheckoutContext();
useEffect( () => {
const unsubscribe = onCheckoutValidation( () => true );
return unsubscribe;
}, [ onCheckoutValidation ] );
return null;
};
```
_For registered payment method components:_
```jsx
const { useEffect } = window.wp.element;
const PaymentMethodComponent = ( { eventRegistration } ) => {
const { onCheckoutValidation } = eventRegistration;
useEffect( () => {
const unsubscribe = onCheckoutValidation( () => true );
return unsubscribe;
}, [ onCheckoutValidation ] );
};
```
### ~~`onPaymentProcessing`~~
This is now deprecated and replaced by the `onPaymentSetup` event emitter.
### `onPaymentSetup`
This event emitter was fired when the payment method context status is `PROCESSING` and that status is set when the checkout status is `PROCESSING`, checkout `hasError` is false, checkout is not calculating, and the current payment status is not `FINISHED`.
This event emitter will execute through each registered observer (passing in nothing as an argument) _until_ an observer returns a non-truthy value at which point it will _abort_ further execution of registered observers.
When a payment method returns a non-truthy value, if it returns a valid response type the event emitter will update various internal statuses according to the response. Here's the possible response types that will get handled by the emitter:
#### Success
A successful response should be given when the user's entered data is correct and the payment checks are successful. A response is considered successful if, at a minimum, it is an object with this shape:
```js
const successResponse = { type: 'success' };
```
When a success response is returned, the payment method context status will be changed to `SUCCESS`. In addition, including any of the additional properties will result in extra actions:
- `paymentMethodData`: The contents of this object will be included as the value for `payment_data` when checkout sends a request to the checkout endpoint for processing the order. This is useful if a payment method does additional server side processing.
- `billingAddress`: This allows payment methods to update any billing data information in the checkout (typically used by Express payment methods) so it's included in the checkout processing request to the server. This data should be in the [shape outlined here](https://github.com/woocommerce/woocommerce/blob/trunk/plugins/woocommerce-blocks/assets/js/settings/shared/default-fields.ts).
- `shippingAddress`: This allows payment methods to update any shipping data information for the order (typically used by Express payment methods) so it's included in the checkout processing request to the server. This data should be in the [shape outlined here](https://github.com/woocommerce/woocommerce/blob/trunk/plugins/woocommerce-blocks/assets/js/settings/shared/default-fields.ts).
If `billingAddress` or `shippingAddress` properties aren't in the response object, then the state for the data is left alone.
#### Fail
A fail response should be given when there is an error with the payment processing. A response is considered a fail response when it is an object with this shape:
```js
const failResponse = { type: 'failure' };
```
When a fail response is returned by an observer, the payment method context status will be changed to `FAIL`. In addition, including any of the following properties will result in extra actions:
- `message`: The string provided here will be set as an error notice in the checkout.
- `messageContext`: If provided, this will target the given area for the error notice (this is where `noticeContexts` mentioned earlier come in to play). Otherwise the notice will be added to the `noticeContexts.PAYMENTS` area.
- `paymentMethodData`: (same as for success responses).
- `billingAddress`: (same as for success responses).
#### Error
An error response should be given when there is an error with the user input on the checkout form. A response is considered an error response when it is an object with this shape:
```js
const errorResponse = { type: 'error' };
```
When an error response is returned by an observer, the payment method context status will be changed to `ERROR`. In addition, including any of the following properties will result in extra actions:
- `message`: The string provided here will be set as an error notice.
- `messageContext`: If provided, this will target the given area for the error notice (this is where `noticeContexts` mentioned earlier come in to play). Otherwise, the notice will be added to the `noticeContexts.PAYMENTS` area.
- `validationErrors`: This will be set as inline validation errors on checkout fields. If your observer wants to trigger validation errors it can use the following shape for the errors:
- This is an object where keys are the property names the validation error is for (that correspond to a checkout field, eg `country` or `coupon`) and values are the error message describing the validation problem.
If the response object doesn't match any of the above conditions, then the fallback is to set the payment status as `SUCCESS`.
When the payment status is set to `SUCCESS` and the checkout status is `PROCESSING`, the `CheckoutProcessor` component will trigger the request to the server for processing the order.
This event emitter subscriber can be obtained via the checkout context using the `usePaymentEventsContext` hook or to payment method extensions as a prop on their registered component:
_For internal development:_
```jsx
import { usePaymentEventsContext } from '@woocommerce/base-contexts';
import { useEffect } from '@wordpress/element';
const Component = () => {
const { onPaymentSetup } = usePaymentEventsContext();
useEffect( () => {
const unsubscribe = onPaymentSetup( () => true );
return unsubscribe;
}, [ onPaymentSetup ] );
return null;
};
```
_For registered payment method components:_
```jsx
const { useEffect } = window.wp.element;
const PaymentMethodComponent = ( { eventRegistration } ) => {
const { onPaymentSetup } = eventRegistration;
useEffect( () => {
const unsubscribe = onPaymentSetup( () => true );
return unsubscribe;
}, [ onPaymentSetup ] );
};
```
### `onCheckoutSuccess`
This event emitter is fired when the checkout status is `AFTER_PROCESSING` and the checkout `hasError` state is false. The `AFTER_PROCESSING` status is set by the `CheckoutProcessor` component after receiving a response from the server for the checkout processing request.
Observers registered to this event emitter will receive the following object as an argument:
```js
const onCheckoutProcessingData = {
redirectUrl,
orderId,
customerId,
orderNotes,
paymentResult,
};
```
The properties are:
- `redirectUrl`: This is a string that is the url the checkout will redirect to as returned by the processing on the server.
- `orderId`: Is the id of the current order being processed.
- `customerId`: Is the id for the customer making the purchase (that is attached to the order).
- `orderNotes`: This will be any custom note the customer left on the order.
- `paymentResult`: This is the value of [`payment_result` from the /checkout StoreApi response](https://github.com/woocommerce/woocommerce-gutenberg-products-block/blob/34e17c3622637dbe8b02fac47b5c9b9ebf9e3596/src/RestApi/StoreApi/Schemas/CheckoutSchema.php#L103-L138). The data exposed on this object is (via the object properties):
- `paymentStatus`: Whatever the status is for the payment after it was processed server side. Will be one of `success`, `failure`, `pending`, `error`.
- `paymentDetails`: This will be an arbitrary object that contains any data the payment method processing server side sends back to the client in the checkout processing response. Payment methods are able to hook in on the processing server side and set this data for returning.
This event emitter will invoke each registered observer until a response from any of the registered observers does not equal `true`. At that point any remaining non-invoked observers will be skipped and the response from the observer triggering the abort will be processed.
This emitter will handle a `success` response type (`{ type: success }`) by setting the checkout status to `COMPLETE`. Along with that, if the response includes `redirectUrl` then the checkout will redirect to the given address.
This emitter will also handle a `failure` response type or an `error` response type and if no valid type is detected it will treat it as an `error` response type.
In all cases, if there are the following properties in the response, additional actions will happen:
- `message`: This string will be added as an error notice.
- `messageContext`: If present, the notice will be configured to show in the designated notice area (otherwise it will just be a general notice for the checkout block).
- `retry`: If this is `true` or not defined, then the checkout status will be set to `IDLE`. This basically means that the error is recoverable (for example try a different payment method) and so checkout will be reset to `IDLE` for another attempt by the shopper. If this is `false`, then the checkout status is set to `COMPLETE` and the checkout will redirect to whatever is currently set as the `redirectUrl`.
- `redirectUrl`: If this is present, then the checkout will redirect to this url when the status is `COMPLETE`.
If all observers return `true`, then the checkout status will just be set to `COMPLETE`.
This event emitter subscriber can be obtained via the checkout context using the `useCheckoutContext` hook or to payment method extensions as a prop on their registered component:
_For internal development:_
```jsx
import { useCheckoutContext } from '@woocommerce/base-contexts';
import { useEffect } from '@wordpress/element';
const Component = () => {
const { onCheckoutSuccess } = useCheckoutContext();
useEffect( () => {
const unsubscribe = onCheckoutSuccess( () => true );
return unsubscribe;
}, [ onCheckoutSuccess ] );
return null;
};
```
_For registered payment method components:_
```jsx
const { useEffect } = window.wp.element;
const PaymentMethodComponent = ( { eventRegistration } ) => {
const { onCheckoutSuccess } = eventRegistration;
useEffect( () => {
const unsubscribe = onCheckoutSuccess( () => true );
return unsubscribe;
}, [ onCheckoutSuccess ] );
};
```
### `onCheckoutFail`
This event emitter is fired when the checkout status is `AFTER_PROCESSING` and the checkout `hasError` state is `true`. The `AFTER_PROCESSING` status is set by the `CheckoutProcessor` component after receiving a response from the server for the checkout processing request.
Observers registered to this emitter will receive the same data package as those registered to `onCheckoutSuccess`.
The response from the first observer returning a value that does not `===` true will be handled similarly as the `onCheckoutSuccess` except it only handles when the type is `error` or `failure`.
If all observers return `true`, then the checkout status will just be set to `IDLE` and a default error notice will be shown in the checkout context.
This event emitter subscriber can be obtained via the checkout context using the `useCheckoutContext` hook or to payment method extensions as a prop on their registered component:
_For internal development:_
```jsx
import { useCheckoutContext } from '@woocommerce/base-contexts';
import { useEffect } from '@wordpress/element';
const Component = () => {
const { onCheckoutFail } = useCheckoutContext();
useEffect( () => {
const unsubscribe = onCheckoutFail( () => true );
return unsubscribe;
}, [ onCheckoutFail ] );
return null;
};
```
_For registered payment method components:_
```jsx
const { useEffect } = window.wp.element;
const PaymentMethodComponent = ( { eventRegistration } ) => {
const { onCheckoutFail } = eventRegistration;
useEffect( () => {
const unsubscribe = onCheckoutFail( () => true );
return unsubscribe;
}, [ onCheckoutFail ] );
};
```
### `onShippingRateSuccess`
This event emitter is fired when shipping rates are not loading and the shipping data context error state is `NONE` and there are shipping rates available.
This event emitter doesn't care about any registered observer response and will simply execute all registered observers passing them the current shipping rates retrieved from the server.
### `onShippingRateFail`
This event emitter is fired when shipping rates are not loading and the shipping data context error state is `UNKNOWN` or `INVALID_ADDRESS`.
This event emitter doesn't care about any registered observer response and will simply execute all registered observers passing them the current error status in the context.
### `onShippingRateSelectSuccess`
This event emitter is fired when a shipping rate selection is not being persisted to the server and there are selected rates available and the current error status in the context is `NONE`.
This event emitter doesn't care about any registered observer response and will simply execute all registered observers passing them the current selected rates.
### `onShippingRateSelectFail`
This event emitter is fired when a shipping rate selection is not being persisted to the server and the shipping data context error state is `UNKNOWN` or `INVALID_ADDRESS`.
This event emitter doesn't care about any registered observer response and will simply execute all registered observers passing them the current error status in the context.

View File

@ -0,0 +1,156 @@
---
post_title: Cart and Checkout - Filtering payment methods in the Checkout block
menu_title: Filtering Payment Methods
tags: how-to
---
<!-- markdownlint-disable MD024 -->
## The problem
You're an extension developer, and your extension is conditionally hiding payment gateways on the checkout step. You need to be able to hide payment gateways on the Checkout block using a front-end extensibility point.
### The solution
WooCommerce Blocks provides a function called `registerPaymentMethodExtensionCallbacks` which allows extensions to register callbacks for specific payment methods to determine if they can make payments.
### Importing
#### Aliased import
```js
import { registerPaymentMethodExtensionCallbacks } from '@woocommerce/blocks-registry';
```
#### `wc global`
```js
const { registerPaymentMethodExtensionCallbacks } = window.wc.wcBlocksRegistry;
```
### Signature
| Parameter | Description | Type |
| ----------- | ------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------- |
| `namespace` | Unique string to identify your extension. Choose something that eliminates a name collision with another extension. | `string` |
| `callbacks` | An object containing callbacks registered for different payment methods | Record< string, CanMakePaymentExtensionCallback > |
Read more below about [callbacks](#callbacks-registered-for-payment-methods).
#### Extension namespace collision
When trying to register callbacks under an extension namespace already used with `registerPaymentMethodExtensionCallbacks`, the registration will be aborted and you will be notified that you are not using a unique namespace. This will be shown in the JavaScript console.
### Usage example
```js
registerPaymentMethodExtensionCallbacks( 'my-hypothetical-extension', {
cod: ( arg ) => {
return arg.shippingAddress.city === 'Berlin';
},
cheque: ( arg ) => {
return false;
},
} );
```
### Callbacks registered for payment methods
Extensions can register only one callback per payment method:
```text
payment_method_name: ( arg ) => {...}
```
`payment_method_name` is the value of the [name](payment-method-integration.md#name-required) property used when the payment method was registered with WooCommerce Blocks.
The registered callbacks are used to determine whether the corresponding payment method should be available as an option for the shopper. The function will be passed an object containing data about the current order.
```ts
type CanMakePaymentExtensionCallback = (
cartData: CanMakePaymentArgument
) => boolean;
```
Each callback will have access to the information bellow
```ts
interface CanMakePaymentArgument {
cart: Cart;
cartTotals: CartTotals;
cartNeedsShipping: boolean;
billingAddress: CartResponseBillingAddress;
shippingAddress: CartResponseShippingAddress;
selectedShippingMethods: Record< string, unknown >;
paymentRequirements: Array< string >;
}
```
If you need data that is not available in the parameter received by the callback you can consider [exposing your data in the Store API](https://github.com/woocommerce/woocommerce/blob/1675c63bba94c59703f57c7ef06e7deff8fd6bba/plugins/woocommerce-blocks/docs/third-party-developers/extensibility/rest-api/extend-rest-api-add-data.md).
## Filtering payment methods using requirements
### The problem
Your extension has added functionality to your store in such a way that only specific payment gateways can process orders that contain certain products.
Using the example of `Bookings` if the shopper adds a `Bookable` product to their cart, for example a stay in a hotel, and you, the merchant, want to confirm all bookings before taking payment. You would still need to capture the customer's checkout details but not their payment method at that point.
### The solution
To allow the shopper to check out without entering payment details, but still require them to fill in the other checkout details it is possible to create a new payment method which will handle carts containing a `Bookable` item.
Using the `supports` configuration of payment methods it is possible to prevent other payment methods (such as credit card, PayPal etc.) from being used to check out, and only allow the one your extension has added to appear in the Checkout block.
For more information on how to register a payment method with WooCommerce Blocks, please refer to the [Payment method integration](./payment-method-integration.md) documentation.
### Basic usage
Following the documentation for registering payment methods linked above, you should register your payment method with a unique `supports` feature, for example `booking_availability`. This will be used to isolate it and prevent other methods from displaying.
First you will need to create a function that will perform the checks on the cart to determine what the specific payment requirements of the cart are. Below is an example of doing this for our `Bookable` products.
Then you will need to use the `register_payment_requirements` on the `ExtendSchema` class to tell the Checkout block to execute a callback to check for requirements.
### Putting it all together
This code example assumes there is some class called `Pseudo_Booking_Class` that has the `cart_contains_bookable_product` method available. The implementation of this method is not relevant here.
```php
/**
* Check the content of the cart and add required payment methods.
*
*
* @return array list of features required by cart items.
*/
function inject_payment_feature_requirements_for_cart_api() {
// Cart contains a bookable product, so return an array containing our requirement of booking_availability.
if ( Pseudo_Booking_Class::cart_contains_bookable_product() ) {
return array( 'booking_availability' );
}
// No bookable products in the cart, no need to add anything.
return array();
}
```
To summarise the above: if there's a bookable product in the cart then this function will return an array containing `booking_availability`, otherwise it will return an empty array.
The next step will tell the `ExtendSchema` class to execute this callback when checking which payment methods to display.
To do this you could use the following code:
```php
add_action('woocommerce_blocks_loaded', function() {
woocommerce_store_api_register_payment_requirements(
array(
'data_callback' => 'inject_payment_feature_requirements_for_cart_api',
)
);
});
```
It is important to note the comment in this code block, you must not instantiate your own version of `ExtendSchema`.
If you've added your payment method correctly with the correct `supports` values then when you reach the checkout page with a `Bookable` item in your cart, any method that does not `supports` the `booking_availability` requirement should not display, while yours, the one that _does_ support this requirement _will_ display.

View File

@ -0,0 +1,237 @@
---
post_title: Cart and Checkout - Payment method integration for the Checkout block
menu_title: Payment Method Integration
tags: reference
---
## Client Side integration
The client side integration consists of an API for registering both _express_ payment methods (those that consist of a one-button payment process initiated by the shopper such as Stripe, ApplePay, or GooglePay), and payment methods such as _cheque_, PayPal Standard, or Stripe Credit Card.
In both cases, the client side integration is done using registration methods exposed on the `blocks-registry` API. You can access this via the `wc` global in a WooCommerce environment (`wc.wcBlocksRegistry`).
> Note: In your build process, you could do something similar to what is done in the blocks repository which [aliases this API as an external on `@woocommerce/blocks-registry`](https://github.com/woocommerce/woocommerce-gutenberg-products-block/blob/e089ae17043fa525e8397d605f0f470959f2ae95/bin/webpack-helpers.js#L16-L35).
### Express payment methods - `registerExpressPaymentMethod( options )`
![Express Payment Area](https://user-images.githubusercontent.com/1429108/79565636-17fed500-807f-11ea-8e5d-9af32e43b71d.png)
To register an express payment method, you use the `registerExpressPaymentMethod` function from the blocks registry. An example of importing this for use in your JavaScript file is:
#### `registerExpressPaymentMethod` Aliased import
```js
import { registerExpressPaymentMethod } from '@woocommerce/blocks-registry';
```
#### `registerExpressPaymentMethod` on the `wc` global
```js
const { registerExpressPaymentMethod } = window.wc.wcBlocksRegistry;
```
#### The `registerExpressPaymentMethod` registration options
The registry function expects a JavaScript object with options specific to the payment method:
```js
registerExpressPaymentMethod( options );
```
The options you feed the configuration instance should be an object in this shape (see `ExpressPaymentMethodConfiguration` typedef):
```js
const options = {
name: 'my_payment_method',
content: <div>A React node</div>,
edit: <div>A React node</div>,
canMakePayment: () => true,
paymentMethodId: 'new_payment_method',
supports: {
features: [],
},
};
```
Here's some more details on the configuration options:
#### `name` (required)
This should be a unique string (wise to try to pick something unique for your gateway that wouldn't be used by another implementation) that is used as the identifier for the gateway client side. If `paymentMethodId` is not provided, `name` is used for `paymentMethodId` as well.
#### `content` (required)
This should be a React node that will output in the express payment method area when the block is rendered in the frontend. It will be cloned in the rendering process. When cloned, this React node will receive props passed in from the checkout payment method interface that will allow your component to interact with checkout data (more on [these props later](#props-fed-to-payment-method-nodes)).
#### `edit` (required)
This should be a React node that will be output in the express payment method area when the block is rendered in the editor. It will be cloned in the rendering process. When cloned, this React node will receive props from the payment method interface to checkout (but they will contain preview data).
#### `canMakePayment` (required)
A callback to determine whether the payment method should be available as an option for the shopper. The function will be passed an object containing data about the current order.
```ts
canMakePayment( {
cart: Cart,
cartTotals: CartTotals,
cartNeedsShipping: boolean,
shippingAddress: CartShippingAddress,
billingAddress: CartBillingAddress,
selectedShippingMethods: Record<string,unknown>,
paymentRequirements: string[],
} )
```
Returns a boolean value - true if payment method is available for use. If your gateway needs to perform async initialization to determine availability, you can return a promise (resolving to boolean). This allows a payment method to be hidden based on the cart, e.g. if the cart has physical/shippable products (example: [`Cash on delivery`](https://github.com/woocommerce/woocommerce-gutenberg-products-block/blob/e089ae17043fa525e8397d605f0f470959f2ae95/assets/js/payment-method-extensions/payment-methods/cod/index.js#L48-L70)); or for payment methods to control whether they are available depending on other conditions.
`canMakePayment` only runs on the frontend of the Store. In editor context, rather than use `canMakePayment`, the editor will assume the payment method is available (true) so that the defined `edit` component is shown to the merchant.
**Keep in mind this function could be invoked multiple times in the lifecycle of the checkout and thus any expensive logic in the callback provided on this property should be memoized.**
#### `paymentMethodId`
This is the only optional configuration object. The value of this property is what will accompany the checkout processing request to the server and is used to identify what payment method gateway class to load for processing the payment (if the shopper selected the gateway). So for instance if this is `stripe`, then `WC_Gateway_Stripe::process_payment` will be invoked for processing the payment.
#### `supports:features`
This is an array of payment features supported by the gateway. It is used to crosscheck if the payment method can be used for the content of the cart. By default payment methods should support at least `products` feature. If no value is provided then this assumes that `['products']` are supported.
---
### Payment Methods - `registerPaymentMethod( options )`
![Image 2021-02-24 at 4 24 05 PM](https://user-images.githubusercontent.com/1429108/109067640-c7073680-76bc-11eb-98e5-f04d35ddef99.jpg)
To register a payment method, you use the `registerPaymentMethod` function from the blocks registry. An example of importing this for use in your JavaScript file is:
#### `registerPaymentMethod` Aliased import
```js
import { registerPaymentMethod } from '@woocommerce/blocks-registry';
```
#### `registerPaymentMethod` on the `wc` global
```js
const { registerPaymentMethod } = window.wc.wcBlocksRegistry;
```
#### The `registerPaymentMethod` registration options
The registry function expects a JavaScript object with options specific to the payment method (see `PaymentMethodRegistrationOptions` typedef):
```js
registerPaymentMethod( options );
```
The options you feed the configuration instance are the same as those for express payment methods with the following additions:
- `savedTokenComponent`: This should be a React node that contains logic handling any processing your payment method has to do with saved payment methods if your payment method supports them. This component will be rendered whenever a customer's saved token using your payment method for processing is selected for making the purchase.
- `label`: This should be a React node that will be used to output the label for the option where the payment methods are. For example it might be `<strong>Credit/Debit Cart</strong>` or you might output images.
- `ariaLabel`: This is the label that will be read out via screen-readers when the payment method is selected.
- `placeOrderButtonLabel`: This is an optional label which will change the default "Place Order" button text to something else when the payment method is selected. As an example, the PayPal Standard payment method [changes the text of the button to "Proceed to PayPal"](https://github.com/woocommerce/woocommerce-gutenberg-products-block/blob/e089ae17043fa525e8397d605f0f470959f2ae95/assets/js/payment-method-extensions/payment-methods/paypal/index.js#L37-L40) when it is selected as the payment method for checkout because the payment method takes the shopper offsite to PayPal for completing the payment.
- `supports`: This is an object containing information about what features your payment method supports. The following keys are valid here:
- `showSavedCards`: This value will determine whether saved cards associated with your payment method are shown to the customer.
- `showSaveOption`: This value will control whether to show the checkbox which allows customers to save their payment method for future payments.
### Props Fed to Payment Method Nodes
A big part of the payment method integration is the interface that is exposed for payment methods to use via props when the node provided is cloned and rendered on block mount. While all the props are listed below, you can find more details about what the props reference, their types etc via the [typedefs described in this file](https://github.com/woocommerce/woocommerce/blob/trunk/plugins/woocommerce-blocks/assets/js/types/type-defs/payment-method-interface.ts).
| Property | Type | Description | Values |
| ------------------------ | -------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
| `activePaymentMethod` | String | The slug of the current active payment method in the checkout. | - |
| `billing` | Object | Contains everything related to billing. | `billingAddress`, `cartTotal`, `currency`, `cartTotalItems`, `displayPricesIncludingTax`, `appliedCoupons`, `customerId` |
| `cartData` | Object | Data exposed from the cart including items, fees, and any registered extension data. Note that this data should be treated as immutable (should not be modified/mutated) or it will result in errors in your application. | `cartItems`, `cartFees`, `extensions` |
| `checkoutStatus` | Object | The current checkout status exposed as various boolean state. | `isCalculating`, `isComplete`, `isIdle`, `isProcessing` |
| `components` | Object | It exposes React components that can be implemented by your payment method for various common interface elements used by payment methods. | <!-- markdownlint-disable-line no-inline-html --><ul><li>`ValidationInputError`: a container for holding validation errors which typically you'll include after any inputs.</li><li>[`PaymentMethodLabel`](https://github.com/woocommerce/woocommerce-gutenberg-products-block/blob/e089ae17043fa525e8397d605f0f470959f2ae95/assets/js/payment-method-extensions/payment-methods/paypal/index.js#L37-L40): use this component for the payment method label, including an optional icon.</li><li>`PaymentMethodIcons`: a React component used for displaying payment method icons.</li><li>- `LoadingMask`: a wrapper component that handles displaying a loading state when the isLoading prop is true. Exposes the [LoadingMask component](https://github.com/woocommerce/woocommerce-gutenberg-products-block/blob/c9074a4941919987dbad16a80f358b960336a09d/assets/js/base/components/loading-mask/index.js)</li></ul> |
| `emitResponse` | Object | Contains some constants that can be helpful when using the event emitter. Read the _[Emitting Events](https://github.com/woocommerce/woocommerce-gutenberg-products-block/blob/e267cd96a4329a4eeef816b2ef627e113ebb72a5/docs/extensibility/checkout-flow-and-events.md#emitting-events)_ section for more details. | <!-- markdownlint-disable-line no-inline-html --><ul><li>`noticeContexts`: This is an object containing properties referencing areas where notices can be targeted in the checkout. The object has the following properties: <ul><li>`PAYMENTS`: This is a reference to the notice area in the payment methods step.</li><li>`EXPRESS_PAYMENTS`: This is a reference to the notice area in the express payment methods step.</li></ul></li><li>`responseTypes`: This is an object containing properties referencing the various response types that can be returned by observers for some event emitters. It makes it easier for autocompleting the types and avoiding typos due to human error. The types are `SUCCESS`, `FAIL`, `ERROR`. The values for these types also correspond to the [payment status types](https://github.com/woocommerce/woocommerce-gutenberg-products-block/blob/34e17c3622637dbe8b02fac47b5c9b9ebf9e3596/src/Payments/PaymentResult.php#L21) from the [checkout endpoint response from the server](https://github.com/woocommerce/woocommerce-gutenberg-products-block/blob/34e17c3622637dbe8b02fac47b5c9b9ebf9e3596/src/RestApi/StoreApi/Schemas/CheckoutSchema.php#L103-L113).</li></ul> |
| `eventRegistration` | object | Contains all the checkout event emitter registration functions. These are functions the payment method can register observers on to interact with various points in the checkout flow (see [this doc](./checkout-flow-and-events.md) for more info). | `onCheckoutValidation`, `onCheckoutSuccess`, `onCheckoutFail`, `onPaymentSetup`, `onShippingRateSuccess`, `onShippingRateFail`, `onShippingRateSelectSuccess`, `onShippingRateSelectFail` |
| `onClick` | Function | **Provided to express payment methods** that should be triggered when the payment method button is clicked (which will signal to checkout the payment method has taken over payment processing) | - |
| `onClose` | Function | **Provided to express payment methods** that should be triggered when the express payment method modal closes and control is returned to checkout. | - |
| `onSubmit` | Function | Submits the checkout and begins processing | - |
| `paymentStatus` | Object | Various payment status helpers. Note, your payment method does not have to handle setting this status client side. Checkout will handle this via the responses your payment method gives from observers registered to [checkout event emitters](./checkout-flow-and-events.md). | `isPristine`, `isStarted`, `isProcessing`, `isFinished`, `hasError`, `hasFailed`, `isSuccessful` (see below for explanation) |
| `setExpressPaymentError` | Function | Receives a string and allows express payment methods to set an error notice for the express payment area on demand. This can be necessary because some express payment method processing might happen outside of checkout events. | - |
| `shippingData` | Object | Contains all shipping related data (outside of the shipping status). | `shippingRates`, `shippingRatesLoading`, `selectedRates`, `setSelectedRates`, `isSelectingRate`, `shippingAddress`, `setShippingAddress`, and `needsShipping` |
| `shippingStatus` | Object | Various shipping status helpers. | <!-- markdownlint-disable-line no-inline-html --><ul><li>`shippingErrorStatus`: an object with various error statuses that might exist for shipping</li><li>`shippingErrorTypes`: an object containing all the possible types for shipping error status</li></ul> |
| `shouldSavePayment` | Boolean | Indicates whether or not the shopper has selected to save their payment method details (for payment methods that support saved payments). True if selected, false otherwise. Defaults to false. | - |
- `isPristine`: This is true when the current payment status is `PRISTINE`.
- `isStarted`: This is true when the current payment status is `EXPRESS_STARTED`.
- `isProcessing`: This is true when the current payment status is `PROCESSING`.
- `isFinished`: This is true when the current payment status is one of `ERROR`, `FAILED`, or`SUCCESS`.
- `hasError`: This is true when the current payment status is `ERROR`.
- `hasFailed`: This is true when the current payment status is `FAILED`.
- `isSuccessful`: This is true when the current payment status is `SUCCESS`
Any registered `savedTokenComponent` node will also receive a `token` prop which includes the id for the selected saved token in case your payment method needs to use it for some internal logic. However, keep in mind, this is just the id representing this token in the database (and the value of the radio input the shopper checked), not the actual customer payment token (since processing using that usually happens on the server for security).
## Server Side Integration
### Processing Payment
The checkout block currently has legacy handling for payment processing. It converts incoming `payment_data` provided by the client-side payment method to `$_POST` and calls the payment gateway's `process_payment` function. If you already have a WooCommerce Payment method extension integrated with the existing shortcode checkout flow, the checkout block's legacy handling will take care of processing your payment for you on the server side. However, If your payment method hooks into the core checkout `process_checkout` function in any way, you will need to account for this behavior and make appropriate adjustments. (See the section below about hooking into the checkout process via the Store API.)
See an example of [Passing a value from the client through to server side payment processing](https://github.com/woocommerce/woocommerce-blocks/blob/62243e1731a0773f51b81fb8406ebc2e8b180b40/docs/internal-developers/block-client-apis/checkout/checkout-api.md#passing-a-value-from-the-client-through-to-server-side-payment-processing)
### Registering Assets
Implementing the correct loading of your client side asset registration is tricky for the blocks integration. This is because there are some dependencies on the _loading order_ of dependent assets in the request. To remove the complexity of this for extension consumers here, the server side API interface helps with ensuring you can register any assets and data to pass along to your client side payment method from the server and handles the correct loading order of those assets.
First, you create a class that extends `Automattic\WooCommerce\Blocks\Payments\Integrations\AbstractPaymentMethodType` (or you can implement the `Automattic\WooCommerce\Blocks\Payments\PaymentMethodTypeInterface`, but you get some functionality for free via the abstract class).
In your class:
- Define a `name` property (This property is a string used to reference your payment method. It is important to use the same name as in your client-side JavaScript payment method registration, see `name: 'my_payment_method'` in the options object above).
- Define an `initialize` function. This function will get called during the server side initialization process and is a good place to put any settings population etc. Basically anything you need to do to initialize your gateway. **Note, this will be called on every request so don't put anything expensive here.**
- Define an `is_active` function. This should return whether the payment method is active or not.
- Define a `get_payment_method_script_handles` function. In this function you should register your payment method scripts (using `wp_register_script`) and then return the script handles you registered with. This will be used to add your payment method as a dependency of the checkout script and thus take sure of loading it correctly. **Note:** You should still make sure any other asset dependencies your script has are registered properly here, if you're using Webpack to build your assets, you may want to use the [WooCommerce Webpack Dependency Extraction Plugin](https://www.npmjs.com/package/@woocommerce/dependency-extraction-webpack-plugin) to make this easier for you.
- Define a `get_payment_method_script_handles_for_admin` function. Include this if your payment method has a script you _only_ want to load in the editor context for the checkout block. Include here any script from `get_payment_method_script_handles` that is also needed in the admin.
- Define a `get_payment_method_data` function. You can return from this function an associative array of data you want to be exposed for your payment method client side. This data will be available client side via `wc.wcSettings.getSetting`. So for instance if you assigned `stripe` as the value of the `name` property for this class, client side you can access any data via: `wc.wcSettings.getSetting( 'stripe_data' )`. That would return an object matching the shape of the associative array you returned from this function.
### Hooking into the Checkout processing by the Store API
There may be some cases where the fallback legacy processing of Checkout requests from the StoreAPI mentioned earlier doesn't work for your existing payment method integration. For these cases, there is also an [action hook you can implement to hook into the server side processing of the order](https://github.com/woocommerce/woocommerce-gutenberg-products-block/blob/308e968c700028180cab391f2223eb0a43dd2d4d/src/RestApi/StoreApi/Routes/Checkout.php#L350-L361). **Note:** a good place to register your callback on this hook is in the `initialize` method of the payment method class you created from the above instructions.
This hook is the _preferred_ place to hook in your payment processing and if you set a status on the provided `PaymentResult` object, then the legacy processing will be ignored for your payment method. Hook callbacks will receive:
[`Automattic\WooCommerce\StoreApi\Payments\PaymentContext`](https://github.com/woocommerce/woocommerce-gutenberg-products-block/blob/trunk/src/StoreApi/Payments/PaymentContext.php)
This contains various details about the payment extracted from the checkout processing request. Notably is the `payment_data` property that will contain an associative array of data your payment method client side provided to checkout. It also contains a string value for `payment_method` which contains the `paymentMethodId` value for the active payment method used during checkout processing. So you can use this to determine whether your payment method processes this data or not.
[`Automattic\WooCommerce\StoreApi\Payments\PaymentResult`](https://github.com/woocommerce/woocommerce-gutenberg-products-block/blob/trunk/src/StoreApi/Payments/PaymentResult.php)
This contains various details about the payment result returned to the client and exposed on the `onAfterCheckoutProcessingWithSucces/WithError` event. Server side, your payment method can use this to:
- set the status to return for the payment method (one of `success`, `failure`, `pending`, `error`).
- set a redirect url.
- set any additional payment details (in case you need to return something for your client to further process with).
### Putting it all together
So you've created a class extending `Automattic\WooCommerce\Blocks\Payments\Integrations\AbstractPaymentMethodType`, but you still need to _register_ this with the server side handling of payment methods. In order to do this you need to register a callback on the `woocommerce_blocks_payment_method_type_registration` action. Your callback will receive an instance of `Automattic\WooCommerce\Blocks\Payments\PaymentMethodRegistry` which has a `register` method for registering an instance of the class you created. It's also recommended that you register your callback on this action within the context of a callback on the `woocommerce_blocks_loaded` action.
> Note: With Cart and Checkout Blocks currently only available in the WooCommerce Blocks Feature plugin, you will want to make sure you check for the availability of the `Automattic\WooCommerce\Blocks\Payments\Integrations\AbstractPaymentMethodType` class before registering your payment method integration server side.
So for example, assuming your class that extends `Automattic\WooCommerce\Blocks\Payments\Integrations\AbstractPaymentMethodType` is named `MyPaymentMethod`. You would have this somewhere in your extension's bootstrap:
```php
use MyPlugin\MyPaymentMethod;
use Automattic\WooCommerce\Blocks\Payments\PaymentMethodRegistry;
add_action( 'woocommerce_blocks_loaded', 'my_extension_woocommerce_blocks_support' );
function my_extension_woocommerce_blocks_support() {
if ( class_exists( 'Automattic\WooCommerce\Blocks\Payments\Integrations\AbstractPaymentMethodType' ) ) {
add_action(
'woocommerce_blocks_payment_method_type_registration',
function( PaymentMethodRegistry $payment_method_registry ) {
$payment_method_registry->register( new MyPaymentMethod );
}
);
}
}
```
As an example, you can see how the Stripe extension adds it's integration in this [pull request](https://github.com/woocommerce/woocommerce-gateway-stripe/pull/1467/files).

View File

@ -0,0 +1,37 @@
---
post_title: Cart and Checkout - DOM events
menu_title: DOM Events
tags: reference
---
Some blocks need to react to certain events in order to display the most up to date data or behave in a certain way. That's the case of the Cart block, for example, that must listen to 'add to cart' events in order to update the cart contents; or the Mini-Cart block, that gets opened every time a product is added to the cart.
## WooCommerce core events in WooCommerce Blocks
WooCommerce core uses jQuery events to trigger and listen to certain events, like when a product is added or removed from the cart. In WooCommerce Blocks, we moved away from using jQuery, but we still need to listen to those events. To achieve that, we have a utility named [`translatejQueryEventToNative()`](https://github.com/woocommerce/woocommerce-gutenberg-products-block/blob/3f7c3e517d7bf13008a22d0c2eb89434a9c35ae7/assets/js/base/utils/legacy-events.ts#L79-L106) that listens to those jQuery events, and every time one is triggered, it triggers an associated DOM native event (with the `wc-blocks_` prefix).
## WooCommerce Blocks events
### `wc-blocks_adding_to_cart`
This event is the equivalent to the jQuery event `adding_to_cart` triggered by WooCommerce core. It indicates that the process of adding a product to the cart was sent to the server, but there is still no indication on whether the product was successfully added or not.
_Example usage in WC Blocks:_ Mini-Cart block listens to this event to append its dependencies.
### `wc-blocks_added_to_cart`
This event is the equivalent to the jQuery event `added_to_cart` triggered by WooCommerce core. It indicates that the process of adding a product to the cart has finished with success.
_Example usage in WC Blocks:_ Cart and Mini-Cart blocks (via the `useStoreCart()` hook) listen to this event to know if they need to update their contents.
#### `detail` parameters
| Parameter | Type | Default value | Description |
| ------------------ | ------- | ------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `preserveCartData` | boolean | `false` | Whether Cart data in the store should be preserved. By default, it's `false` so any `wc-blocks_added_to_cart` event will invalidate cart data and blocks listening to it will refetch cart data again. However, if the code triggering the event already updates the store (ie: All Products block), it can set `preserveCartData: true` to avoid the other blocks refetching the data again. |
### `wc-blocks_removed_from_cart`
This event is the equivalent to the jQuery event `removed_from_cart` triggered by WooCommerce core. It indicates that a product has been removed from the cart.
_Example usage in WC Blocks:_ Cart and Mini-Cart blocks (via the `useStoreCart()` hook) listen to this event to know if they need to update their contents.

View File

@ -0,0 +1,8 @@
---
category_title: Hooks
category_slug: cart-and-checkout-hooks
post_title: Cart and Checkout - Hooks
---

View File

@ -0,0 +1,50 @@
---
post_title: Cart and Checkout - Legacy hooks
menu_title: Legacy Hooks
tags: reference
---
Below are the hooks that exist in WooCommerce core and that were brough over to WooCommerce Blocks.
Please note that the actions and filters here run on the server side. The client-side blocks won't necessarily change based on a callback added to a server side hook. [Please see our documentation relating to APIs for manipulating the blocks on the client-side](./an-introduction-to-extensiblity-in-woocommerce-blocks/).
## Legacy Filters
- [loop_shop_per_page](https://github.com/woocommerce/woocommerce/tree/trunk/plugins/woocommerce-blocks/docs/third-party-developers/extensibility/hooks/filters.md#loop_shop_per_page)
- [wc_session_expiration](https://github.com/woocommerce/woocommerce/tree/trunk/plugins/woocommerce-blocks/docs/third-party-developers/extensibility/hooks/filters.md#wc_session_expiration)
- [woocommerce_add_cart_item](https://github.com/woocommerce/woocommerce/tree/trunk/plugins/woocommerce-blocks/docs/third-party-developers/extensibility/hooks/filters.md#woocommerce_add_cart_item)
- [woocommerce_add_cart_item_data](https://github.com/woocommerce/woocommerce/tree/trunk/plugins/woocommerce-blocks/docs/third-party-developers/extensibility/hooks/filters.md#woocommerce_add_cart_item_data)
- [woocommerce_add_to_cart_quantity](https://github.com/woocommerce/woocommerce/tree/trunk/plugins/woocommerce-blocks/docs/third-party-developers/extensibility/hooks/filters.md#woocommerce_add_to_cart_quantity)
- [woocommerce_add_to_cart_sold_individually_quantity](https://github.com/woocommerce/woocommerce/tree/trunk/plugins/woocommerce-blocks/docs/third-party-developers/extensibility/hooks/filters.md#woocommerce_add_to_cart_sold_individually_quantity)
- [woocommerce_add_to_cart_validation](https://github.com/woocommerce/woocommerce/tree/trunk/plugins/woocommerce-blocks/docs/third-party-developers/extensibility/hooks/filters.md#woocommerce_add_to_cart_validation)
- [woocommerce_adjust_non_base_location_prices](https://github.com/woocommerce/woocommerce/tree/trunk/plugins/woocommerce-blocks/docs/third-party-developers/extensibility/hooks/filters.md#woocommerce_adjust_non_base_location_prices)
- [woocommerce_apply_base_tax_for_local_pickup](https://github.com/woocommerce/woocommerce/tree/trunk/plugins/woocommerce-blocks/docs/third-party-developers/extensibility/hooks/filters.md#woocommerce_apply_base_tax_for_local_pickup)
- [woocommerce_apply_individual_use_coupon](https://github.com/woocommerce/woocommerce/tree/trunk/plugins/woocommerce-blocks/docs/third-party-developers/extensibility/hooks/filters.md#woocommerce_apply_individual_use_coupon)
- [woocommerce_apply_with_individual_use_coupon](https://github.com/woocommerce/woocommerce/tree/trunk/plugins/woocommerce-blocks/docs/third-party-developers/extensibility/hooks/filters.md#woocommerce_apply_with_individual_use_coupon)
- [woocommerce_cart_contents_changed](https://github.com/woocommerce/woocommerce/tree/trunk/plugins/woocommerce-blocks/docs/third-party-developers/extensibility/hooks/filters.md#woocommerce_cart_contents_changed)
- [woocommerce_cart_item_permalink](https://github.com/woocommerce/woocommerce/tree/trunk/plugins/woocommerce-blocks/docs/third-party-developers/extensibility/hooks/filters.md#woocommerce_cart_item_permalink)
- [woocommerce_get_item_data](https://github.com/woocommerce/woocommerce/tree/trunk/plugins/woocommerce-blocks/docs/third-party-developers/extensibility/hooks/filters.md#woocommerce_get_item_data)
- [woocommerce_loop_add_to_cart_args](https://github.com/woocommerce/woocommerce/tree/trunk/plugins/woocommerce-blocks/docs/third-party-developers/extensibility/hooks/filters.md#woocommerce_loop_add_to_cart_args)
- [woocommerce_loop_add_to_cart_link](https://github.com/woocommerce/woocommerce/tree/trunk/plugins/woocommerce-blocks/docs/third-party-developers/extensibility/hooks/filters.md#woocommerce_loop_add_to_cart_link)
- [woocommerce_new_customer_data](https://github.com/woocommerce/woocommerce/tree/trunk/plugins/woocommerce-blocks/docs/third-party-developers/extensibility/hooks/filters.md#woocommerce_new_customer_data)
- [woocommerce_pay_order_product_has_enough_stock](https://github.com/woocommerce/woocommerce/tree/trunk/plugins/woocommerce-blocks/docs/third-party-developers/extensibility/hooks/filters.md#woocommerce_pay_order_product_has_enough_stock)
- [woocommerce_pay_order_product_in_stock](https://github.com/woocommerce/woocommerce/tree/trunk/plugins/woocommerce-blocks/docs/third-party-developers/extensibility/hooks/filters.md#woocommerce_pay_order_product_in_stock)
- [woocommerce_registration_errors](https://github.com/woocommerce/woocommerce/tree/trunk/plugins/woocommerce-blocks/docs/third-party-developers/extensibility/hooks/filters.md#woocommerce_registration_errors)
- [woocommerce_shipping_package_name](https://github.com/woocommerce/woocommerce/tree/trunk/plugins/woocommerce-blocks/docs/third-party-developers/extensibility/hooks/filters.md#woocommerce_shipping_package_name)
- [woocommerce_show_page_title](https://github.com/woocommerce/woocommerce/tree/trunk/plugins/woocommerce-blocks/docs/third-party-developers/extensibility/hooks/filters.md#woocommerce_show_page_title)
- [woocommerce_single_product_image_thumbnail_html](https://github.com/woocommerce/woocommerce/tree/trunk/plugins/woocommerce-blocks/docs/third-party-developers/extensibility/hooks/filters.md#woocommerce_single_product_image_thumbnail_html)
## Legacy Actions
- [woocommerce_add_to_cart](https://github.com/woocommerce/woocommerce/tree/trunk/plugins/woocommerce-blocks/docs/third-party-developers/extensibility/hooks/actions.md#woocommerce_add_to_cart)
- [woocommerce_after_main_content](https://github.com/woocommerce/woocommerce/tree/trunk/plugins/woocommerce-blocks/docs/third-party-developers/extensibility/hooks/actions.md#woocommerce_after_main_content)
- [woocommerce_after_shop_loop](https://github.com/woocommerce/woocommerce/tree/trunk/plugins/woocommerce-blocks/docs/third-party-developers/extensibility/hooks/actions.md#woocommerce_after_shop_loop)
- [woocommerce_applied_coupon](https://github.com/woocommerce/woocommerce/tree/trunk/plugins/woocommerce-blocks/docs/third-party-developers/extensibility/hooks/actions.md#woocommerce_applied_coupon)
- [woocommerce_archive_description](https://github.com/woocommerce/woocommerce/tree/trunk/plugins/woocommerce-blocks/docs/third-party-developers/extensibility/hooks/actions.md#woocommerce_archive_description)
- [woocommerce_before_main_content](https://github.com/woocommerce/woocommerce/tree/trunk/plugins/woocommerce-blocks/docs/third-party-developers/extensibility/hooks/actions.md#woocommerce_before_main_content)
- [woocommerce_before_shop_loop](https://github.com/woocommerce/woocommerce/tree/trunk/plugins/woocommerce-blocks/docs/third-party-developers/extensibility/hooks/actions.md#woocommerce_before_shop_loop)
- [woocommerce_check_cart_items](https://github.com/woocommerce/woocommerce/tree/trunk/plugins/woocommerce-blocks/docs/third-party-developers/extensibility/hooks/actions.md#woocommerce_check_cart_items)
- [woocommerce_created_customer](https://github.com/woocommerce/woocommerce/tree/trunk/plugins/woocommerce-blocks/docs/third-party-developers/extensibility/hooks/actions.md#woocommerce_created_customer)
- [woocommerce_no_products_found](https://github.com/woocommerce/woocommerce/tree/trunk/plugins/woocommerce-blocks/docs/third-party-developers/extensibility/hooks/actions.md#woocommerce_no_products_found)
- [woocommerce_register_post](https://github.com/woocommerce/woocommerce/tree/trunk/plugins/woocommerce-blocks/docs/third-party-developers/extensibility/hooks/actions.md#woocommerce_register_post)
- [woocommerce_shop_loop](https://github.com/woocommerce/woocommerce/tree/trunk/plugins/woocommerce-blocks/docs/third-party-developers/extensibility/hooks/actions.md#woocommerce_shop_loop)

View File

@ -0,0 +1,142 @@
---
post_title: Cart and Checkout - How the checkout block processes an order
menu_title: Processing an Order
tags: reference
---
This document will shed some light on the inner workings of the Checkout flow. More specifically, what happens after a user hits the "Place Order" button.
## Structure
The following areas are associated with processing the checkout for a user.
### The Payment Registry [(file)](https://href.li/?https://github.com/woocommerce/woocommerce-blocks/blob/4af2c0916a936369be8a4f0044683b90b3af4f0d/assets/js/blocks-registry/payment-methods/registry.ts#L1)
The payment registry stores all the configuration information for each payment method. We can register a new payment method here with the `registerPaymentMethod` and `registerExpressPaymentMethod `functions, also available to other plugins.
### Data Stores
Data stores are used to keep track of data that is likely to change during a user's session, such as the active payment method, whether the checkout has an error, etc. We split these data stores by areas of concern, so we have 2 data stores related to the checkout: `wc/store/checkout` [(file)](https://href.li/?https://github.com/woocommerce/woocommerce-blocks/blob/4af2c0916a936369be8a4f0044683b90b3af4f0d/assets/js/data/checkout/index.ts#L1) and `wc/store/payment` [(file)](https://href.li/?https://github.com/woocommerce/woocommerce-blocks/blob/4af2c0916a936369be8a4f0044683b90b3af4f0d/assets/js/data/payment-methods/index.ts#L1) . Data stores live in the `assets/js/data` folder.
### Contexts
Contexts are used to make data available to the Checkout block. Each of these provide data and functions related to a specific area of concern, via the use of a hook. For example, if we wanted to use the `onPaymentSetup` handler from the `PaymentEventsContext` context, we can do it like this:
```js
const { onPaymentSetup } = usePaymentEventsContext();
```
The other job of contexts is to run side effects for our Checkout block. What typically happens is that the `CheckoutEvents` and `PaymentEvents` will listen for changes in the checkout and payment data stores, and dispatch actions on those stores based on some logic.
For example, in the `CheckoutEvents` context, we dispatch the `emitValidateEvent` action when the checkout status is `before_processing`. There is a lot of similar logic that reacts to changes in status and other state data from these two stores.
The Checkout contexts are:
| Context | Description |
| ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------- |
| [CheckoutEvents](https://github.com/woocommerce/woocommerce-blocks/blob/4af2c0916a936369be8a4f0044683b90b3af4f0d/assets/js/base/context/providers/cart-checkout/checkout-events/index.tsx#L4) | Provides some checkout related event handlers |
| [ PaymentEvents ](https://github.com/woocommerce/woocommerce-blocks/blob/4af2c0916a936369be8a4f0044683b90b3af4f0d/assets/js/base/context/providers/cart-checkout/payment-methods/payment-method-events-context.tsx#L3) | Provides event handlers related to payments |
| [ CustomerData ](https://github.com/woocommerce/woocommerce-blocks/blob/4af2c0916a936369be8a4f0044683b90b3af4f0d/assets/js/base/context/providers/cart-checkout/customer/index.tsx#L1) | Provides data related to the current customer |
| [ ShippingData ](https://github.com/woocommerce/woocommerce-blocks/blob/4af2c0916a936369be8a4f0044683b90b3af4f0d/assets/js/base/context/providers/cart-checkout/shipping/index.js#L1) | Provides data and actions related to shipping errors |
### The Checkout Processor (checkout-processor.js)
The checkout processor component subscribes to changes in the checkout or payment data stores, packages up some of this data and calls the StoreApi `/checkout` endpoint when the conditions are right.
## The Checkout Provider
The [checkout provider](https://github.com/woocommerce/woocommerce-blocks/blob/trunk/assets/js/base/context/providers/cart-checkout/checkout-provider.js), wraps all the contexts mentioned above around the `CheckoutProcessor` component.
---
## Checkout User Flow
Below is the complete checkout flow
### 1\. Click the "Place Order" button
The checkout process starts when a user clicks the button
### 2\. Checkout status is set to `before_processing` [(file)](https://github.com/woocommerce/woocommerce-blocks/blob/4af2c0916a936369be8a4f0044683b90b3af4f0d/assets/js/base/context/providers/cart-checkout/checkout-events/index.tsx#L167)
As soon as the user clicks the "Place Order" button, we change the checkout status to _"before_processing"_. This is where we handle the validation of the checkout information.
### 3\. Emit the `checkout_validation_before_processing` event [(file)](https://github.com/woocommerce/woocommerce-blocks/blob/4af2c0916a936369be8a4f0044683b90b3af4f0d/assets/js/base/context/providers/cart-checkout/checkout-events/index.tsx#L113)
This is where the WooCommerce Blocks plugin and other plugins can register event listeners for dealing with validation. The event listeners for this event will run and if there are errors, we set checkout status to `idle` and display the errors to the user.
If there are no errors, we move to step 4 below.
### 4\. Checkout status is set to `processing` [(file)](https://github.com/woocommerce/woocommerce-blocks/blob/4af2c0916a936369be8a4f0044683b90b3af4f0d/assets/js/data/checkout/thunks.ts#L76)
The processing status is used by step 5 below to change the payment status
### 5\. Payment status is set to `processing` [(file)](https://github.com/woocommerce/woocommerce-blocks/blob/4af2c0916a936369be8a4f0044683b90b3af4f0d/assets/js/base/context/providers/cart-checkout/payment-methods/payment-method-events-context.tsx#L94)
Once all the checkout processing is done and if there are no errors, the payment processing begins
### 6\. Emit the `payment_processing` event [(file)](https://github.com/woocommerce/woocommerce-blocks/blob/4af2c0916a936369be8a4f0044683b90b3af4f0d/assets/js/data/payment-methods/thunks.ts#L42)
The `payment_processing` event is emitted. Otherplugins can register event listeners for this event and run their own code.
For example, the Stripe plugin checks the address and payment details here, and uses the stripe APIs to create a customer and payment reference within Stripe.
**Important note: The actual payment is not taken here**. **It acts like a pre-payment hook to run any payment plugin code before the actual payment is attempted.**
### 7\. Execute the `payment_processing` event listeners and set the payment and checkout states accordingly [(file)](https://github.com/woocommerce/woocommerce-blocks/blob/4af2c0916a936369be8a4f0044683b90b3af4f0d/assets/js/data/payment-methods/thunks.ts#L54-L132)
If the registered event listeners return errors, we will display this to the user.
If the event listeners are considered successful, we sync up the address of the checkout with the payment address, store the `paymentMethodData` in the payment store, and set the payment status property `{ isProcessing: true }`.
### 8\. POST to `/wc/store/v1/checkout` [(file)](https://github.com/woocommerce/woocommerce-blocks/blob/4af2c0916a936369be8a4f0044683b90b3af4f0d/assets/js/base/context/providers/cart-checkout/checkout-processor.js#L234)
The `/checkout` StoreApi endpoint is called if there are no payment errors. This will take the final customer addresses and chosen payment method, and any additional payment data, then attempts payment and returns the result.
**Important: payment is attempted through the StoreApi, NOT through the `payment_processing` event that is sent from the client**
### 9\. The `processCheckoutResponse` action is triggered on the checkout store [(file)](https://github.com/woocommerce/woocommerce-blocks/blob/4af2c0916a936369be8a4f0044683b90b3af4f0d/assets/js/data/checkout/thunks.ts#L33)
Once the fetch to the StoreApi `/checkout` endpoint returns a response, we pass this to the `processCheckoutResponse` action on the `checkout` data store.
It will perform the following actions:
- It sets the redirect url to redirect to once the order is complete
- It stores the payment result in the `checkout` data store.
- It changes the checkout status to `after_processing` (step 10)
### 10\. Checkout status is set to `after_processing` [(file)](https://github.com/woocommerce/woocommerce-blocks/blob/4af2c0916a936369be8a4f0044683b90b3af4f0d/assets/js/data/checkout/thunks.ts#L42)
The `after_processing` status indicates that we've finished the main checkout processing step. In this step, we run cleanup actions and display any errors that have been triggered during the last step.
### 11\. Emit the `checkout_after_processing_with_success` event [(file)](https://github.com/woocommerce/woocommerce-blocks/blob/4af2c0916a936369be8a4f0044683b90b3af4f0d/assets/js/data/checkout/thunks.ts#L118-L128)
If there are no errors, the `checkout_after_processing_with_success` event is triggered. This is where other plugins can run some code after the checkout process has been successful.
Any event listeners registered on the `checkout_after_processing_with_success` event will be executed. If there are no errors from the event listeners, `setComplete` action is called on the `checkout` data store to set the status to `complete` (step 13). An event listener can also return an error here, which will be displayed to the user.
### 12\. Emit the `checkout_after_processing_with_error` event [(file)](https://github.com/woocommerce/woocommerce-blocks/blob/4af2c0916a936369be8a4f0044683b90b3af4f0d/assets/js/data/checkout/thunks.ts#L104-L116)
If there has been an error from step 5, the `checkout_after_processing_with_error` event will be emitted. Other plugins can register event listeners to run here to display an error to the user. The event listeners are processed and display any errors to the user.
### 13\. Set checkout status to `complete` [(file)](https://github.com/woocommerce/woocommerce-blocks/blob/4af2c0916a936369be8a4f0044683b90b3af4f0d/assets/js/data/checkout/utils.ts#L146)
If there are no errors, the `status` property changes to `complete` in the checkout data store. This indicates that the checkout process is complete.
### 14\. Redirect [(file)](https://github.com/woocommerce/woocommerce-blocks/blob/4af2c0916a936369be8a4f0044683b90b3af4f0d/assets/js/base/context/providers/cart-checkout/checkout-processor.js#L193-L197)
Once the checkout status is set to `complete`, if there is a `redirectUrl` in the checkout data store, then we redirect the user to the URL.
## Other notable things
### Checking payment methods
A payment method is registered with a [configuration object](https://github.com/woocommerce/woocommerce-blocks/blob/4af2c0916a936369be8a4f0044683b90b3af4f0d/assets/js/types/type-defs/payments.ts#L60-L83). It must include a function named `canMakePayment`. This function should return true if the payment method can be used to pay for the current cart. The current cart (items, addresses, shipping methods etc.) is passed to this function, and each payment method is responsible for reporting whether it can be used.
The `checkPaymentMethodsCanPay()` [function](https://github.com/woocommerce/woocommerce-blocks/blob/4af2c0916a936369be8a4f0044683b90b3af4f0d/assets/js/data/payment-methods/check-payment-methods.ts#L26) goes through all the registered payment methods, checks if they can pay, and if so, adds them to the `availablePaymentMethods` property on the payment data store.
The `checkPaymentMethodsCanPay()` [function](https://github.com/woocommerce/woocommerce-blocks/blob/4af2c0916a936369be8a4f0044683b90b3af4f0d/assets/js/data/payment-methods/check-payment-methods.ts#L26) must be called in a few places in order to validate the payment methods before they can be displayed to the user as viable options.
- [Here](https://github.com/woocommerce/woocommerce-blocks/blob/4af2c0916a936369be8a4f0044683b90b3af4f0d/assets/js/data/cart/index.ts#L46-L57), once the cart loads, we want to be able to display express payment methods, so we need to validate them first.
- [Here](https://github.com/woocommerce/woocommerce-blocks/blob/4af2c0916a936369be8a4f0044683b90b3af4f0d/assets/js/data/cart/index.ts#L42-L43), once the cart changes, we may want to enable/disable certain payment methods
- [Here](https://github.com/woocommerce/woocommerce-blocks/blob/4af2c0916a936369be8a4f0044683b90b3af4f0d/assets/js/data/checkout/index.ts#L44-L49), once the checkout loads, we want to verify all registered payment methods

View File

@ -0,0 +1,196 @@
---
post_title: Cart and Checkout - Handling scripts, styles, and data
menu_title: Script, Styles, and Data Handling
tags: how-to
---
## The problem
You are an extension developer, and to allow users to interact with your extension on the client-side, you have written some CSS and JavaScript that you would like to be included on the page. Your JavaScript also relies on some server-side data, and you'd like this to be available to your scripts.
## The solution
You may use the `IntegrationRegistry` to register an `IntegrationInterface` this will be a class that will handle the enqueuing of scripts, styles, and data. You may have a different `IntegrationInterface` for each block (Mini-Cart, Cart and Checkout), or you may use the same one, it is entirely dependent on your use case.
You should use the hooks: `woocommerce_blocks_mini-cart_block_registration`. `woocommerce_blocks_cart_block_registration` and `woocommerce_blocks_checkout_block_registration`. These hooks pass an instance of [`IntegrationRegistry`](https://github.com/woocommerce/woocommerce-gutenberg-products-block/blob/trunk/src/Integrations/IntegrationRegistry.php) to the callback.
You may then use the `register` method on this object to register your `IntegrationInterface`.
## `IntegrationInterface` methods
To begin, we'll need to create our integration class, our `IntegrationInterface`. This will be a class that implements WooCommerce Blocks' interface named [`IntegrationInterface`](https://github.com/woocommerce/woocommerce-gutenberg-products-block/blob/trunk/src/Integrations/IntegrationInterface.php).
In this section, we will step through the interface's members and discuss what they are used for.
### `get_name()`
This is the `IntegrationInterface`'s way of namespacing your integration. The name chosen here should be unique to your extension. This method should return a string.
### `initialize()`
This is where any setup, or initialization for your integration should be placed. For example, you could register the scripts and styles your extension needs here. This method should not return anything.
### `get_script_handles()`
This is where the handles of any scripts you want to be enqueued on the client-side in the frontend context should be placed. This method should return an array of strings.
### `get_editor_script_handles()`
This is where the handles of any scripts you want to be enqueued on the client-side in the editor context should be placed. This method should return an array of strings.
### `get_script_data()`
This is where you can set values you want to be available to your scripts on the frontend. This method should return an associative array, the keys of which will be used to get the data using the JavaScript function `getSetting`.
The keys and values of this array should all be serializable.
## Usage example
Let's suppose we're the author of an extension: `WooCommerce Example Plugin`. We want to enqueue scripts, styles, and data on the frontend when either the Mini-Cart, Cart or Checkout blocks are being used.
We also want some data from a server-side function to be available to our front-end scripts.
You will notice that in the example below, we reference the `/build/index.asset.php` file. This is created by the [`DependencyExtractionWebpackPlugin`](https://www.npmjs.com/package/@wordpress/dependency-extraction-webpack-plugin) which creates a PHP file mapping the dependencies of your client-side scripts, so that they can be added in the `dependencies` array of `wp_register_script`.
Let's create our `IntegrationInterface`.
```php
<?php
use Automattic\WooCommerce\Blocks\Integrations\IntegrationInterface;
/**
* Class for integrating with WooCommerce Blocks
*/
class WooCommerce_Example_Plugin_Integration implements IntegrationInterface {
/**
* The name of the integration.
*
* @return string
*/
public function get_name() {
return 'woocommerce-example-plugin';
}
/**
* When called invokes any initialization/setup for the integration.
*/
public function initialize() {
$script_path = '/build/index.js';
$style_path = '/build/style-index.css';
/**
* The assets linked below should be a path to a file, for the sake of brevity
* we will assume \WooCommerce_Example_Plugin_Assets::$plugin_file is a valid file path
*/
$script_url = plugins_url( $script_path, \WooCommerce_Example_Plugin_Assets::$plugin_file );
$style_url = plugins_url( $style_path, \WooCommerce_Example_Plugin_Assets::$plugin_file );
$script_asset_path = dirname( \WooCommerce_Example_Plugin_Assets::$plugin_file ) . '/build/index.asset.php';
$script_asset = file_exists( $script_asset_path )
? require $script_asset_path
: array(
'dependencies' => array(),
'version' => $this->get_file_version( $script_path ),
);
wp_enqueue_style(
'wc-blocks-integration',
$style_url,
[],
$this->get_file_version( $style_path )
);
wp_register_script(
'wc-blocks-integration',
$script_url,
$script_asset['dependencies'],
$script_asset['version'],
true
);
wp_set_script_translations(
'wc-blocks-integration',
'woocommerce-example-plugin',
dirname( \WooCommerce_Example_Plugin_Assets::$plugin_file ) . '/languages'
);
}
/**
* Returns an array of script handles to enqueue in the frontend context.
*
* @return string[]
*/
public function get_script_handles() {
return array( 'wc-blocks-integration' );
}
/**
* Returns an array of script handles to enqueue in the editor context.
*
* @return string[]
*/
public function get_editor_script_handles() {
return array( 'wc-blocks-integration' );
}
/**
* An array of key, value pairs of data made available to the block on the client side.
*
* @return array
*/
public function get_script_data() {
$woocommerce_example_plugin_data = some_expensive_serverside_function();
return [
'expensive_data_calculation' => $woocommerce_example_plugin_data
];
}
/**
* Get the file modified time as a cache buster if we're in dev mode.
*
* @param string $file Local path to the file.
* @return string The cache buster value to use for the given file.
*/
protected function get_file_version( $file ) {
if ( defined( 'SCRIPT_DEBUG' ) && SCRIPT_DEBUG && file_exists( $file ) ) {
return filemtime( $file );
}
// As above, let's assume that WooCommerce_Example_Plugin_Assets::VERSION resolves to some versioning number our
// extension uses.
return \WooCommerce_Example_Plugin_Assets::VERSION;
}
}
```
As mentioned, we will need register our `IntegrationInterface` with WooCommerce Blocks, as we want our scripts to be included when either the Mini-Cart, Cart or Checkout is used, we need to register callbacks for three actions.
```php
add_action(
'woocommerce_blocks_mini-cart_block_registration',
function( $integration_registry ) {
$integration_registry->register( new WooCommerce_Example_Plugin_Integration() );
}
);
add_action(
'woocommerce_blocks_cart_block_registration',
function( $integration_registry ) {
$integration_registry->register( new WooCommerce_Example_Plugin_Integration() );
}
);
add_action(
'woocommerce_blocks_checkout_block_registration',
function( $integration_registry ) {
$integration_registry->register( new WooCommerce_Example_Plugin_Integration() );
}
);
```
Now, when we load a page containing either block, we should see the scripts we registered in `initialize` being loaded!
### Getting data added in `get_script_data`
We associated some data with the extension in the `get_script_data` method of our interface, we need to know how to get this!
In the `@woocommerce/settings` package there is a method you can import called `getSetting`. This method accepts a string. The name of the setting containing the data added in `get_script_data` is the name of your integration (i.e. the value returned by `get_name`) suffixed with `_data`. In our example it would be: `woocommerce-example-plugin_data`.
The value returned here is a plain old JavaScript object, keyed by the keys of the array returned by `get_script_data`, the values will serialized.

View File

@ -0,0 +1,60 @@
---
post_title: Cart and Checkout - Slot and fill
menu_title: Slot and Fill
tags: reference
---
## The problem
You added custom data to the [Store API](https://github.com/woocommerce/woocommerce/blob/1675c63bba94c59703f57c7ef06e7deff8fd6bba/plugins/woocommerce-blocks/docs/third-party-developers/extensibility/rest-api/extend-rest-api-add-data.md). You changed several strings using [Checkout filters](./category/cart-and-checkout-blocks/available-filters/). Now you want to render your own components in specific places in the Cart and Checkout.
## Solution
Slot and Fill are a pair of components that add the possibility to render your own HTML in pre-defined places in the Cart and Checkout. Your component will get access to contextual data and will get re-rendered when needed.
A _Slot_ is a place in the Cart and Checkout that can render an indefinite number of external components.
A _Fill_ is the component provided by third-party developers to render inside a _Slot_.
Slot and Fill use WordPress' API, and you can learn more about how they work in [the Slot and Fill documentation.](https://github.com/WordPress/gutenberg/tree/trunk/packages/components/src/slot-fill).
## Basic Usage
`ExperimentalOrderMeta` is a fill that will render in a slot below the Order summary section in the Cart and Checkout blocks.
The `ExperimentalOrderMeta` will automatically pass props to its top level child:
- `cart` which contains cart data
- `extensions` which contains data registered with `ExtendSchema::class` in `wc/store/cart` endpoint
- `context`, equal to the name of the Block in which the fill is rendered: `woocommerce/cart` or `woocommerce/checkout`
```jsx
const { registerPlugin } = wp.plugins;
const { ExperimentalOrderMeta } = wc.blocksCheckout;
const MyCustomComponent = ( { cart, extensions } ) => {
return <div className="my-component">Hello WooCommerce</div>;
};
const render = () => {
return (
<ExperimentalOrderMeta>
<MyCustomComponent />
</ExperimentalOrderMeta>
);
};
registerPlugin( 'my-plugin-namespace', {
render,
scope: 'woocommerce-checkout',
} );
```
## registerPlugin
In the above example, we're using `registerPlugin`. This plugin will take our component and render it, but it won't make it visible. The SlotFill part is the one responsible for actually having it show up in the correct place.
You use `registerPlugin` to feed in your plugin namespace, your component `render`, and the scope of your `registerPlugin`. The value of scope should always be `woocommerce-checkout`.
## Requirements
For this to work, your script must be enqueued after Cart and Checkout. You can follow the [IntegrationInterface](https://github.com/woocommerce/woocommerce-gutenberg-products-block/blob/50f9b3e8d012f425d318908cc13d9c601d97bd68/docs/extensibility/integration-interface.md) documentation for enqueueing your script.

View File

@ -0,0 +1,42 @@
---
post_title: Check if a Payment Method Support Refunds, Subscriptions or Pre-orders
menu_title: Payment method support for refunds, subscriptions, pre-orders
tags: payment-methods
current wccom url: https://woocommerce.com/document/check-if-payment-gateway-supports-refunds-subscriptions-preorders/
---
If a payment method's documentation doesnt clearly outline the supported features, you can often find what features are supported by looking at payment methods code.
Payment methods can add support for certain features from WooCommerce and its extensions. For example, a payment method can support refunds, subscriptions or pre-orders functionality.
## Simplify Commerce example
Taking the Simplify Commerce payment method as an example, open the plugin files in your favorite editor and search for `$this->supports`. You'll find the supported features:
```php
class WC_Gateway_Simplify_Commerce extends WC_Payment_Gateway {
/** * Constructor */
public function __construct() {
$this->id
= 'simplify_commerce';
$this->method_title
= __( 'Simplify Commerce', 'woocommerce' );
$this->method_description = __( 'Take payments via Simplify Commerce - uses simplify.js to create card tokens and the Simplify Commerce SDK. Requires SSL when sandbox is disabled.', 'woocommerce' );
$this->has_fields = true;
$this->supports = array(
'subscriptions',
'products',
'subscription_cancellation',
'subscription_reactivation',
'subscription_suspension',
'subscription_amount_changes',
'subscription_payment_method_change',
'subscription_date_changes',
'default_credit_card_form',
'refunds',
'pre-orders'
);
```
If you don't find `$this->supports` in the plugin files, that may mean that the payment method isn't correctly declaring support for refunds, subscripts or pre-orders.

View File

@ -0,0 +1,77 @@
---
post_title: Code snippets for configuring special tax scenarios
menu_title: Configuring special tax scenarios
tags: code-snippet, tax
current wccom url: https://woocommerce.com/document/setting-up-taxes-in-woocommerce/configuring-specific-tax-setups-in-woocommerce/#configuring-special-tax-setups
---
## Scenario A: Charge the same price regardless of location and taxes
If a store enters product prices including taxes, but levies various location-based tax rates, the prices will appear to change depending on which tax rate is applied. In reality, the base price remains the same, but the taxes influence the total. [Follow this link for a detailed explanation](https://woocommerce.com/document/how-taxes-work-in-woocommerce/#cross-border-taxes).
Some merchants prefer to dynamically change product base prices to account for the changes in taxes and so keep the total price consistent regardless of tax rate. Enable that functionality by adding the following snippet to your child theme's functions.php file or via a code snippet plugin.
```php
<?php
add_filter( 'woocommerce_adjust_non_base_location_prices', '__return_false' );
```
## Scenario B: Charge tax based on the subtotal amount
The following snippet is useful in case where a store only ads taxes when the subtotal reaches a specified minimum. In the code snippet below that minimum is 110 of the store's currency. Adjust the snippet according to your requirements.
```php
<?php
add_filter( 'woocommerce_product_get_tax_class', 'big_apple_get_tax_class', 1, 2 );
function big_apple_get_tax_class( $tax_class, $product ) {
if ( WC()->cart->subtotal <= 110 )
$tax_class = 'Zero Rate';
return $tax_class;
}
```
## Scenario C: Apply different tax rates based on the customer role
Some merchants may require different tax rates to be applied based on a customer role to accommodate for wholesale status or tax exemption.
To enable this functionality, add the following snippet to your child theme's functions.php file or via a code snippet plugin. In this snippet, users with “administrator” capabilities will be assigned the **Zero rate tax class**. Adjust it according to your requirements.
```php
<?php
/**
* Apply a different tax rate based on the user role.
*/
function wc_diff_rate_for_user( $tax_class, $product ) {
if ( is_user_logged_in() && current_user_can( 'administrator' ) ) {
$tax_class = 'Zero Rate';
}
return $tax_class;
}
add_filter( 'woocommerce_product_get_tax_class', 'wc_diff_rate_for_user', 1, 2 );
add_filter( 'woocommerce_product_variation_get_tax_class', 'wc_diff_rate_for_user', 1, 2 );
```
## Scenario D: Show 0 value taxes
Taxes that have 0-value are hidden by default. To show them regardless, add the following snippet to your theme's functions.php file or via a code snippet plugins:
```php
add_filter( 'woocommerce_order_hide_zero_taxes', '__return_false' );
```
## Scenario E: Suffixes on the main variable product
One of the tax settings for WooCommerce enables the use of suffixes to add additional information to product prices. It's available for use with the variations of a variable product, but is disabled at the main variation level as it can impact website performance when there are many variations.
The method responsible for the related price output can be customized via filter hooks if needed for variable products. This will require customization that can be implemented via this filter:
```php
add_filter( 'woocommerce_show_variation_price', '__return_true' );
```

Binary file not shown.

After

Width:  |  Height:  |  Size: 189 KiB

View File

@ -0,0 +1,16 @@
---
post_title: Disabling Marketplace Suggestions Programmatically
menu_title: Disabling marketplace suggestions
current wccom url: https://woocommerce.com/document/woocommerce-marketplace-suggestions-settings/#section-6
---
For those who prefer to programmatically disable marketplace suggestions that are fetched from woocommerce.com, add the `woocommerce_allow_marketplace_suggestions` filter to your themes `functions.php` or a custom plugin.
For example:
```php
add_filter( 'woocommerce_allow_marketplace_suggestions', '__return_false' );
```
This filter will completely remove Marketplace Suggestions from your WooCommerce admin.

View File

@ -0,0 +1,41 @@
---
post_title: Displaying Custom Fields in Your Theme or Site
menu_title: Displaying custom fields in theme
tags: code-snippet
current wccom url: https://woocommerce.com/document/custom-product-fields/
---
## Displaying Custom Fields in Your Theme or Site
You can use the metadata from custom fields you add to your products to display the added information within your theme or site.
To display the custom fields for each product, you have to edit your themes files. Heres an example of how you might display a custom field within the single product pages after the short description:
![image](https://github.com/woocommerce/woocommerce-developer-advocacy/assets/15178758/ed417ed8-4462-45b9-96b6-c0141afaeb2b)
```php
<?php
// Display a product custom field within single product pages after the short description
function woocommerce_custom_field_example() {
if ( ! is_product() ) {
return;
}
global $product;
if ( ! is_object( $product ) ) {
$product = wc_get_product( get_the_ID() );
}
$custom_field_value = get_post_meta( $product->get_id(), 'woo_custom_field', true );
if ( ! empty( $custom_field_value ) ) {
echo '<div class="custom-field">' . esc_html( $custom_field_value ) . '</div>';
}
}
add_action( 'woocommerce_before_add_to_cart_form', 'woocommerce_custom_field_example', 10 );
```

View File

@ -0,0 +1,147 @@
---
post_title: Free Shipping Customizations
menu_title: Free shipping customizations
tags: code-snippets
current wccom url: https://woocommerce.com/document/free-shipping/#advanced-settings-customization
combined with: https://woocommerce.com/document/hide-other-shipping-methods-when-free-shipping-is-available/#use-a-plugin
---
## Free Shipping: Advanced Settings/Customization
### Overview
By default, WooCommerce shows all shipping methods that match the customer and the cart contents. This means Free Shipping also shows along with Flat Rate and other Shipping Methods.
The functionality to hide all other methods, and only show Free Shipping, requires either custom PHP code or a plugin/extension.
### Adding code
Before adding snippets, clear your WooCommerce cache. Go to WooCommerce > System Status > Tools > WooCommerce Transients > Clear transients.
Add this code to your child theme's `functions.php`, or via a plugin that allows custom functions to be added. Please don't add custom code directly to a parent theme's `functions.php` as changes are entirely erased when a parent theme updates.
## Code Snippets
### Enabling or Disabling Free Shipping via Hooks
You can hook into the `is_available` function of the free shipping method.
```php
return apply_filters( 'woocommerce_shipping_' . $this->id . '_is_available', $is_available );
```
This means you can use `add_filter()` on `woocommerce_shipping_free_shipping_is_available` and return `true` or `false`.
### How do I only show Free Shipping?
The following snippet hides everything but `free_shipping`, if it's available and the customer's cart qualifies.
```php
/**
* Hide shipping rates when free shipping is available.
* Updated to support WooCommerce 2.6 Shipping Zones.
*
* @param array $rates Array of rates found for the package.
* @return array
*/
function my_hide_shipping_when_free_is_available( $rates ) {
$free = array();
foreach ( $rates as $rate_id => $rate ) {
if ( 'free_shipping' === $rate->method_id ) {
$free[ $rate_id ] = $rate;
break;
}
}
return ! empty( $free ) ? $free : $rates;
}
add_filter( 'woocommerce_package_rates', 'my_hide_shipping_when_free_is_available', 100 );
```
### How do I only show Local Pickup and Free Shipping?
The snippet below hides everything but `free_shipping` and `local_pickup`, if it's available and the customer's cart qualifies.
```php
/**
* Hide shipping rates when free shipping is available, but keep "Local pickup"
* Updated to support WooCommerce 2.6 Shipping Zones
*/
function hide_shipping_when_free_is_available( $rates, $package ) {
$new_rates = array();
foreach ( $rates as $rate_id => $rate ) {
// Only modify rates if free_shipping is present.
if ( 'free_shipping' === $rate->method_id ) {
$new_rates[ $rate_id ] = $rate;
break;
}
}
if ( ! empty( $new_rates ) ) {
//Save local pickup if it's present.
foreach ( $rates as $rate_id => $rate ) {
if ('local_pickup' === $rate->method_id ) {
$new_rates[ $rate_id ] = $rate;
break;
}
}
return $new_rates;
}
return $rates;
}
add_filter( 'woocommerce_package_rates', 'hide_shipping_when_free_is_available', 10, 2 );
```
### Only show free shipping in all states except…
This snippet results in showing only free shipping in all states except the exclusion list. It hides free shipping if the customer is in one of the states listed:
```php
/**
* Hide ALL shipping options when free shipping is available and customer is NOT in certain states
*
* Change $excluded_states = array( 'AK','HI','GU','PR' ); to include all the states that DO NOT have free shipping
*/
add_filter( 'woocommerce_package_rates', 'hide_all_shipping_when_free_is_available' , 10, 2 );
/**
* Hide ALL Shipping option when free shipping is available
*
* @param array $available_methods
*/
function hide_all_shipping_when_free_is_available( $rates, $package ) {
$excluded_states = array( 'AK','HI','GU','PR' );
if( isset( $rates['free_shipping'] ) AND !in_array( WC()->customer->shipping_state, $excluded_states ) ) :
// Get Free Shipping array into a new array
$freeshipping = array();
$freeshipping = $rates['free_shipping'];
// Empty the $available_methods array
unset( $rates );
// Add Free Shipping back into $avaialble_methods
$rates = array();
$rates[] = $freeshipping;
endif;
if( isset( $rates['free_shipping'] ) AND in_array( WC()->customer->shipping_state, $excluded_states ) ) {
// remove free shipping option
unset( $rates['free_shipping'] );
}
return $rates;
}
```
### Enable Shipping Methods on a per Class / Product Basis, split orders, or other scenarios?
Need more flexibility? Take a look at our [premium Shipping Method extensions](https://woocommerce.com/product-category/woocommerce-extensions/shipping-methods/).

View File

@ -0,0 +1,35 @@
---
post_title: Advanced settings and customization for legacy Local Pickup
tags: code-snippet
current wccom url: https://woocommerce.com/document/local-pickup/#advanced-settings-customization
note: Docs links out to Skyverge's site for howto add a custom email - do we have our own alternative?
---
## Disable local taxes when using local pickup
Local Pickup calculates taxes based on your store's location (address) by default, and not the customer's address. Add this snippet at the end of your theme's `functions.php` to use your standard tax configuration instead:
```php
add_filter( 'woocommerce_apply_base_tax_for_local_pickup', '__return_false' );
```
Regular taxes is then used when local pickup is selected, instead of store-location-based taxes.
## Changing the location for local taxes
To charge local taxes based on the postcode and city of the local pickup location, you need to define the shop's base city and post code using this example code:
```php
add_filter( 'woocommerce_countries_base_postcode', create_function( '', 'return "80903";' ) );
add_filter( 'woocommerce_countries_base_city', create_function( '', 'return "COLORADO SPRINGS";' ) );
```
Update `80903` to reflect your preferred postcode/zip, and `COLORADO SPRINGS` with your preferred town or city.
## Custom emails for local pickup
_Shipping Address_ is not displayed on the admin order emails when Local Pickup is used as the shipping method.
Since all core shipping options use the standard order flow, customers receive the same order confirmation email whether they select local pickup or any other shipping option.
Use this guide to create custom emails for local pickup if you'd like to send a separate email for local pickup orders: [How to Add a Custom WooCommerce Email](https://www.skyverge.com/blog/how-to-add-a-custom-woocommerce-email/).

View File

@ -0,0 +1,27 @@
---
post_title: Making your translation upgrade safe
menu_title: Translation upgrade safety
tags: code-snippet
current wccom url: https://woocommerce.com/document/woocommerce-localization/#making-your-translation-upgrade-safe
---
Like all other plugins, WooCommerce keeps translations in `wp-content/languages/plugins`.
However, if you want to include a custom translation, you can add them to `wp-content/languages/woocommerce`, or you can use a snippet to load a custom translation stored elsewhere:
```php
// Code to be placed in functions.php of your theme or a custom plugin file.
add_filter( 'load_textdomain_mofile', 'load_custom_plugin_translation_file', 10, 2 );
/*
* Replace 'textdomain' with your plugin's textdomain. e.g. 'woocommerce'.
* File to be named, for example, yourtranslationfile-en_GB.mo
* File to be placed, for example, wp-content/lanaguages/textdomain/yourtranslationfile-en_GB.mo
*/
function load_custom_plugin_translation_file( $mofile, $domain ) {
if ( 'textdomain' === $domain ) {
$mofile = WP_LANG_DIR . '/textdomain/yourtranslationfile-' . get_locale() . '.mo';
}
return $mofile;
}
```

View File

@ -0,0 +1,210 @@
---
post_title: Shipping Method API
menu_title: Shipping method API
tags: shipping, API
current wccom url: https://woocommerce.com/document/shipping-method-api/
---
# Shipping Method API
WooCommerce has a shipping method API which plugins can use to add their own rates. This article outlines steps to create a new shipping method and interact with the API.
## Create a plugin
First, create a regular WordPress/WooCommerce plugin (see [Create a plugin](https://woocommerce.com/document/create-a-plugin/)). Youll define your shipping method class in this plugin file and maintain it outside of WooCommerce.
## Create a function to house your class
To ensure the classes you need to extend exist, you should wrap your class in a function which is called after all plugins are loaded:
```php
function your_shipping_method_init() {
// Your class will go here
}
add_action( 'woocommerce_shipping_init', 'your_shipping_method_init' );
```
## Create your class
Create your class and place it inside the function you just created. Make sure it extends the shipping method class so that you have access to the API. Youll see below we also init our shipping method options.
```php
if ( ! class_exists( 'WC_Your_Shipping_Method' ) ) {
class WC_Your_Shipping_Method extends WC_Shipping_Method {
/**
* Constructor for your shipping class
*
* @access public
* @return void
*/
public function __construct() {
$this->id = 'your_shipping_method';
$this->title = __( 'Your Shipping Method' );
$this->method_description = __( 'Description of your shipping method' ); //
$this->enabled = "yes"; // This can be added as an setting but for this example its forced enabled
$this->init();
}
/**
* Init your settings
*
* @access public
* @return void
*/
function init() {
// Load the settings API
$this->init_form_fields(); // This is part of the settings API. Override the method to add your own settings
$this->init_settings(); // This is part of the settings API. Loads settings you previously init.
// Save settings in admin if you have any defined
add_action( 'woocommerce_update_options_shipping_' . $this->id, array( $this, 'process_admin_options' ) );
}
/**
* calculate_shipping function.
*
* @access public
* @param mixed $package
* @return void
*/
public function calculate_shipping( $package ) {
// This is where you'll add your rates
}
}
}
```
As well as declaring your class, you also need to tell WooCommerce it exists with another function:
```php
function add_your_shipping_method( $methods ) {
$methods['your_shipping_method'] = 'WC_Your_Shipping_Method';
return $methods;
}
add_filter( 'woocommerce_shipping_methods', 'add_your_shipping_method' );
```
## Defining settings/options
You can define your options once the above is in place by using the settings API. In the snippets above youll notice we `init_form_fields` and `init_settings`. These load up the settings API. To see how to add settings, see [WooCommerce settings API](https://woocommerce.com/document/settings-api/).
## The calculate_shipping() method
Add your rates by usign the `calculate_shipping()` method. WooCommerce calls this when doing shipping calculations. Do your plugin specific calculations here and then add the rates via the API. Like so:
```php
$rate = array(
'label' => "Label for the rate",
'cost' => '10.99',
'calc_tax' => 'per_item'
);
// Register the rate
$this->add_rate( $rate );
```
`Add_rate` takes an array of options. The defaults/possible values for the array are as follows:
```php
$defaults = array(
'label' => '', // Label for the rate
'cost' => '0', // Amount for shipping or an array of costs (for per item shipping)
'taxes' => '', // Pass an array of taxes, or pass nothing to have it calculated for you, or pass 'false' to calculate no tax for this method
'calc_tax' => 'per_order' // Calc tax per_order or per_item. Per item needs an array of costs passed via 'cost'
);
```
Your shipping method can pass as many rates as you want just ensure that the id for each is different. The user will get to choose rate during checkout.
## Piecing it all together
The skeleton shipping method code all put together looks like this:
```php
<?php
/*
Plugin Name: Your Shipping plugin
Plugin URI: https://woocommerce.com/
Description: Your shipping method plugin
Version: 1.0.0
Author: WooThemes
Author URI: https://woocommerce.com/
*/
/**
* Check if WooCommerce is active
*/
if ( in_array( 'woocommerce/woocommerce.php', apply_filters( 'active_plugins', get_option( 'active_plugins' ) ) ) ) {
function your_shipping_method_init() {
if ( ! class_exists( 'WC_Your_Shipping_Method' ) ) {
class WC_Your_Shipping_Method extends WC_Shipping_Method {
/**
* Constructor for your shipping class
*
* @access public
* @return void
*/
public function __construct() {
$this->id = 'your_shipping_method'; // Id for your shipping method. Should be uunique.
$this->method_title = __( 'Your Shipping Method' ); // Title shown in admin
$this->method_description = __( 'Description of your shipping method' ); // Description shown in admin
$this->enabled = "yes"; // This can be added as an setting but for this example its forced enabled
$this->title = "My Shipping Method"; // This can be added as an setting but for this example its forced.
$this->init();
}
/**
* Init your settings
*
* @access public
* @return void
*/
function init() {
// Load the settings API
$this->init_form_fields(); // This is part of the settings API. Override the method to add your own settings
$this->init_settings(); // This is part of the settings API. Loads settings you previously init.
// Save settings in admin if you have any defined
add_action( 'woocommerce_update_options_shipping_' . $this->id, array( $this, 'process_admin_options' ) );
}
/**
* calculate_shipping function.
*
* @access public
* @param array $package
* @return void
*/
public function calculate_shipping( $package = array() ) {
$rate = array(
'label' => $this->title,
'cost' => '10.99',
'calc_tax' => 'per_item'
);
// Register the rate
$this->add_rate( $rate );
}
}
}
}
add_action( 'woocommerce_shipping_init', 'your_shipping_method_init' );
function add_your_shipping_method( $methods ) {
$methods['your_shipping_method'] = 'WC_Your_Shipping_Method';
return $methods;
}
add_filter( 'woocommerce_shipping_methods', 'add_your_shipping_method' );
}
```
For further information, please check out the [Shipping Method API Wiki](https://github.com/woocommerce/woocommerce/wiki/Shipping-Method-API).

View File

@ -0,0 +1,22 @@
---
post_title: SSL and HTTPS and WooCommerce
menu_title: SSL and HTTPS and WooCommerce
tags: code-snippet
current wccom url: https://woocommerce.com/document/ssl-and-https/#websites-behind-load-balancers-or-reverse-proxies
---
## Websites behind load balancers or reverse proxies
WooCommerce uses the `is_ssl()` WordPress function to verify if your website using SSL or not.
`is_ssl()` checks if the connection is via HTTPS or on Port 443. However, this won't work for websites behind load balancers, especially websites hosted at Network Solutions. For details, read [WordPress is_ssl() function reference notes](https://codex.wordpress.org/Function_Reference/is_ssl#Notes).
Websites behind load balancers or reverse proxies that support `HTTP_X_FORWARDED_PROTO` can be fixed by adding the following code to the `wp-config.php` file, above the require_once call:
```php
if ( isset( $_SERVER['HTTP_X_FORWARDED_PROTO'] ) && 'https' == $_SERVER['HTTP_X_FORWARDED_PROTO'] ) {
$_SERVER['HTTPS'] = 'on';
}
```
**Note:** If you use CloudFlare, you need to configure it. Check their documentation.

View File

@ -0,0 +1,24 @@
---
post_title: Uninstall and remove all WooCommerce Data
menu_title: Uninstalling and removing data
tags: code-snippet
current wccom url: https://woocommerce.com/document/installing-uninstalling-woocommerce/#uninstalling-woocommerce
---
The WooCommerce plugin can be uninstalled like any other WordPress plugin. By default, the WooCommerce data is left in place though.
If you need to remove *all* WooCommerce data as well, including products, order data, coupons, etc., you need to to modify the site's `wp-config.php` *before* deactivating and deleting the WooCommerce plugin.
As this action is destructive and permanent, the information is provided as is. WooCommerce Support cannot help with this process or anything that happens as a result.
To fully remove all WooCommerce data from your WordPress site, open `wp-config.php`, scroll down to the bottom of the file, and add the following constant on its own line above `/* That's all, stop editing. */`.
```php
define( 'WC_REMOVE_ALL_DATA', true );
/* That's all, stop editing! Happy publishing. */
```
Then, once the changes are saved to the file, when you deactivate and delete WooCommerce, all of its data is removed from your WordPress site database.
![Uninstall WooCommerce WPConfig](https://woocommerce.com/wp-content/uploads/2020/03/uninstall_wocommerce_plugin_wpconfig.png)

View File

@ -0,0 +1,33 @@
---
post_title: Using NGINX server to protect your upload directory
menu_title: NGINX server to protect upload directory
tags: code-snippet
current wccom url: https://woocommerce.com/document/digital-downloadable-product-handling/#protecting-your-uploads-directory
---
If you using NGINX server for your site along with **X-Accel-Redirect/X-Sendfile** or **Force Downloads** download method, it is necessary that you add this configuration for better security:
```php
# Protect WooCommerce upload folder from being accessed directly.
# You may want to change this config if you are using "X-Accel-Redirect/X-Sendfile" or "Force Downloads" method for downloadable products.
# Place this config towards the end of "server" block in NGINX configuration.
location ~* /wp-content/uploads/woocommerce_uploads/ {
if ( $upstream_http_x_accel_redirect = "" ) {
return 403;
}
internal;
}
```
And this the configuration in case you are using **Redirect only** download method:
```php
# Protect WooCommerce upload folder from being accessed directly.
# You may want to change this config if you are using "Redirect Only" method for downloadable products.
# Place this config towards the end of "server" block in NGINX configuration.
location ~* /wp-content/uploads/woocommerce_uploads/ {
autoindex off;
}
```
If you do not know which web server you are using, please reach out to your host along with a link to this support page.

View File

@ -15,7 +15,7 @@ Inside each subfolder you'll find various markdown files. When imported into the
## Getting Setup
> This guide presumes that you're familar with basic Git and GitHub functionality, that you're signed into a GitHub account, and that you have Git setup locally. If you're new to GitHub, we recommend reading their [quickstart](https://docs.github.com/en/get-started/quickstart/hello-world) and [working with forks](https://docs.github.com/en/pull-requests/collaborating-with-pull-requests/working-with-forks/fork-a-repo) guides before getting started.
> This guide presumes that you're familiar with basic Git and GitHub functionality, that you're signed into a GitHub account, and that you have Git setup locally. If you're new to GitHub, we recommend reading their [quickstart](https://docs.github.com/en/get-started/quickstart/hello-world) and [working with forks](https://docs.github.com/en/pull-requests/collaborating-with-pull-requests/working-with-forks/fork-a-repo) guides before getting started.
### Initial Setup
@ -33,7 +33,7 @@ Inside each subfolder you'll find various markdown files. When imported into the
6. [Open a pull request](https://docs.github.com/en/pull-requests/collaborating-with-pull-requests/proposing-changes-to-your-work-with-pull-requests/creating-a-pull-request) that merges your branch with the WooCommerce monorepo's trunk branch.
* To do this, when creating the pull request, set the `base repository` to `woocommerce/woocommerce`, the `base` to `trunk`, the `head repository` to `yourgithubusername/woocommerce` and the `compare` to the branch you created (eg: `docs/improve-extension-performance`).
* When creating the pull request, set a descriptive title. Additionally, ensure you fill out the template provided in the description. For purely docs changes, your testing instructions should reference any major changes you think should be checked.
7. The WooCommerce Developer Advocacy team will review your pull request and provide feedback via the comments as neccesary. Once the content is ready, we'll merge it into `trunk` and it'll appear on the Woo Developer Docs site!
7. The WooCommerce Developer Advocacy team will review your pull request and provide feedback via the comments as necessary. Once the content is ready, we'll merge it into `trunk` and it'll appear on the Woo Developer Docs site!
## Creating New Pages

View File

@ -16,7 +16,7 @@ The WooCommerce core plugin code can be found in our [monorepo](https://github.c
### Code of Conduct
Contributing to an open source project requires cooperation amongst individuals and organziations all working to make our project a stable and safe place to build and ask questions. Please thoroughly read our [Code of Conduct](https://github.com/woocommerce/woocommerce/blob/trunk/SECURITY.md) to get familiar with our standards and processes.
Contributing to an open source project requires cooperation amongst individuals and organizations all working to make our project a stable and safe place to build and ask questions. Please thoroughly read our [Code of Conduct](https://github.com/woocommerce/woocommerce/blob/trunk/SECURITY.md) to get familiar with our standards and processes.
### Contributor Guidelines

File diff suppressed because one or more lines are too long

View File

@ -0,0 +1,64 @@
---
category_title: Extensibility in Blocks
category_slug: extensibility-in-blocks
post_title: Extensibility in blocks
---
These documents are all dealing with extensibility in the various WooCommerce Blocks.
## Imports and dependency extraction
The documentation in this section will use window globals in code examples, for example:
```js
const { registerCheckoutFilters } = window.wc.blocksCheckout;
```
However, if you're using `@woocommerce/dependency-extraction-webpack-plugin` for enhanced dependency management you can instead use ES module syntax:
```js
import { registerCheckoutFilters } from '@woocommerce/blocks-checkout';
```
See <https://www.npmjs.com/package/@woocommerce/dependency-extraction-webpack-plugin> for more information.
## Hooks (actions and filters)
| Document | Description |
| ----------------------------- | ------------------------------------------------------- |
| [Actions](https://github.com/woocommerce/woocommerce/blob/trunk/plugins/woocommerce-blocks/docs/third-party-developers/extensibility/hooks/actions.md) | Documentation covering action hooks on the server side. |
| [Filters](https://github.com/woocommerce/woocommerce/blob/trunk/plugins/woocommerce-blocks/docs/third-party-developers/extensibility/hooks/filters.md) | Documentation covering filter hooks on the server side. |
| [Migrated Hooks](/docs/cart-and-checkout-legacy-hooks/) | Documentation covering the migrated WooCommerce core hooks. |
## REST API
| Document | Description |
| ---------------------------------------------------------------------------------------------- | ------------------------------------------------------------------- |
| [Exposing your data in the Store API.](https://github.com/woocommerce/woocommerce/blob/trunk/plugins/woocommerce-blocks/docs/third-party-developers/extensibility/rest-api/extend-rest-api-add-data.md) | Explains how you can add additional data to Store API endpoints. |
| [Available endpoints to extend with ExtendSchema](https://github.com/woocommerce/woocommerce/blob/trunk/plugins/woocommerce-blocks/docs/third-party-developers/extensibility/rest-api/available-endpoints-to-extend.md) | A list of all available endpoints to extend. |
| [Available Formatters](https://github.com/woocommerce/woocommerce/blob/trunk/plugins/woocommerce-blocks/docs/third-party-developers/extensibility/rest-api/extend-rest-api-formatters.md) | Available `Formatters` to format data for use in the Store API. |
| [Updating the cart with the Store API](https://github.com/woocommerce/woocommerce/blob/trunk/plugins/woocommerce-blocks/docs/third-party-developers/extensibility/rest-api/extend-rest-api-update-cart.md) | Update the server-side cart following an action from the front-end. |
## Checkout Payment Methods
| Document | Description |
| -------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------- |
| [Checkout Flow and Events](/docs/cart-and-checkout-checkout-flow-and-events/) | All about the checkout flow in the checkout block and the various emitted events that can be subscribed to. |
| [Payment Method Integration](/docs/cart-and-checkout-payment-method-integration-for-the-checkout-block/) | Information about implementing payment methods. |
| [Filtering Payment Methods](/docs/cart-and-checkout-filtering-payment-methods-in-the-checkout-block/) | Information about filtering the payment methods available in the Checkout Block. |
## Checkout Block
In addition to the reference material below, [please see the `block-checkout` package documentation](https://github.com/woocommerce/woocommerce/blob/trunk/plugins/woocommerce-blocks/packages/checkout/README.md) which is used to extend checkout with Filters, Slot Fills, and Inner Blocks.
| Document | Description |
|--------------------------------------------------------------------------------------------------| ----------------------------------------------------------------------------------------------------------------- |
| [How the Checkout Block processes an order](/docs/cart-and-checkout-how-the-checkout-block-processes-an-order/) | The detailed inner workings of the Checkout Flow. |
| [IntegrationInterface](/docs/cart-and-checkout-handling-scripts-styles-and-data/) | The `IntegrationInterface` class and how to use it to register scripts, styles, and data with WooCommerce Blocks. |
| [Available Filters](/docs/category/cart-and-checkout-blocks/available-filters/) | All about the filters that you may use to change values of certain elements of WooCommerce Blocks. |
| [Slots and Fills](/docs/cart-and-checkout-slot-and-fill/) | Explains Slot Fills and how to use them to render your own components in Cart and Checkout. |
| [Available Slot Fills](/docs/cart-and-checkout-available-slots/) | Available Slots that you can use and their positions in Cart and Checkout. |
| [DOM Events](/docs/cart-and-checkout-dom-events/) | A list of DOM Events used by some blocks to communicate between them and with other parts of WooCommerce. |
| [Filter Registry](https://github.com/woocommerce/woocommerce/blob/trunk/plugins/woocommerce-blocks/packages/checkout/filter-registry/README.md) | The filter registry allows callbacks to be registered to manipulate certain values. |
| [Additional Checkout Fields](/docs/cart-and-checkout-additional-checkout-fields/) | The filter registry allows callbacks to be registered to manipulate certain values. |

View File

@ -7,21 +7,27 @@ tags: reference
When developing for WordPress and WooCommerce, it's important to consider the nature and permanence of your data. This will help you decide the best way to store it. Here's a quick primer:
## Transients
If the data may not always be present (i.e., it expires), use a [transient](https://developer.wordpress.org/apis/handbook/transients/). Transients are a simple and standardized way of storing cached data in the database temporarily by giving it a custom name and a timeframe after which it will expire and be deleted.
## WP Cache
If the data is persistent but not always present, consider using the [WP Cache](https://developer.wordpress.org/reference/classes/wp_object_cache/). The WP Cache functions allow you to cache data that is computationally expensive to regenerate, such as complex query results.
## wp_options Table
If the data is persistent and always present, consider the [wp_options table](https://developer.wordpress.org/apis/handbook/options/). The Options API is a simple and standardized way of storing data in the wp_options table in the WordPress database.
## Post Types
If the data type is an entity with n units, consider a [post type](https://developer.wordpress.org/post_type/). Post types are "types" of content that are stored in the same way, but are easy to distinguish in the code and UI.
## Taxonomies
If the data is a means of sorting/categorizing an entity, consider a [taxonomy](https://developer.wordpress.org/taxonomy/). Taxonomies are a way of grouping things together.
## Logging
Logs should be written to a file using the [WC_Logger](https://woocommerce.com/wc-apidocs/class-WC_Logger.html) class. This is a simple and standardized way of recording events and errors for debugging purposes.
Remember, the best method of data storage depends on the nature of the data and how it will be used in your application.

View File

@ -57,7 +57,7 @@ function sync_coming_soon_to_other_plugins( $old_value, $new_value, $option ) {
#### Trigger from other plugins
You can use the following example to enable or disable WooCommerce coming soon mode from another plugin by directy updating `woocommerce_coming_soon` option:
You can use the following example to enable or disable WooCommerce coming soon mode from another plugin by directly updating `woocommerce_coming_soon` option:
```php
function sync_coming_soon_from_other_plugins( $is_enabled ) {

View File

@ -140,9 +140,9 @@ wc_get_logger()->info(
### Best practices
* Rather than using the `WC_Logger`s `log()` method directly, it's better to use one of the wrapper methods that's specific to the log level. E.g. `info()` or `error()`.
* Rather than using the `WC_Logger`'s `log()` method directly, it's better to use one of the wrapper methods that's specific to the log level. E.g. `info()` or `error()`.
* Write a message that is a complete, coherent sentence. This will make it more useful for people who aren't familiar with the codebase.
* Log messages should not be translatable (see the discussion about this in the comments). Keeping the message in English makes it easier to search for solutions based on the message contents, and also makes it easier for Happiness Engineers to understand what's happening, since they may not speak the same language as the site owner.
* Log messages should not be translatable. Keeping the message in English makes it easier to search for solutions based on the message contents, and also makes it easier for anyone troubleshooting to understand what's happening, since they may not speak the same language as the site owner.
* Ideally, each log entry message should be a single line (i.e. no line breaks within the message string). Additional lines or extra data should be put in the context array.
* Avoid outputting structured data in the message string. Put it in a key in the context array instead. The logger will handle converting it to JSON and making it legible in the log viewer.
* If you need to include a stack trace, let the logger generate it for you.
@ -159,7 +159,7 @@ The `WC_Logger` class can be substituted for another class via the `woocommerce_
In WooCommerce, a log handler is a PHP class that takes the raw log data and transforms it into a log entry that can be stored or dispatched. WooCommerce ships with four different log handler classes:
* `Automattic\WooCommerce\Internal\Admin\Logging\LogHandlerFileV2`: This is the default handler, representing the "file system" log storage method. It records log entries to files.
* `Automattic\\WooCommerce\\Internal\\Admin\\Logging\\LogHandlerFileV2`: This is the default handler, representing the "file system" log storage method. It records log entries to files.
* `WC_Log_Handler_File`: This is the old default handler that also records log entries to files. It may be deprecated in the future, and it is not recommended to use this class or extend it.
* `WC_Log_Handler_DB`: This handler represents the "database" log storage method. It records log entries to the database.
* `WC_Log_Handler_Email`: This handler does not store log entries, but instead sends them as email messages. Emails are sent to the site admin email address. This handler has [some limitations](https://github.com/woocommerce/woocommerce/blob/fe81a4cf27601473ad5c394a4f0124c785aaa4e6/plugins/woocommerce/includes/log-handlers/class-wc-log-handler-email.php#L15-L27).
@ -185,6 +185,10 @@ add_filter( 'woocommerce_register_log_handlers', 'my_wc_log_handlers' );
You may want to create your own log handler class in order to send logs somewhere else, such as a Slack channel or perhaps an InfluxDB instance. Your class must extend the [`WC_Log_Handler`](https://woocommerce.github.io/code-reference/classes/WC-Log-Handler.html) abstract class and implement the [`WC_Log_Handler_Interface`](https://woocommerce.github.io/code-reference/classes/WC-Log-Handler-Interface.html) interface. The [`WC_Log_Handler_Email`](https://github.com/woocommerce/woocommerce/blob/6688c60fe47ad42d49deedab8be971288e4786c1/plugins/woocommerce/includes/log-handlers/class-wc-log-handler-email.php) handler class provides a good example of how to set this up.
### Log file storage location
When using the "file system" log handler, by default the log files are stored in the `wc-logs` subdirectory of the WordPress `uploads` directory, which means they might be publicly accessible. WooCommerce adds an `.htaccess` file to prevent access to `wc-logs`, but not all web servers recognize that file. If you have the option, you may want to consider storing your log files in a directory outside of the web root. Make sure the directory has the same user/group permissions as the `uploads` directory so that WordPress can access it. Then use the `woocommerce_log_directory` filter hook to set the path to your custom directory.
### Turning off noisy logs
If there is a particular log that is recurring frequently and clogging up your log files, you should probably figure out why it keeps getting triggered and resolve the issue. However, if that's not possible, you can add a callback to the `woocommerce_logger_log_message` filter hook to ignore that particular log while still allowing other logs to get through:

View File

@ -137,4 +137,4 @@ Now with synchronization fully disabled, test out various critical flows, check
3. [ ] Regularly communicate with stakeholders regarding testing progress and outcomes.
4. [ ] Plan for potential fallback scenarios, ensuring the ability to revert to posts if issues arise.
Did you follow this guide? Drop us a comment below to let us know how it went. Still have more questions? Reach to us on our dedicated HPOS upgrade channel in the Community Slack: [#hpos-upgrade-party](https://woocommercecommunity.slack.com/archives/C043X91E72M). If you are not yet a member of the Woo Slack Communtiy, you can join [here](https://woocommerce.com/community-slack/).
Did you follow this guide? Drop us a comment below to let us know how it went. Still have more questions? Reach to us on our dedicated HPOS upgrade channel in the Community Slack: [#hpos-upgrade-party](https://woocommercecommunity.slack.com/archives/C043X91E72M). If you are not yet a member of the Woo Slack Community, you can join [here](https://woocommerce.com/community-slack/).

View File

@ -0,0 +1,5 @@
---
category_title: Product Collection Block
category_slug: product-collection
post_title: Product collection block
---

View File

@ -0,0 +1,29 @@
---
post_title: DOM Events sent from product collection block
menu_title: DOM Events
tags: how-to
---
# Product Collection - DOM Events
## `wc-blocks_product_list_rendered`
This event is triggered when Product Collection block was rendered or re-rendered (e.g. due to page change).
### `detail` parameters
| Parameter | Type | Default value | Description |
| ------------------ | ------- | ------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `collection` | string | `undefined` | Collection type. It's `undefined` for "create your own" collections as the type is not specified. For other Core collections it can be one of type: `woocommerce/product-collection/best-sellers`, `woocommerce/product-collection/featured`, `woocommerce/product-collection/new-arrivals`, `woocommerce/product-collection/on-sale`, `woocommerce/product-collection/top-rated`. For custom collections it will hold their name. |
### Example usage
```javascript
window.document.addEventListener(
'wc-blocks_product_list_rendered',
( e ) => {
const { collection } = e.detail;
console.log( collection ) // -> collection name, e.g. woocommerce/product-collection/on-sale
}
);
```

View File

@ -0,0 +1,282 @@
---
post_title: Registering custom collections in product collection block
menu_title: Registering custom collections
tags: how-to
---
# Register Product Collection
The `__experimentalRegisterProductCollection` function is part of the `@woocommerce/blocks-registry` package. This function allows third party developers to register a new collection. This function accepts most of the arguments that are accepted by [Block Variation](https://developer.wordpress.org/block-editor/reference-guides/block-api/block-variations/#defining-a-block-variation).
> [!WARNING]
> It's experimental and may change in the future. Please use it with caution.
**There are two ways to use this function:**
1. Using `@woocommerce/dependency-extraction-webpack-plugin` in a Webpack configuration: This will allow you to import the function from the package & use it in your code. For example:
```tsx
import { __experimentalRegisterProductCollection } from "@woocommerce/blocks-registry";
```
2. Using the global `wc` object: This will allow you to use the function using the global JS object without importing it. For example:
```tsx
wc.wcBlocksRegistry.__experimentalRegisterProductCollection({
...
});
```
> [!TIP]
> The first method is recommended if you are using Webpack.
## Defining a Collection
We will explain important arguments that can be passed to `__experimentalRegisterProductCollection`. For other arguments, you can refer to the [Block Variation](https://developer.wordpress.org/block-editor/reference-guides/block-api/block-variations/#defining-a-block-variation) documentation.
A Collection is defined by an object that can contain the following fields:
- `name` (type `string`): A unique and machine-readable collection name. We recommend using the format `<plugin-name>/product-collection/<collection-name>`. Both `<plugin-name>` and `<collection-name>` should consist only of alphanumeric characters and hyphens (e.g., `my-plugin/product-collection/my-collection`).
- `title` (type `string`): The title of the collection, which will be displayed in various places including the block inserter and collection chooser.
- `description` (optional, type `string`): A human-readable description of the collection.
- `innerBlocks` (optional, type `Array[]`): An array of inner blocks that will be added to the collection. If not provided, the default inner blocks will be used.
- `isDefault`: It's set to `false` for all collections. Third party developers don't need to pass this argument.
- `isActive`: It will be managed by us. Third party developers don't need to pass this argument.
- `usesReference` (optional, type `Array[]`): An array of strings specifying the required reference for the collection. Acceptable values are `product`, `archive`, `cart`, and `order`. When the required reference isn't available on Editor side but will be available in Frontend, we will show a preview label.
### Attributes
Attributes are the properties that define the behavior of the collection. All the attributes are *optional*. Here are some of the important attributes that can be passed to `__experimentalRegisterProductCollection`:
- `query` (type `object`): The query object that defines the query for the collection. It can contain the following fields:
- `offset` (type `number`): The number of items to offset the query by.
- `order` (type `string`): The order of the query. Accepted values are `asc` and `desc`.
- `orderBy` (type `string`): The field to order the query by.
- `pages` (type `number`): The number of pages to query.
- `perPage` (type `number`): The number of products per page.
- `search` (type `string`): The search term to query by.
- `taxQuery` (type `object`): The tax query to filter the query by. For example, if you wanna fetch products with category `Clothing` & `Accessories` and tag `Summer` then you can pass `taxQuery` as `{"product_cat":[20,17],"product_tag":[36]}`. Where array values are the term IDs.
- `featured` (type `boolean`): Whether to query for featured items.
- `timeFrame` (type `object`): The time frame to query by.
- `operator` (type `string`): The operator to use for the time frame query. Accepted values are `in` and `not-in`.
- `value` (type `string`): The value to query by. It should be a valid date string that PHP's `strtotime` function can parse.
- `woocommerceOnSale` (type `boolean`): Whether to query for items on sale.
- `woocommerceStockStatus` (type `array`): The stock status to query by. Some of the accepted values are `instock`, `outofstock`, `onbackorder`.
- `woocommerceAttributes` (type `array`): The attributes to query by.
- For example, if you wanna fetch products with color `blue` & `gray` and size `Large` then you can pass `woocommerceAttributes` as `[{"termId":23,"taxonomy":"pa_color"},{"termId":26,"taxonomy":"pa_size"},{"termId":29,"taxonomy":"pa_color"}]`.
- `woocommerceHandPickedProducts` (type `array`): The hand-picked products to query by. It should contain the product IDs.
- `priceRange` (type `object`): The price range to query by.
- `min` (type `number`): The minimum price.
- `max` (type `number`): The maximum price.
- `displayLayout` (type `object`): The display layout object that defines the layout of the collection. It can contain the following fields:
- `type` (type `string`): The type of layout. Accepted values are `grid` and `stack`.
- `columns` (type `number`): The number of columns to display.
- `shrinkColumns` (type `boolean`): Whether the layout should be responsive.
- `hideControls` (type `array`): The controls to hide. Possible values:
- `order` - "Order by" setting
- `attributes` - "Product Attributes" filter
- `created` - "Created" filter
- `featured` - "Featured" filter
- `hand-picked` - "Hand-picked Products" filter
- `keyword` - "Keyword" filter
- `on-sale` - "On Sale" filter
- `stock-status` - "Stock Status" filter
- `taxonomy` - "Product Categories", "Product Tags" and custom taxonomies filters
- `price-range` - "Price Range" filter
#### Preview Attribute
The `preview` attribute is optional, and it is used to set the preview state of the collection. It can contain the following fields:
- `initialPreviewState` (type `object`): The initial preview state of the collection. It can contain the following fields:
- `isPreview` (type `boolean`): Whether the collection is in preview mode.
- `previewMessage` (type `string`): The message to be displayed in the Tooltip when the user hovers over the preview label.
- `setPreviewState` (optional, type `function`): The function to set the preview state of the collection. It receives the following arguments:
- `setState` (type `function`): The function to set the preview state. You can pass a new preview state to this function containing `isPreview` and `previewMessage`.
- `attributes` (type `object`): The current attributes of the collection.
- `location` (type `object`): The location of the collection. Accepted values are `product`, `archive`, `cart`, `order`, `site`.
For more info, you may check [PR #46369](https://github.com/woocommerce/woocommerce/pull/46369), in which the Preview feature was added
## Examples
### Example 1: Registering a new collection
```tsx
__experimentalRegisterProductCollection({
name: "your-plugin-name/product-collection/my-custom-collection",
title: "My Custom Collection",
icon: "games",
description: "This is a custom collection.",
keywords: ["custom collection", "product collection"],
});
```
As you can see in the example above, we are registering a new collection with the name `woocommerce/product-collection/my-custom-collection` & title `My Custom Collection`. Here is screenshot of how it will look like:
![image](https://github.com/woocommerce/woocommerce/assets/16707866/7fddbc02-a6cd-494e-b2f4-13dd5ef9cf96)
### Example 2: Register a new collection with a preview
As you can see below, setting the initial preview state is possible. In the example below, we are setting `isPreview` and `previewMessage`.
```tsx
__experimentalRegisterProductCollection({
name: "your-plugin-name/product-collection/my-custom-collection-with-preview",
title: "My Custom Collection with Preview",
icon: "games",
description: "This is a custom collection with preview.",
keywords: ["My Custom Collection with Preview", "product collection"],
preview: {
initialPreviewState: {
isPreview: true,
previewMessage:
"This is a preview message for my custom collection with preview.",
},
},
attributes: {
query: {
perPage: 5,
featured: true,
},
displayLayout: {
type: "grid",
columns: 3,
shrinkColumns: true,
},
hideControls: [ "created", "stock-status" ]
},
});
```
Here is how it will look like:
![image](https://github.com/woocommerce/woocommerce/assets/16707866/5fc1aa20-552a-4e09-b811-08babab46665)
### Example 3: Advanced usage of preview
As you can see below, it's also possible to use `setPreviewState` to set the preview state. In the example below, we are setting `initialPreviewState` and using `setPreviewState` to change the preview state after 5 seconds.
**This example shows:**
- How to access current attributes and location in the preview state
- How to use async operations
- We are using `setTimeout` to change the preview state after 5 seconds. You can use any async operation, like fetching data from an API, to decide the preview state.
- How to use the cleanup function as a return value
- We are returning a cleanup function that will clear the timeout after the component is unmounted. You can use this to clean up any resources you have used in `setPreviewState`.
```tsx
__experimentalRegisterProductCollection({
name: "your-plugin-name/product-collection/my-custom-collection-with-advanced-preview",
title: "My Custom Collection with Advanced Preview",
icon: "games",
description: "This is a custom collection with advanced preview.",
keywords: [
"My Custom Collection with Advanced Preview",
"product collection",
],
preview: {
setPreviewState: ({
setState,
attributes: currentAttributes,
location,
}) => {
// setPreviewState has access to the current attributes and location.
// console.log( currentAttributes, location );
const timeoutID = setTimeout(() => {
setState({
isPreview: false,
previewMessage: "",
});
}, 5000);
return () => clearTimeout(timeoutID);
},
initialPreviewState: {
isPreview: true,
previewMessage:
"This is a preview message for my custom collection with advanced preview.",
},
},
});
```
### Example 4: Collection with inner blocks
As you can see below, it's also possible to define inner blocks for the collection. In the example below, we are defining inner blocks for the collection.
```tsx
__experimentalRegisterProductCollection({
name: "your-plugin-name/product-collection/my-custom-collection-with-inner-blocks",
title: "My Custom Collection with Inner Blocks",
icon: "games",
description: "This is a custom collection with inner blocks.",
keywords: ["My Custom Collection with Inner Blocks", "product collection"],
innerBlocks: [
[
"core/heading",
{
textAlign: "center",
level: 2,
content: "Title of the collection",
},
],
[
"woocommerce/product-template",
{},
[
["woocommerce/product-image"],
[
"woocommerce/product-price",
{
textAlign: "center",
fontSize: "small",
},
],
],
],
],
});
```
This will create a collection with a heading, product image, and product price. Here is how it will look like:
![image](https://github.com/woocommerce/woocommerce/assets/16707866/3d92c084-91e9-4872-a898-080b4b93afca)
> [!TIP]
> You can learn more about inner blocks template in the [Inner Blocks](https://developer.wordpress.org/block-editor/how-to-guides/block-tutorial/nested-blocks-inner-blocks/#template) documentation.
### Example 5: Collection with `usesReference` argument
When a collection requires a reference to work properly, you can specify it using the `usesReference` argument. In the example below, we are defining a collection that requires a `product` reference.
```tsx
__experimentalRegisterProductCollection({
name: "your-plugin-name/product-collection/my-custom-collection",
title: "My Custom Collection",
icon: "games",
description: "This is a custom collection.",
keywords: ["custom collection", "product collection"],
usesReference: ["product"],
});
```
This will create a collection that requires a `product` reference. If the required reference isn't available on the Editor side but will be available in the Frontend, we will show a preview label.
When a collection need one of the multiple references, you can specify it using the `usesReference` argument. In the example below, we are defining a collection that requires either a `product` or `order` reference.
```tsx
__experimentalRegisterProductCollection({
name: "your-plugin-name/product-collection/my-custom-collection",
title: "My Custom Collection",
icon: "games",
description: "This is a custom collection.",
keywords: ["custom collection", "product collection"],
usesReference: ["product", "order"],
});
```
---
> [!TIP]
> You can also take a look at how we are defining our core collections at `plugins/woocommerce-blocks/assets/js/blocks/product-collection/collections` directory. Our core collections will also evolve over time.

View File

@ -6,4 +6,4 @@ post_title: Product Editor
Discover how to customize the WooCommerce product editor, from extending product data to adding unique functionalities.
This handbook is a guide for extension developers looking to add support for the new product editor in their extensions. The product editor uses [Gutenberg's Block Editor](https://github.com/WordPress/gutenberg/tree/trunk/packages/block-editor), which is going to help WooCommerce evolve alongside the WordPress ecosystem.
This handbook is a guide for extension developers looking to add support for the new product editor in their extensions. The product editor uses [Gutenberg's Block Editor](https://github.com/WordPress/gutenberg/tree/trunk/packages/block-editor), which is going to help WooCommerce evolve alongside the WordPress ecosystem.

View File

@ -0,0 +1,14 @@
# How-to Guides for the Product form
There are several ways to extend and modify the new product form. Below are links to different tutorials.
## Generic fields
One way to extend the new product form is by making use of generic fields. This allows you to easily modify the form using PHP only. We have a wide variety of generic fields that you can use, like a text, checkbox, pricing or a select field. You can find the full list [here](https://github.com/woocommerce/woocommerce/blob/trunk/packages/js/product-editor/src/blocks/generic/README.md).
To see how you can make use of these fields you can follow the [generic fields tutorial](https://github.com/woocommerce/woocommerce/blob/trunk/docs/product-editor-development/how-to-guides/generic-fields-tutorial.md).
## Writing a custom field
It is also possible to write your own custom field and render those within the product form. This is helpful if the generic fields don't quite fit your use case.
To see an example of how to create a basic dropdown field in the product form you can follow [this tutorial](https://github.com/woocommerce/woocommerce/blob/trunk/docs/product-editor-development/how-to-guides/custom-field-tutorial.md).

View File

@ -0,0 +1,263 @@
# Extending the product form with custom fields
Aside from extending the product form using generic fields it is also possible to use custom fields. This does require knowledge of JavaScript and React.
If you are already familiar with writing blocks for the WordPress site editor this will feel very similar.
## Getting started
To get started we would recommend reading through the [fundamentals of block development docs](https://developer.wordpress.org/block-editor/getting-started/fundamentals/) in WordPress. This gives a good overview of working with blocks, the block structure, and the [JavaScript build process](https://developer.wordpress.org/block-editor/getting-started/fundamentals/javascript-in-the-block-editor/).
This tutorial will use vanilla JavaScript to render a new field in the product form for those that already have a plugin and may not have a JavaScript build process set up yet.
If you want to create a plugin from scratch with the necessary build tools, we recommend using the `@wordpress/create-block` script. We also have a specific template for the product form: [README](https://github.com/woocommerce/woocommerce/blob/trunk/packages/js/create-product-editor-block/README.md).
## Creating a custom field
### Adding and registering our custom field
Adding and registering our custom field is very similar as creating a brand new block.
Inside a new folder within your plugin, let's create a `block.json` file with the contents below. The only main difference between this `block.json` and a `block.json` for the site editor is that we will set `supports.inserter` to false, so it doesn't show up there. We will also be registering this slightly different.
```json
{
"$schema": "https://schemas.wp.org/trunk/block.json",
"apiVersion": 3,
"name": "tutorial/new-product-form-field",
"title": "Product form field",
"category": "woocommerce",
"description": "A sample field for the product form",
"keywords": [ "products" ],
"attributes": {},
"supports": {
"html": false,
"multiple": true,
// Setting inserter to false is important so that it doesn't show in the site editor.
"inserter": false
},
"textdomain": "woocommerce",
"editorScript": "file:./index.js"
}
```
In the same directory, create a `index.js` file, which we can keep simple by just outputting a hello world.
In this case the `edit` function is the part that will get rendered in the form. We are wrapping it with the `createElement` function to keep support for React.
```javascript
( function ( wp ) {
var el = wp.element.createElement;
wp.blocks.registerBlockType( 'tutorial/new-product-form-field', {
title: 'Product form field',
attributes: {},
edit: function () {
return el( 'p', {}, 'Hello World (from the editor).' );
},
} );
} )( window.wp );
```
In React:
```jsx
import { registerBlockType } from '@wordpress/blocks';
function Edit() {
return <p>Hello World (from the editor).</p>;
}
registerBlockType( 'tutorial/new-product-form-field', {
title: 'Product form field',
attributes: {},
edit: Edit,
} );
```
Lastly, in order to make this work the block registration needs to know about the JavaScript dependencies, we can do so by adding a `index.asset.php` file with the below contents:
```php
<?php return array('dependencies' => array('react', 'wc-product-editor', 'wp-blocks' ) );
```
Now that we have all the for the field we need to register it and add it to the template.
Registering can be done on `init` by calling `BlockRegistry::get_instance()->register_block_type_from_metadata` like so:
```php
use Automattic\WooCommerce\Admin\Features\ProductBlockEditor\BlockRegistry;
function example_custom_product_form_init() {
if ( isset( $_GET['page'] ) && $_GET['page'] === 'wc-admin' ) {
// This points to the directory that contains your block.json.
BlockRegistry::get_instance()->register_block_type_from_metadata( __DIR__ . '/js/sample-block' );
}
}
add_action( 'init', 'example_custom_product_form_init' );
```
We can add it to the product form by hooking into the `woocommerce_layout_template_after_instantiation` action ( see [block addition and removal](https://github.com/woocommerce/woocommerce/blob/trunk/docs/product-editor-development/block-template-lifecycle.md#block-addition-and-removal) ).
What we did was the following ( see [here](https://github.com/woocommerce/woocommerce/blob/trunk/plugins/woocommerce/src/Admin/Features/ProductBlockEditor/ProductTemplates/README.md#usage) for more related functions ):
- Get a group by the `general` id, this is the General tab.
- Create a new section on the general tab called `Tutorial Section`
- Add our custom field to the `Tutorial Section`
```php
add_action(
'woocommerce_layout_template_after_instantiation',
function( $layout_template_id, $layout_template_area, $layout_template ) {
$general = $layout_template->get_group_by_id( 'general' );
if ( $general ) {
// Creating a new section, this is optional.
$tutorial_section = $general->add_section(
array(
'id' => 'tutorial-section',
'order' => 15,
'attributes' => array(
'title' => __( 'Tutorial Section', 'woocommerce' ),
'description' => __( 'Fields related to the tutorial', 'woocommerce' ),
),
)
);
$tutorial_section->add_block(
[
'id' => 'example-new-product-form-field',
'blockName' => 'tutorial/new-product-form-field',
'attributes' => [],
]
);
}
},
10,
3
);
```
### Turn field into a dropdown
We recommend using components from `@wordpress/components` as this will also keep the styling consistent. We will use the [ComboboxControl](https://wordpress.github.io/gutenberg/?path=/docs/components-comboboxcontrol--docs) core component in this field.
We can add it to our `edit` function pretty easily by making use of `wp.components`. We will also add a constant for the filter options.
**Note:** I also added the `blockProps` to the top element, we still recommend using this as some of these props are being used in the product form. When we add the block props we need to also let the form know it is an interactive element. We do this by adding at-least one attribute with the `__experimentalRole` set to `content`.
So lets add this to our `index.js` attributes:
```javascript
attributes: {
"message": {
"type": "string",
"__experimentalRole": "content",
"source": "text",
"selector": "div"
}
},
```
Dropdown options, these can live outside of the `edit` function:
```javascript
const DROPDOWN_OPTIONS = [
{
value: 'small',
label: 'Small',
},
{
value: 'normal',
label: 'Normal',
},
{
value: 'large',
label: 'Large',
},
];
```
The updated `edit` function:
```javascript
// edit function.
function ( { attributes } ) {
// useState is a React specific function.
const [ value, setValue ] = wp.element.useState();
const [ filteredOptions, setFilteredOptions ] = wp.element.useState( DROPDOWN_OPTIONS );
const blockProps = window.wc.blockTemplates.useWooBlockProps( attributes );
return el( 'div', { ...blockProps }, [
el( wp.components.ComboboxControl, {
label: "Example dropdown",
value: value,
onChange: setValue,
options: filteredOptions,
onFilterValueChange: function( inputValue ) {
setFilteredOptions(
DROPDOWN_OPTIONS.filter( ( option ) =>
option.label
.toLowerCase()
.startsWith( inputValue.toLowerCase() )
)
)
}
} )
] );
},
```
In React:
```jsx
import { createElement, useState } from '@wordpress/element';
import { ComboboxControl } from '@wordpress/components';
import { useWooBlockProps } from '@woocommerce/block-templates';
function Edit( { attributes } ) {
const [ value, setValue ] = useState();
const [ filteredOptions, setFilteredOptions ] =
useState( DROPDOWN_OPTIONS );
const blockProps = useWooBlockProps( attributes );
return (
<div { ...blockProps }>
<ComboboxControl
label="Example dropdown"
value={ value }
onChange={ setValue }
options={ filteredOptions }
onFilterValueChange={ ( inputValue ) =>
setFilteredOptions(
DROPDOWN_OPTIONS.filter( ( option ) =>
option.label
.toLowerCase()
.startsWith( inputValue.toLowerCase() )
)
)
}
/>
</div>
);
}
```
### Save field data to the product data
We can make use of the `__experimentalUseProductEntityProp` for saving the field input to the product.
The function does rely on `postType`, we can hardcode this to `product`, but the `postType` is also exposed through a context. We can do so by adding `"usesContext": [ "postType" ],` to the `block.json` and getting it from the `context` passed into the `edit` function props.
So the top part of the edit function will look like this, where we also replace the `value, setValue` `useState` line:
```javascript
// edit function.
function ( { attributes, context } ) {
const [ value, setValue ] = window.wc.productEditor.__experimentalUseProductEntityProp(
'meta_data.animal_type',
{
postType: context.postType,
fallbackValue: '',
}
);
// .... Rest of edit function
```
Now if you select small, medium, or large from the dropdown and save your product, the value should persist correctly.
Note, the above function supports the use of `meta_data` by dot notation, but you can also target other fields like `regular_price` or `summary`.

View File

@ -0,0 +1,58 @@
# Extending the product form with generic fields
We have large list of generic fields that a plugin can use to extend the new product form. You can find the full list [here](https://github.com/woocommerce/woocommerce/blob/trunk/packages/js/product-editor/src/blocks/generic/README.md). Each field contains documentation for what attributes the field supports.
## Using a generic block
Using a generic block is pretty easy. We have created an template API that allows you to add new fields, the API refers to them as `blocks`. There are a couple actions that allow us to interact with these templates. There is the `woocommerce_layout_template_after_instantiation` that is triggered when a new template is registered. There are also other actions triggered when a specific field/block is added ( see [block addition and removal](https://github.com/woocommerce/woocommerce/blob/trunk/docs/product-editor-development/block-template-lifecycle.md#block-addition-and-removal) ).
Let's say we want to add something to the basic details section, we can do so by making use of the above mentioned hook:
This will add a number field called **Animal age** to each template that has a `basic-details` section.
```php
add_action(
'woocommerce_layout_template_after_instantiation',
function( $layout_template_id, $layout_template_area, $layout_template ) {
$basic_details = $layout_template->get_section_by_id( 'basic-details' );
if ( $basic_details ) {
$basic_details->add_block(
[
'id' => 'example-tutorial-animal-age',
// This orders the field, core fields are separated by sums of 10.
'order' => 40,
'blockName' => 'woocommerce/product-number-field',
'attributes' => [
// Attributes specific for the product-number-field.
'label' => 'Animal age',
'property' => 'meta_data.animal_age',
'suffix' => 'Yrs',
'placeholder' => 'Age of animal',
'required' => true,
'min' => 1,
'max' => 20
],
]
);
}
},
10,
3
);
```
### Dynamically hiding or showing the generic field
It is also possible to dynamically hide or show your field if data on the product form changes.
We can do this by adding a `hideCondition` ( plural ). For example if we wanted to hide our field if the product price is higher than 20, we can do so by adding this expression:
```php
'hideConditions' => array(
array(
'expression' => 'editedProduct.regular_price >= 20',
),
),
```
The `hideConditions` also support targeting meta data by using dot notation. You can do so by writing an expression like this: `! editedProduct.meta_data.animal_type` that will hide a field if the `animal_type` meta data value doesn't exist.

View File

@ -37,5 +37,7 @@ Please note that this check is currently not being enforced: the product editor
## Related documentation
- [Examples on Template API usage](https://github.com/woocommerce/woocommerce/blob/trunk/plugins/woocommerce/src/Admin/Features/ProductBlockEditor/ProductTemplates/README.md/)
- [How to guides](https://github.com/woocommerce/woocommerce/blob/trunk/docs/product-editor-development/how-to-guides/README.md)
- [Related hooks and Template API documentation](https://github.com/woocommerce/woocommerce/blob/trunk/plugins/woocommerce/src/Admin/BlockTemplates/README.md)
- [Generic blocks documentation](https://github.com/woocommerce/woocommerce/blob/trunk/packages/js/product-editor/src/blocks/generic/README.md)
- [Validations and error handling](https://github.com/woocommerce/woocommerce/blob/trunk/packages/js/product-editor/src/contexts/validation-context/README.md)

View File

@ -4,4 +4,4 @@ category_slug: quality-and-best-practices
post_title: Quality and best practices
---
Ensuring the quality of your WooCommerce projects is essential. This section will delve into quality exoectations, best practices, coding standards, and other methodologies to ensure your projects stand out in terms of reliability, efficiency, user experience, and more.
Ensuring the quality of your WooCommerce projects is essential. This section will delve into quality expectations, best practices, coding standards, and other methodologies to ensure your projects stand out in terms of reliability, efficiency, user experience, and more.

View File

@ -56,7 +56,7 @@ These flows will continually evolve as the platform evolves with flows updated,
| Shopper | Product | Variable Product info updates depending on variation | shopper/product-variable.spec.js |
| Shopper | Product | Add Variable Product to Cart | shopper/product-variable.spec.js |
| Shopper | Product | Display up-sell product | products/product-linked-products.spec.js |
| Shopper | Product | Display releated products | products/product-linked-products.spec.js |
| Shopper | Product | Display related products | products/product-linked-products.spec.js |
| Shopper | Product | Display reviews | merchant/product-reviews.spec.js |
| Shopper | Product | Add review | merchant/product-reviews.spec.js |
| Shopper | Product | View product images | shopper/product-simple.spec.js |
@ -74,7 +74,7 @@ These flows will continually evolve as the platform evolves with flows updated,
| Shopper | Cart | Display shipping options by address | shopper/calculate-shipping.spec.js |
| Shopper | Cart | View empty cart | shopper/cart.spec.js |
| Shopper | Cart | Display correct tax | shopper/cart-checkout-calculate-tax.spec.js |
| Shopper | Cart | Respect coupon usage contraints | shopper/cart-checkout-coupons.spec.js |
| Shopper | Cart | Respect coupon usage constraints | shopper/cart-checkout-coupons.spec.js |
| Shopper | Cart | Display cross-sell products | products/product-linked-products.spec.js |
| Shopper | Cart | Proceed to checkout | shopper/checkout.spec.js |
@ -92,7 +92,7 @@ These flows will continually evolve as the platform evolves with flows updated,
| Shopper | Checkout | View checkout | shopper/checkout.spec.js |
| Shopper | Checkout | Receive warnings when form is incomplete | shopper/checkout.spec.js |
| Shopper | Checkout | Add billing address | shopper/checkout.spec.js |
| Shopper | Checkout | Respect coupon usage contraints | shopper/cart-checkout-coupons.spec.js |
| Shopper | Checkout | Respect coupon usage constraints | shopper/cart-checkout-coupons.spec.js |
| Shopper | Checkout | Display correct tax in checkout | shopper/cart-checkout-calculate-tax.spec.js |
| Shopper | Checkout | View order confirmation page | shopper/checkout.spec.js |

View File

@ -0,0 +1,19 @@
---
category_title: Review Guidelines
category_slug: review-guidelines
post_title: Review Guidelines
---
Reviews are an integral part of the online shopping experience, and people installing software pay attention to them. Prospective users of your extensions will likely consider average ratings when making software choices.
Many of today's most popular online review platforms - from Yelp business reviews, to Amazon product reviews - have a range of opinion that can be polarized, with many extremely positive and/or negative reviews, and fewer moderate opinions. This creates a "J-shaped" distribution of reviews that isn't as accurate or as helpful as could be.
WooCommerce.com and WordPress.org both feature reviews heavily, and competing extensions having a higher rating likely have the edge in user choice.
## Primary considerations around reviews
Requesting more reviews for a extension with major issues will not generate good reviews, and analyzing existing reviews will help surface areas to address before soliciting reviews.
It is extremely rare for users of WordPress plugins to leave reviews organically (.2% of users for WordPress.org leave reviews), which means that there's an untapped market of 99.8% of users of the average plugin.
These plugins are competing with other plugins on the same search terms in the WordPress.org plugin directory, and ratings are a large factor in the ranking algorithm. This is not usually a factor to the same extent on the WooCommerce Marketplace. For instance, WooCommerce's PayPal extension directly competes on all possible keywords with other PayPal extensions on the WordPress.org repository, while it does not compete with other PayPal payments extensions on the Marketplace.

View File

@ -0,0 +1,39 @@
---
post_title: How to request WooCommerce extension reviews
menu_title: Requesting reviews
---
## Methods of requesting reviews
### Admin notices
Admin notices are an industry standard method of requesting reviews, but bombarding the admin dashboard with admin notices is not effective. We recommend using restraint in the design of a notice, as well as limiting to a single notice at a time. It's very easy to overwhelm merchants with too many notices, or too intrusive notices.
#### Recommendations
* A good place for an admin notice to review an extension would be to show on the `Plugins` page and extension's settings pages.
* Include a snooze option (or multiple) on your notices with a clear expectation of when the notice will reappear.
* Admin notices should always be always be completely dismissable. They cannot only have a snooze option.
* The options presented in the notice must be phrased carefully to avoid manipulative language.
* Use consistently designed notices so the request for reviews feels like a part of your extension, and looks consistent with WooCommerce's design.
### Direct contact
#### Recommendations
* The most direct route to requesting reviews with the highest chance of being positive is to contact the customer when they are the happiest with the product.
* This can be milestone or time based, following the timing guidelines below.
* The best method for this is either an email or other direct exchange (support chat, call, etc.). This has the highest conversion rate, especially when timed properly so that the customer is happiest.
* This is also extremely effective when you are able to request feedback from specifically qualified merchants, such as merchants that have processed a certain amount with your platform, or who have shipped their first 100 orders using your fulfillment extension, or similar.
* Direct outreach is most likely to be successful if you have ways of targeting users for review requests (merchant account / usage info, etc.), as well as ways to gather the reviews, like sales or marketing teams able to email/call/chat with merchants.
## Messaging for requesting reviews
One method of requesting feedback that we recommend is using the NPS style of review solicitation. This can allow for an increase positive reviews as well as providing the opportunity to assist merchants that are struggling.
NPS-style reviews first ask the user how they rate the product (out of 5 stars), then route them based on their response:
* If they click 4 or 5 stars, ask them to leave a review.
* If they click 1, 2 or 3, tell them we're here to help & ask them to submit a support ticket.
Merchants are significantly more likely to leave a review after a positive support interaction with a support rep who explicitly asked for a review. The language "the best way to thank me is to leave a 5 star review that mentions me in it" or similar tends to work very well - people are more willing to help a person than a produc or company.

View File

@ -0,0 +1,14 @@
---
post_title: Miscellaneous guidelines and advice
menu_title: Miscellaneous guidelines
---
Contributors' names matching search terms directly will rank extremely highly on the WordPress.org plugin repo, which means that having a WordPress.org user named after your business (if that's a search term for your plugin) could tilt the scales over a competing plugin.
Constant nags and overwhelming the admin dashboard with unnecessary alerts detract from your user experience.
You can request to have reviews that are not actually feedback removed. Where this might be applicable is if the request is a simple support request, where it's obviously in the wrong spot. 1 star reviews, even if aggressive or angry, are not usually removed.
Reply to reviews! Thank the giver for offering feedback, acknowledge the issue if needed, ask for more specific feedback, or provide an update when that feedback is addressed! Your reviews are a great window into what your extension's users are actually thinking.
Having folks close to the extension's development (think developers and project managers) looking at reviews on a regular basis is a good way to ensure the customers voice is heard. 1 star reviews are among the most useful, as long as the issue is understood and addressed (if needed).

View File

@ -0,0 +1,18 @@
---
post_title: Notifying users about bug fixes and feature requests
menu_title: Notifying users about bug fixes and feature requests
---
A bug or a missing feature can be a showstopper for merchants. Bugs that pile up or popular features that are not implemented can lead to negative reviews and/or merchants churning and looking at a competitive solution.
Bugs are usually reported via support or GitHub, or you can discover them yourselves in testing.
When a critical bug is found, resolve it within a couple of days (most critical bugs should be resolved within 24 hours) and release a new plugin version promptly. Part of your release process should be to notify all stakeholders (the support team and the merchant affected) about the upcoming release.
Even though a critical bug is a great source of stress for merchants, a quick resolution makes merchants feel heard and supported - having a reliable business partner, who is keen to help in the most difficult situation, helps build a stronger relationship. Therefore, we usually ask merchants for a 5* review when we deliver a fast solution.
When you implement a new feature request and ship a new plugin version, you can follow a similar approach to bugs:
* Notify all stakeholders.
* Update the relevant request in the Feature Requests board, by sharing a public update and marking it as 'Completed'.
* For breaking releases: communicating with your marketing/relations teams to publish updates/newsletters before the release.

View File

@ -0,0 +1,33 @@
---
post_title: How to respond to negative WooCommerce extension reviews
menu_title: Responding to negative reviews
---
An unpleasant event in the merchant's journey can lead them to leave a public, negative review. These events usually are:
* a problem with the product,
* a missing product feature,
* an unhelpful reply,
* long wait times to receive a reply, or;
* combinations of the above.
When receiving a negative review, your goal should always be to turn this review around - this sounds tough, but it is really rewarding.
In the majority of cases, merchants who leave a negative review have first tried contacting support for help. This is useful knowledge, as we can read through the conversation history, understand the issue the merchant experienced and share more details with them when we reach out, even from our first reply.
The process we have seen work well is:
* Create a new response (via email, or on a public review) with subject: Regarding your recent review for xxx.
* Start by introducing yourself, for example: "Hey there, This is Andrew from the team that develops xxx".
* Use empathetic language and make it clear that this negative review had an impact on you. For example, "I read your recent review for xxx and I am worried to hear that an issue is preventing you from using this plugin as you had in mind. I'd be happy to help you resolve this!".
Compare the above sentence with: "I am sorry to hear that you experienced an issue with xxx". "I am sorry to" indicates that you are saddened by an event, but don't necessarily plan to do something about it. In comparison, in "I am worried to hear", worry indicates action. Additionally, "That you experienced an issue" can be interpreted as if the problem is mainly the merchant's fault, whereas language like "an issue is preventing you from using this plugin as you had in mind. I'd be happy to help you resolve this!" implies you and the merchant are on the same team.
* Share more details, a solution, an idea, a suggestion or an explanation.
* Urge the merchant to update the review, by highlighting how important reviews are for our team and for other merchants. Example language to do this is "We would appreciate it if you could take a couple of minutes to update your review and describe your experience with our product and support. Honest reviews are extremely helpful for other merchants who try to decide if a plugin is a right fit for them. Thank you for your contribution!".
* Include a direct link to the reviews section, so merchants can easily navigate there and change their review.
* On a follow-up communication, if the merchant has changed the review, consider saying something like: "I shared this with the rest of the team and it made everyone's day".
If the above things are true, sharing some of your procedures with merchants (highlighting how your team emphasizes and thrives on feedback) helps ensure merchants feel like you are part of their team and builds a strong relationship with them.
Even a merchant that doesn't change their review can offer a mutually beneficial discussion by learning more about their setup and offering some suggestions. These conversations help grow merchants' trust.

View File

@ -0,0 +1,31 @@
---
post_title: Utilizing WooCommerce extension feature requests
menu_title: Utilizing feature requests
---
It is important to keep track of all feature requests, and have some sort of system of record where anyone can see what kind of feedback the product is receiving over time.
We recommend a daily or bi-daily check-in, where you:
* triage new feature requests,
* celebrate positive reviews and;
* act upon negative reviews.
Carefully maintaining feature request boards (or similar system) is key, as the average board contains a lot of duplicate/spam content, requests about features that have been implemented and requests about features that will likely never be implemented. Poorly maintained boards make merchants feel unheard/neglected.
This results in more negative reviews on the premise that the product teams were not reading/listening to their feedback.
We've seen good results with the following procedures:
Starting with the most affected products, go through all open requests, reply to most/all of them and categorize them as:
* "Open", for requests that we still want more feedback,
* "Planned", for requests that we plan to implement,
* "Completed", for requests that have already been implemented and;
* "Closed", for requests that we do not plan to implement, as they are not a good fit for the product, for duplicate/spam requests and for requests that were actually support questions.
Replying to all "Open" requests is the goal, but if that's not attainable currently, make sure to reply to 100% of the requests that are closed.
For new open requests that arrive as a feature request, discuss/triage them, reply promptly, and assign a status to avoid having the board become unmanaged, and ensure merchants feel (and are) heard.
In addition to the effect a tidy board has on merchants, it also helps product teams better understand which requests are most wanted and most impactful and then plan work accordingly.

View File

@ -0,0 +1,18 @@
---
post_title: Utilizing your support team to respond to feedback
menu_title: Utilizing your support team
---
Your support team is usually the primary contact point of merchants when they contact you. Tickets and chats are the best tools we have to converse with merchants, understand pain-points about our software, listen to their feedback and analyze their feature requests. Collectively, support teams have a great understanding of the products and how people use them. This information is essential to be transferred over to product and engineering teams.
We recommend that you take the following steps to best utilize your support team:
* Create a strict internal SLA where support team requests are answered by product or engineering teams.
* Ensure you have a way for your support team to effectively report bugs to your product and engineering teams.
* When responding to your support team, avoid super-short answers, and try to explain the answer simply and concisely. This will allow the support agent to copy/paste your answer to the merchant.
* Avoid replying with statements like "no, this is not possible" or "no, this feature will not be implemented" without providing additional context about technical or product limitations.
* Regularly dedicate additional time to implement a short custom code snippets or to provide in-depth technical details about how a custom project would be implemented so that merchants can reach a solution faster if they decide to hire a dedicated WooCommerce developer. A small effort can go a long way to amaze merchants and reveal an opportunity to request a 5 star review.
* Keep support in the loop when they report a bug or request a new feature. When you release a new product version, we always consider the impact it can have on support.
* Work closely with your support team. For example, consider having a feedback hangout call every month where you can discuss product feedback and planned improvements.
With these kinds of practices in place, support teams are more willing to share feedback, issues, concerns, and questions with us. This helps maintain a closer relationship with merchants and identify pain-points early, before they become a reason for them to churn.

View File

@ -0,0 +1,24 @@
---
post_title: When to request WooCommerce extension reviews
menu_title: When to request reviews
---
The best approach to increasing our top-star reviews is to identify key moments in the merchant's journey, when they are more likely to leave a review and actively request for it.
The most distinct moments for most of our use cases are:
* When merchants feel helpless, lost, frustrated and we are able to help,
* When merchants find a bug in our code and we quickly ship a fix,
* When merchants need a feature and we notify them when it is shipped,
* When merchants feel alone and we make them feel heard and;
* When merchants contact with a question and we go out of our way to provide them with top-notch support, even if this means slightly stepping outside the official boundaries of a support policy.
Think about who is seeing the review request, and what they are doing at that time. Showing a request to a fulfillment worker just trying to ship an order isn't likely going to work well.
Outreach after a milestone works really well. Some language we've used before is "Congratulations on your xxth sale! We're delighted that WooPayments facilitated this milestone. Would you consider sharing your experience and encouraging others by reviewing our extension?".
Another way to optimally time a review request would be to setup a prompt that aligns with use patterns. For instance, if you know that most of your merchants use your extension daily, you would likely send a review request sooner than a extension that most merchants interact very sparingly with.
SaaS/Connector extensions need to be particularly careful about requesting ratings correctly, as they are the most likely to be overlooked unless there is an issue, leading to skewed ratings not representative of the actual extension.
Consider requesting feedback at the end of every single support interaction, especially in the WordPress.org support forums. One of the largest barriers to leaving a review is the requirement of a user being logged into WooCommerce.com (or WordPress.org), and the WordPress.org support forums present a good opportunity to gather these reviews. By being highly responsive in the public support forum and solving issues there, users are already logged in and able to immediately leave a review (after being requested to!).

View File

@ -23,7 +23,7 @@ cd woocommerce-admin
npm run build
```
Once thats working, we can setup the extension folder ready for JavaScript development.
Once that's working, we can setup the extension folder ready for JavaScript development.
```sh
npm run create-wc-extension

View File

@ -49,7 +49,7 @@ Insomnia is almost identical to Postman; fill in the same fields and again use b
![Insomnia](https://developer.woocommerce.com/wp-content/uploads/2023/12/insomnia.png)
Thats it! The API is working.
That's it! The API is working.
If you have problems connecting, you may need to disable SSL verification - see the connection issues section below.

View File

@ -1,9 +1,9 @@
---
category_title: Theme Development
category_title: Classic Theme Development
category_slug: theme-development
post_title: Theme Development
post_title: Classic theme development
---
Learn to design and integrate custom themes in WooCommerce, focusing on responsive design and ecommerce optimization.
This document was created for use when developing classic themes. Check this other document for [block theme development](../../plugins/woocommerce-blocks/docs/designers/theming/README.md).
For blocks themes, see our [block theme documentation](/docs/category/block-theme-development).

View File

@ -4,120 +4,148 @@ post_title: Template structure & Overriding templates via a theme
---
**Note:** this document is geared toward template development for classic themes. Check this other document for [block theme development](../../plugins/woocommerce-blocks/docs/designers/theming/README.md).
We are unable to provide support for customizations under our [Support Policy](http://woocommerce.com/support-policy/). If you
need to further customize a snippet, or extend its functionality, we highly
recommend [Codeable](https://codeable.io/?ref=z4Hnp), or a [Certified WooExpert](https://woocommerce.com/experts/).
**NOTE** This document makes reference to classic themes which use PHP templates. If you are working on a block theme with HTML templates, [please check the Theming docs for block themes](https://github.com/woocommerce/woocommerce/blob/trunk/plugins/woocommerce-blocks/docs/designers/theming/README.md).
Overview
---
## Overview
---
WooCommerce template files contain the markup and template structure for the frontend and HTML emails of your store.
Below is video walkthrough showing how one may go about updating the template files.
WooCommerce template files contain the **markup** and **template structure** for **frontend and HTML emails** of your
store.
[![Documentation for Template structure & Overriding templates via a theme](https://embed-ssl.wistia.com/deliveries/a2f57c5896505b39952aa8411a474066.jpg?image_play_button_size=2x&amp;image_crop_resized=960x540&amp;image_play_button=1&amp;image_play_button_color=694397e0)](https://woocommerce.com/document/template-structure/?wvideo=8mvl4bro0g)
When you open these files, you will notice they all contain **hooks** that allow you to add/move content without needing
to edit template files themselves. This method protects against upgrade issues, as the template files can be left
completely untouched.
## Template List
## Template list
The various template files on your WooCommerce site can be found via an FTP client or your hosts file manager, in `/wp-content/plugins/woocommerce/templates/`. Below are links to the current and earlier versions of the WooCommerce template files on Github, where you can view the code exactly as it appears in those files:
| Latest Version | Files |
| -------------- | ----- |
| 8.9 | [View template files](https://github.com/woocommerce/woocommerce/tree/8.9.0/plugins/woocommerce/templates) |
Below are the links to the files of all major previous WooCommerce versions:
| Version | Files |
| -------------- | ----- |
| 8.8.0 | [View template files](https://github.com/woocommerce/woocommerce/tree/8.8.0/plugins/woocommerce/templates) |
| 8.7.0 | [View template files](https://github.com/woocommerce/woocommerce/tree/8.7.0/plugins/woocommerce/templates) |
| 8.6.0 | [View template files](https://github.com/woocommerce/woocommerce/tree/8.6.0/plugins/woocommerce/templates) |
| 8.5.0 | [View template files](https://github.com/woocommerce/woocommerce/tree/8.5.0/plugins/woocommerce/templates) |
| 8.4.0 | [View template files](https://github.com/woocommerce/woocommerce/tree/8.4.0/plugins/woocommerce/templates) |
| 8.3.0 | [View template files](https://github.com/woocommerce/woocommerce/tree/8.3.0/plugins/woocommerce/templates) |
| 8.2.0 | [View template files](https://github.com/woocommerce/woocommerce/tree/8.2.0/plugins/woocommerce/templates) |
| 8.1.0 | [View template files](https://github.com/woocommerce/woocommerce/tree/8.1.0/plugins/woocommerce/templates) |
| 8.0.0 | [View template files](https://github.com/woocommerce/woocommerce/tree/8.0.0/plugins/woocommerce/templates) |
| 7.9.0 | [View template files](https://github.com/woocommerce/woocommerce/tree/7.9.0/plugins/woocommerce/templates) |
| 7.8.0 | [View template files](https://github.com/woocommerce/woocommerce/tree/7.8.0/plugins/woocommerce/templates) |
| 7.7.0 | [View template files](https://github.com/woocommerce/woocommerce/tree/7.7.0/plugins/woocommerce/templates) |
| 7.6.0 | [View template files](https://github.com/woocommerce/woocommerce/tree/7.6.0/plugins/woocommerce/templates) |
| 7.5.0 | [View template files](https://github.com/woocommerce/woocommerce/tree/7.5.0/plugins/woocommerce/templates) |
| 7.4.0 | [View template files](https://github.com/woocommerce/woocommerce/tree/7.4.0/plugins/woocommerce/templates) |
| 7.3.0 | [View template files](https://github.com/woocommerce/woocommerce/tree/7.3.0/plugins/woocommerce/templates) |
| 7.2.0 | [View template files](https://github.com/woocommerce/woocommerce/tree/7.2.0/plugins/woocommerce/templates) |
| 7.1.0 | [View template files](https://github.com/woocommerce/woocommerce/tree/7.1.0/plugins/woocommerce/templates) |
| 7.0.0 | [View template files](https://github.com/woocommerce/woocommerce/tree/7.0.0/plugins/woocommerce/templates) |
| 6.9.0 | [View template files](https://github.com/woocommerce/woocommerce/tree/6.9.0/plugins/woocommerce/templates) |
| 6.8.0 | [View template files](https://github.com/woocommerce/woocommerce/tree/6.8.0/plugins/woocommerce/templates) |
| 6.7.0 | [View template files](https://github.com/woocommerce/woocommerce/tree/6.7.0/plugins/woocommerce/templates) |
| 6.6.0 | [View template files](https://github.com/woocommerce/woocommerce/tree/6.6.0/plugins/woocommerce/templates) |
| 6.5.0 | [View template files](https://github.com/woocommerce/woocommerce/tree/6.5.0/plugins/woocommerce/templates) |
| 6.4.0 | [View template files](https://github.com/woocommerce/woocommerce/tree/6.4.0/plugins/woocommerce/templates) |
| 6.3.0 | [View template files](https://github.com/woocommerce/woocommerce/tree/6.3.0/plugins/woocommerce/templates) |
| 6.2.0 | [View template files](https://github.com/woocommerce/woocommerce/tree/6.2.0/plugins/woocommerce/templates) |
| 6.1.0 | [View template files](https://github.com/woocommerce/woocommerce/tree/6.1.0/plugins/woocommerce/templates) |
| 6.0.0 | [View template files](https://github.com/woocommerce/woocommerce/tree/6.0.0/plugins/woocommerce/templates) |
| 5.9.0 | [View template files](https://github.com/woocommerce/woocommerce/tree/5.9.0/templates) |
| 5.8.0 | [View template files](https://github.com/woocommerce/woocommerce/tree/5.8.0/templates) |
| 5.7.0 | [View template files](https://github.com/woocommerce/woocommerce/tree/5.7.0/templates) |
| 5.6.0 | [View template files](https://github.com/woocommerce/woocommerce/tree/5.6.0/templates) |
| 5.5.0 | [View template files](https://github.com/woocommerce/woocommerce/tree/5.5.0/templates) |
| 5.4.0 | [View template files](https://github.com/woocommerce/woocommerce/tree/5.4.0/templates) |
| 5.3.0 | [View template files](https://github.com/woocommerce/woocommerce/tree/5.3.0/templates) |
| 5.2.0 | [View template files](https://github.com/woocommerce/woocommerce/tree/5.2.0/templates) |
| 5.1.0 | [View template files](https://github.com/woocommerce/woocommerce/tree/5.1.0/templates) |
| 5.0.0 | [View template files](https://github.com/woocommerce/woocommerce/tree/5.0.0/templates) |
| 4.9.0 | [View template files](https://github.com/woocommerce/woocommerce/tree/4.9.0/templates) |
| 4.8.0 | [View template files](https://github.com/woocommerce/woocommerce/tree/4.8.0/templates) |
| 4.7.0 | [View template files](https://github.com/woocommerce/woocommerce/tree/4.7.0/templates) |
| 4.6.0 | [View template files](https://github.com/woocommerce/woocommerce/tree/4.6.0/templates) |
| 4.5.0 | [View template files](https://github.com/woocommerce/woocommerce/tree/4.5.0/templates) |
| 4.4.0 | [View template files](https://github.com/woocommerce/woocommerce/tree/4.4.0/templates) |
| 4.3.0 | [View template files](https://github.com/woocommerce/woocommerce/tree/4.3.0/templates) |
| 4.2.0 | [View template files](https://github.com/woocommerce/woocommerce/tree/4.2.0/templates) |
| 4.1.0 | [View template files](https://github.com/woocommerce/woocommerce/tree/4.1.0/templates) |
| 4.0.0 | [View template files](https://github.com/woocommerce/woocommerce/tree/4.0.0/templates) |
| 3.9.0 | [View template files](https://github.com/woocommerce/woocommerce/tree/3.9.0/templates) |
| 3.8.0 | [View template files](https://github.com/woocommerce/woocommerce/tree/3.8.0/templates) |
| 3.7.0 | [View template files](https://github.com/woocommerce/woocommerce/tree/3.7.0/templates) |
| 3.6.0 | [View template files](https://github.com/woocommerce/woocommerce/tree/3.6.0/templates) |
| 3.5.0 | [View template files](https://github.com/woocommerce/woocommerce/tree/3.5.0/templates) |
| 3.4.0 | [View template files](https://github.com/woocommerce/woocommerce/tree/3.4.0/templates) |
| 3.3.0 | [View template files](https://github.com/woocommerce/woocommerce/tree/3.3.0/templates) |
| 3.2.0 | [View template files](https://github.com/woocommerce/woocommerce/tree/3.2.0/templates) |
| 3.1.0 | [View template files](https://github.com/woocommerce/woocommerce/tree/3.1.0/templates) |
| 3.0.0 | [View template files](https://github.com/woocommerce/woocommerce/tree/3.0.0/templates) |
| 2.6.0 | [View template files](https://github.com/woocommerce/woocommerce/tree/2.6.0/templates) |
## Changing Templates via Hooks
When you open a template file, you will notice they all contain _hooks_ that allow you to add/move content without needing to edit template files themselves. Hooks are a way for one piece of code to interact/modify another piece of code at specific, pre-defined spots. This method allows implementing a code snippet that “hooks” into a particular a theme location. It avoids upgrade issues, as the template files can be left completely untouched and doesn't require a child theme to be configured.
Let's take a look at [/wp-content/plugins/woocommerce/templates/emails/admin-new-order.php](https://github.com/woocommerce/woocommerce/blob/8.9.0/plugins/woocommerce/templates/emails/admin-new-order.php) and see what a hook looks like. Starting on line 30, we see the following code, which is responsible for producing the order details section of the New Order email.
```php
/*
* @hooked WC_Emails::order_details() Shows the order details table.
* @hooked WC_Structured_Data::generate_order_data() Generates structured data.
* @hooked WC_Structured_Data::output_structured_data() Outputs structured data.
* @since 2.5.0
*/
do_action( 'woocommerce_email_order_details', $order, $sent_to_admin, $plain_text, $email );
```
The code above outputs the block highlighted in red in the image below, which is the New Order email a shop manager receives following a successful order on their site:
![image](https://woocommerce.com/wp-content/uploads/2020/05/templating-using-hooks.webp)
A code below can be used as a starting point to build out desired functionality. It can then be added to a code snippets plugin to modify the output at that particular location in the template, without having to edit the template itself. The same goes for other hooks, wherever in the templates they may appear.
```php
add_action( 'woocommerce_email_order_details', 'my_custom_woo_function');
function my_custom_woo_function() {
/* Your code goes here */
}
```
## Changing Templates by Editing the Files
Editing files directly in a plugin or a parent theme creates the risk of causing errors that could bring a site to a grinding halt. But more importantly, any changes made in this way will disappear when the plugin or theme updates itself; a process that entirely deletes the old version and replaces it with a fresh, updated copy.
Instead, the recommended approach is to [set up a child theme](https://developer.woocommerce.com/docs/how-to-set-up-and-use-a-child-theme/), which creates a safe directory where to make overriding changes that will not be automatically updated.
For this example, let's call our child theme `storefront-child`. With `storefront-child` in place, edits can be made in an upgrade-safe way by using overrides. Copy the template into a directory within your child theme named `/storefront-child/woocommerce/` keeping the same file structure but removing the `/templates/` subdirectory.
To override the admin order notification in our example, copy `wp-content/plugins/woocommerce/templates/emails/admin-new-order.php` to `wp-content/themes/storefront-child/woocommerce/emails/admin-new-order.php`
The copied file will now override the WooCommerce default template file, so you can make any changes you wish to the copied file, and see it reflected in the resulting output.
---
Template files can be found within the **/woocommerce/templates/** directory:
| Latest version | Files |
|:---------------|:-----------------------------------------------------------------------------------------------------------|
| v8.4.0 | [View template files](https://github.com/woocommerce/woocommerce/tree/8.4.0/plugins/woocommerce/templates) |
---
<!-- markdownlint-disable MD033 -->
<details>
<summary>Expand to view files of all major previous versions</summary>
| Version | Files |
|---------|------------------------------------------------------------------------------------------------------------|
| v8.3.0 | [View template files](https://github.com/woocommerce/woocommerce/tree/8.3.0/plugins/woocommerce/templates) |
| v8.2.0 | [View template files](https://github.com/woocommerce/woocommerce/tree/8.2.0/plugins/woocommerce/templates) |
| v.8.1.0 | [View template files](https://github.com/woocommerce/woocommerce/tree/8.1.0/plugins/woocommerce/templates) |
| v8.0.0 | [View template files](https://github.com/woocommerce/woocommerce/tree/8.0.0/plugins/woocommerce/templates) |
| v7.9.0 | [View template files](https://github.com/woocommerce/woocommerce/tree/7.9.0/plugins/woocommerce/templates) |
| v7.8.0 | [View template files](https://github.com/woocommerce/woocommerce/tree/7.8.0/plugins/woocommerce/templates) |
| v7.7.0 | [View template files](https://github.com/woocommerce/woocommerce/tree/7.7.0/plugins/woocommerce/templates) |
| v7.6.0 | [View template files](https://github.com/woocommerce/woocommerce/tree/7.6.0/plugins/woocommerce/templates) |
| v7.5.0 | [View template files](https://github.com/woocommerce/woocommerce/tree/7.5.0/plugins/woocommerce/templates) |
| v7.4.0 | [View template files](https://github.com/woocommerce/woocommerce/tree/7.4.0/plugins/woocommerce/templates) |
| v7.3.0 | [View template files](https://github.com/woocommerce/woocommerce/tree/7.3.0/plugins/woocommerce/templates) |
| v7.2.0 | [View template files](https://github.com/woocommerce/woocommerce/tree/7.2.0/plugins/woocommerce/templates) |
| v7.1.0 | [View template files](https://github.com/woocommerce/woocommerce/tree/7.1.0/plugins/woocommerce/templates) |
| v7.0.0 | [View template files](https://github.com/woocommerce/woocommerce/tree/7.0.0/plugins/woocommerce/templates) |
| v6.9.0 | [View template files](https://github.com/woocommerce/woocommerce/tree/6.9.0/plugins/woocommerce/templates) |
| v6.8.0 | [View template files](https://github.com/woocommerce/woocommerce/tree/6.8.0/plugins/woocommerce/templates) |
| v6.7.0 | [View template files](https://github.com/woocommerce/woocommerce/tree/6.7.0/plugins/woocommerce/templates) |
| v6.6.0 | [View template files](https://github.com/woocommerce/woocommerce/tree/6.6.0/plugins/woocommerce/templates) |
| v6.5.0 | [View template files](https://github.com/woocommerce/woocommerce/tree/6.5.0/plugins/woocommerce/templates) |
| v6.4.0 | [View template files](https://github.com/woocommerce/woocommerce/tree/6.4.0/plugins/woocommerce/templates) |
| v6.3.0 | [View template files](https://github.com/woocommerce/woocommerce/tree/6.3.0/plugins/woocommerce/templates) |
| v6.2.0 | [View template files](https://github.com/woocommerce/woocommerce/tree/6.2.0/plugins/woocommerce/templates) |
| v6.1.0 | [View template files](https://github.com/woocommerce/woocommerce/tree/6.1.0/plugins/woocommerce/templates) |
| v6.0.0 | [View template files](https://github.com/woocommerce/woocommerce/tree/6.0.0/plugins/woocommerce/templates) |
| v5.9.0 | [View template files](https://github.com/woocommerce/woocommerce/tree/5.9.0/templates) |
| v5.8.0 | [View template files](https://github.com/woocommerce/woocommerce/tree/5.8.0/templates) |
| v5.7.0 | [View template files](https://github.com/woocommerce/woocommerce/tree/5.7.0/templates) |
| v5.6.0 | [View template files](https://github.com/woocommerce/woocommerce/tree/5.6.0/templates) |
| v5.5.0 | [View template files](https://github.com/woocommerce/woocommerce/tree/5.5.0/templates) |
| v5.4.0 | [View template files](https://github.com/woocommerce/woocommerce/tree/5.4.0/templates) |
| v5.3.0 | [View template files](https://github.com/woocommerce/woocommerce/tree/5.3.0/templates) |
| v5.2.0 | [View template files](https://github.com/woocommerce/woocommerce/tree/5.2.0/templates) |
| v5.1.0 | [View template files](https://github.com/woocommerce/woocommerce/tree/5.1.0/templates) |
| v5.0.0 | [View template files](https://github.com/woocommerce/woocommerce/tree/5.0.0/templates) |
| v4.9.0 | [View template files](https://github.com/woocommerce/woocommerce/tree/4.9.0/templates) |
| v4.8.0 | [View template files](https://github.com/woocommerce/woocommerce/tree/4.8.0/templates) |
| v4.7.0 | [View template files](https://github.com/woocommerce/woocommerce/tree/4.7.0/templates) |
| v4.6.0 | [View template files](https://github.com/woocommerce/woocommerce/tree/4.6.0/templates) |
| v4.5.0 | [View template files](https://github.com/woocommerce/woocommerce/tree/4.5.0/templates) |
| v4.4.0 | [View template files](https://github.com/woocommerce/woocommerce/tree/4.4.0/templates) |
| v4.3.0 | [View template files](https://github.com/woocommerce/woocommerce/tree/4.3.0/templates) |
| v4.2.0 | [View template files](https://github.com/woocommerce/woocommerce/tree/4.2.0/templates) |
| v4.1.0 | [View template files](https://github.com/woocommerce/woocommerce/tree/4.1.0/templates) |
| v4.0.0 | [View template files](https://github.com/woocommerce/woocommerce/tree/4.0.0/templates) |
| v3.9.0 | [View template files](https://github.com/woocommerce/woocommerce/tree/3.9.0/templates) |
| v3.8.0 | [View template files](https://github.com/woocommerce/woocommerce/tree/3.8.0/templates) |
| v3.7.0 | [View template files](https://github.com/woocommerce/woocommerce/tree/3.9.0/templates) |
| v3.6.0 | [View template files](https://github.com/woocommerce/woocommerce/tree/3.6.0/templates) |
| v3.5.0 | [View template files](https://github.com/woocommerce/woocommerce/tree/3.5.0/templates) |
| v3.4.0 | [View template files](https://github.com/woocommerce/woocommerce/tree/3.4.0/templates) |
| v3.3.0 | [View template files](https://github.com/woocommerce/woocommerce/tree/3.3.0/templates) |
| v3.2.0 | [View template files](https://github.com/woocommerce/woocommerce/tree/3.2.0/templates) |
| v3.1.0 | [View template files](https://github.com/woocommerce/woocommerce/tree/3.1.0/templates) |
| v3.0.0 | [View template files](https://github.com/woocommerce/woocommerce/tree/3.0.0/templates) |
| v2.6.0 | [View template files](https://github.com/woocommerce/woocommerce/tree/2.6.0/templates) |
</details>
<!-- markdownlint-enable MD033 -->
**Note** A (desirable) side-effect of your templates being upgrade-safe is that WooCommerce core templates will update, but your custom overrides will not. You may occassionally see notices in your System Status report that says, e.g. “version 3.5.0 is out of date. The core version is 3.7.0″. Should that happen, follow the Fixing Outdated WooCommerce Templates guide to bring them in line.
---
## How to Edit Files
---
Edit files in an **upgrade-safe** way using **overrides**. Copy the template into a directory within your theme named `/woocommerce` keeping the same file structure but removing the `/templates/` subdirectory.
Example: To override the admin order notification, copy: `wp-content/plugins/woocommerce/templates/emails/admin-new-order.php` to `wp-content/themes/yourtheme/woocommerce/emails/admin-new-order.php`.
The copied file will now override the WooCommerce default template file.
**Warning:** Do not edit these files within the core plugin itself as they are overwritten during the upgrade process and any customizations will be lost. For more detailed information, see [Fixing Outdated WooCommerce Templates](https://woocommerce.com/document/fix-outdated-templates-woocommerce/).
## For Custom Templates
## Declare Theme Support for Custom Templates
If you are a theme developer or using a theme with custom templates, you must declare WooCommerce theme support using the `add_theme_support` function. See [Declaring WooCommerce Support in Themes](https://github.com/woocommerce/woocommerce/wiki/Declaring-WooCommerce-support-in-themes) at GitHub.
If your theme has a `woocommerce.php` file, you will be unable to override the `woocommerce/archive-product.php` custom template in your theme, as `woocommerce.php` has priority over other template files. This is intended to prevent display issues.
If your theme has `woocommerce.php`, you will be unable to override `woocommerce/archive-product.php` custom template in your theme, as `woocommerce.php` has priority over other template files. This is intended to prevent display issues.
---

View File

@ -3,9 +3,10 @@
"title": "WooCommerce Monorepo",
"description": "Monorepo for the WooCommerce ecosystem",
"homepage": "https://woocommerce.com/",
"packageManager": "pnpm@9.1.3",
"engines": {
"node": "^20.11.1",
"pnpm": "^9.1.0"
"pnpm": "9.1.3"
},
"private": true,
"repository": {
@ -22,8 +23,8 @@
"test": "pnpm -r test",
"lint": "pnpm -r lint",
"cherry-pick": "node ./tools/cherry-pick/bin/run",
"clean": "rimraf -g '**/node_modules' '**/.wireit' && pnpm store prune && pnpm i",
"distclean": "git clean --force -d -X",
"clean": "rimraf -g '**/node_modules' '**/.wireit' && pnpm store prune",
"buildclean": "git clean --force -d -X ./packages ./plugins ./tools",
"preinstall": "npx only-allow pnpm",
"postinstall": "pnpm git:update-hooks",
"git:update-hooks": "if test -d .git; then rm -rf .git/hooks && mkdir -p .git/hooks && husky install; else husky install; fi",
@ -75,6 +76,9 @@
"@types/react": "^17.0.71",
"react-resize-aware": "3.1.1",
"@automattic/tour-kit>@wordpress/element": "4.4.1"
},
"patchedDependencies": {
"@wordpress/edit-site@5.15.0": "bin/patches/@wordpress__edit-site@5.15.0.patch"
}
}
}

View File

@ -0,0 +1,4 @@
Significance: patch
Type: dev
Fix pnpm version to 9.1.3 to avoid dependency installation issues.

Some files were not shown because too many files have changed in this diff Show More