Code Snippets

A shared folder with AI prompts and code snippets

From workspace: CodeWP

Team: Main

Total snippets: 60

CodeWP

Code Snippets

60 snippets

auto_rss.php

This PHP snippet is designed for integration with a WordPress website to automatically fetch and create new posts from an external RSS feed. By loading the WordPress core, the script gains access to its inherent functionalities. The script then defines an RSS feed URL, retrieves its content, and parses it using the SimpleXML PHP extension. Iterating through each item in the RSS feed, it checks whether a post with an identical title already exists in the WordPress database to prevent content duplication. If no matching post is found, it crafts a new post object populated with the RSS item's title and description, and subsequently inserts this into the WordPress database as a published post authored by the primary user in the default category. While functional, real-world application might necessitate additional checks, error handling, and customizations tailored to the specific RSS feed and WordPress site requirements.

<?php // Load WordPress require( dirname( __FILE__ ) . '/wp-load.php' ); // Set the RSS feed URL $feed_url = "http://example.com/rss"; // Get the RSS feed content $feed = simplexml_load_file( $feed_url ); // Loop through each feed item and...

top_bar_dd.php

The provided PHP code creates a dropdown menu with links to different websites. This is done inside a 'TopBarDropdown' class. The 'TopBarDropdown' class has a constructor that initializes an associative array with the names of the links as keys and the corresponding URLs as values. When the 'render' method is called, it outputs HTML for a dropdown menu where each option's value is a URL and its display text is the name of the link. When a user selects an option, they are redirected to the corresponding URL. The last two lines create an instance of the 'TopBarDropdown' class and call the 'render' method to display the dropdown menu.

<?php class TopBarDropdown { private $links; function __construct() { $this->links = array( 'Link 1' => 'https://example.com/link1', 'Link 2' => 'https://example.com/link2', 'Link 3' =>...

custom_admin_bar_logo.php

The provided PHP code will create a new top-level settings menu in the WordPress dashboard named 'Custom Settings'. In this settings page, there is an input field where you can add the URL for the custom logo. This URL is saved as an option in the WordPress database. The custom logo is then added to the WordPress top admin bar using the 'admin_bar_menu' action. The logo is linked to the home URL of the website and is styled to a height of 32px with the width adjusting automatically. The code checks if the logo URL is set before adding it to the top bar to prevent errors.

<?php // Create custom plugin settings menu add_action('admin_menu', 'custom_create_menu'); function custom_create_menu() { //create new top-level menu add_menu_page('Custom Plugin Settings', 'Custom Settings', 'administrator', __FILE__,...

Dog Breeds Select2 Metabox Plugin

This file is a WordPress plugin that introduces a custom metabox to the Dog post type using Select2 for an enhanced user interface. It allows users to select dog breeds from a custom taxonomy with a searchable dropdown, which supports multiple selections and lazy loading for performance. The plugin also includes scripts for enqueuing Select2 assets and functions for saving the selected terms.

<?php /* Plugin Name: Dog Breeds Metabox with Select2 Description: A metabox using Select2 for Dog post type, with lazy loaded choices from dog_breeds taxonomy. Version: 1.0 Author: Your Name */ function codewp_enqueue_select2() { ...

Dog CPT and Taxonomy Plugin

This plugin provides a straightforward way to manage dog listings on your WordPress site. It introduces a custom post type 'Dog' for adding and managing individual dog listings, and a custom taxonomy 'Dog Breeds' for organizing these listings by breed. It's equipped with an auto-populate feature that fills the taxonomy with demo data if it's empty.

<?php /* Plugin Name: Dog CPT and Taxonomy Description: This plugin creates a custom post type 'Dog' and a custom taxonomy 'Dog Breeds'. Version: 1.0 Author: CodeWP Text Domain: codewp */ // Register Custom Post Type function create_dog_cpt() { ...

export_wc_coupons.php

The provided code is a PHP and JavaScript solution for adding an "Export Coupons" button to the WordPress admin page for managing WooCommerce coupons. This button allows users to export all the available coupons as a CSV file. The PHP function add_export_coupons_button adds the button to the page actions section, next to the "Add Coupon" button. When the "Export Coupons" button is clicked, an AJAX request is sent to the server to export the coupons as a CSV file. The PHP function export_coupons_as_csv retrieves all the coupons, prepares the data in CSV format, and saves it as a file. Once the export is complete, a success message is displayed. The code also includes the necessary WordPress files and registers the AJAX action for exporting coupons.

<?php // Function to handle AJAX request add_action("admin_footer", "add_export_coupons_button"); function add_export_coupons_button() { global $current_screen; if ($current_screen->post_type != "shop_coupon") { return; }?> ...

Gravity Forms Display Entries Shortcode

This WordPress file contains a shortcode that allows users to display entries from a specified Gravity Form in a structured table format. It uses the Gravity Forms API to retrieve the entries and then generates an HTML table to present them on the site.

<?php add_shortcode("display_gf_entries", "display_gravity_forms_entries"); function display_gravity_forms_entries($atts) { $defaults = [ "id" => "", ]; $atts = shortcode_atts($defaults, $atts); if (class_exists("GFAPI"))...

simple_contact_form.php

The provided PHP code will create a WordPress plugin named "Simple Contact Form". This plugin will add a shortcode [simple_contact_form] that you can use to display the form on any page or post. The form includes fields for name, email, message, and a Google reCAPTCHA for spam protection. When the form is submitted, an AJAX request is sent to the server to process the form. The server verifies the nonce and the reCAPTCHA response. If the validation is successful, an email containing the form data is sent to the site admin. The reCAPTCHA site key and secret should be replaced with your actual reCAPTCHA keys. Please replace "your-site-key" and "your-secret" with your actual reCAPTCHA site key and secret key. The form is only visible to users who have JavaScript enabled in their browsers, which adds an extra layer of spam protection.

<?php /** * Plugin Name: Simple Contact Form * Description: A simple contact form with conditional visibility and reCAPTCHA protection. * Version: 1.0 * Author: Your Name * Text Domain: codewp */ if (!defined('ABSPATH')) { exit; //...

plugin_notes.php

This PHP code snippet is for a WordPress plugin named "Admin Plugins Notes" which enables users to add personal notes to plugins directly from the WordPress admin plugins page. The plugin adds a new column for notes in the plugins table where users can write and save remarks for each plugin. It uses AJAX to update these notes without reloading the page, thereby improving user experience. The functionality to add and save notes is only available to users with the 'activate_plugins' capability, typically administrators. The notes are stored in the WordPress database using the update_option function, with each note tied to a specific plugin file.

<?php /** * Plugin Name: Admin Plugins Notes * Plugin URI: https://codewp.ai * Description: Add a notes column to the admin plugins table * Version: 1.0 * Author: CodeWP Assistant * Author URI: https://codewp.ai */ class...

Custom Onsale Badge for Individual Variations

This code is used to enhance the functionality of a WooCommerce variable product by adding a "On Sale" badge to the variation options when they are selected. The code consists of several functions and actions. The first function, 'add_data_sale_to_variation_option', adds a 'data-sale' attribute to the variation options that are on sale. The second function, 'cwpai_add_sale_badge_script', adds a script to the footer that listens for the change event on select elements and dynamically adds or removes the "On Sale" badge based on the selected option. The third function, 'cwpai_hide_default_sale_badge', hides the default sale badge using CSS. The fourth function, 'cwpai_add_on_sale_badge_styles', adds custom CSS styles for the "On Sale" badge.

<?php add_filter( 'woocommerce_dropdown_variation_attribute_options_html', 'cwpai_add_data_sale_to_variation_option', 10, 2 ); function cwpai_add_data_sale_to_variation_option( $html, $args ) { // Ensure that the product is a variable...

WooCommerce Auto-Cart Clear

This file contains a WordPress class that hooks into WooCommerce to clear user shopping carts after 5 minutes of inactivity. It uses user meta and cookies to track the last activity time of logged-in users and guests, respectively.

<?php if ( ! class_exists( 'WC_Session' ) ) { return; } class WC_Clear_Cart_After_Time { protected $cart_cleared; public function __construct() { $this->cart_cleared = false; add_action( 'init', array( $this,...

Agency Custom Post Type

This file contains the code necessary to create a new Custom Post Type in WordPress called 'Agency', which includes several custom fields such as Website URL, City, State, ZIP, and Phone #. The code makes it possible to manage and categorize agency-related content separately from posts and pages. It uses the Advanced Custom Fields plugin for additional metadata associated with each agency entry.

<?php // Register Custom Post Type Agency function create_agency_cpt() { $labels = array( 'name' => _x( 'Agencies', 'Post Type General Name', 'text_domain' ), 'singular_name' => _x( 'Agency', 'Post Type Singular Name',...

WooCommerce Selfie Upload on Registration

This code is a WordPress plugin called "WooCommerce Selfie Upload" that extends the WooCommerce registration form by adding a mandatory selfie upload field. The plugin modifies the registration form by adding the necessary enctype attribute to allow file uploads. It also adds a file input field to the form, specifies its accepted file types (JPG and PNG), and makes it required. The plugin includes validation to check if a valid selfie image was uploaded and displays an error message if not. After successful registration, the plugin saves the uploaded selfie file as an attachment in the media library and associates it with the user's profile by storing the attachment ID in user meta. Lastly, it displays the uploaded selfie image in the admin user profile.

<?php /* Plugin Name: WooCommerce Selfie Upload Plugin URI: https://codewp.ai Description: Extend the WooCommerce registration form with a mandatory selfie upload field. Version: 1.0 Author: CodeWP Assistant Author URI: https://codewp.ai Text...

WooCommerce Admin-Only Coupon Code

This file contains code that enhances WooCommerce by allowing the creation of coupons that are exclusively for admin use. It includes functions to add a checkbox on the coupon edit page, save the admin-only setting, and validate coupon usage based on the admin-only status.

<?php /** * Add a checkbox to the coupon data panel to mark the coupon as "Admin Only". */ add_action('woocommerce_coupon_options', 'cwpai_add_coupon_option_field', 10, 2); function cwpai_add_coupon_option_field($coupon_id, $coupon) { ...

CodeWP Google Analytics Integration

The CodeWP Google Analytics plugin provides a seamless way to add Google Analytics GA4 tracking code to your WordPress site. It leverages the WordPress action hook system to insert the necessary scripts into the header of your website, thus enabling GA4 tracking on all pages.

<?php /* Plugin Name: CodeWP Google Analytics Plugin URI: https://codewp.ai Description: This plugin adds Google Analytics GA4 tracking code to your WordPress website. Version: 1.0 Author: CodeWP Assistant Author URI: https://codewp.ai License:...

WooCommerce Custom Email Notifications

This custom plugin for WooCommerce sends separate order notifications to specific email addresses based on the categories of the products in the order. It hooks into the WooCommerce order status completed action and iterates through the order items, matching product categories with predefined email addresses, and dispatching notifications accordingly.

<?php /** * Plugin Name: WooCommerce Custom Email Notifications * Plugin URI: https://codewp.ai * Description: This plugin sends order notifications for different categories to separate email addresses. * Version: 1.0.0 * Author: CodeWP...

WooCommerce Local Free Shipping Class

This file contains a PHP class that integrates with WooCommerce to provide free shipping for products that match the customer's local area zip code. It adds a new field to the product's shipping options for entering a local zip code and applies free shipping for matching products during cart calculations.

<?php if (!class_exists("Cwpai_Local_Free_Shipping")) { class Cwpai_Local_Free_Shipping { public function __construct() { add_action("woocommerce_product_options_shipping", [$this,...

WooCommerce Delivery Date Plugin

This plugin introduces a mandatory delivery date field at the WooCommerce checkout process. It saves the date selected by the customer and displays it on the admin order page, ensuring the delivery date is clearly communicated to store management.

<?php /* Plugin Name: WooCommerce Delivery Date Plugin URI: https://codewp.ai Description: This plugin adds a delivery date field to WooCommerce checkout process and shows it on the admin order page. Author: CodeWP Assistant Author URI:...

WP REST API Basic Authentication

This plugin ensures that only logged-in users or users with valid basic HTTP authentication credentials can access the WordPress REST API. It hooks into the REST API initialization process, checks for user credentials, and returns an error if the authentication fails.

<?php /** * Plugin Name: WP REST API Basic Authentication * Plugin URI: https://codewp.ai * Description: This WordPress plugin requires users to have basic authentication to access the WP REST API if they're not logged in. * Version: 1.0 *...

User Registration Chart Widget

This WordPress plugin provides a dashboard widget that displays a bar chart of user registrations over the past 7 days. It utilizes Google Charts to render the bar chart and queries the WordPress database to retrieve the necessary data.

<?php /* Plugin Name: User Registration Chart Plugin URI: https://codewp.ai Description: Adds a widget to the WordPress dashboard showing user registration data as a bar chart for the past 7 days. Version: 1.0 Author: CodeWP Assistant Author URI:...

WooCommerce Coupons CSV Exporter

This file contains the code for a WordPress plugin that allows users to export all WooCommerce coupons to a CSV file. The CSV file is then saved to the WordPress media library for easy access. The plugin adds an 'Export Coupons' button to the WooCommerce coupons page in the admin area, providing a seamless export experience.

<?php /** * Plugin Name: WooCommerce Coupons Exporter * Plugin URI: https://codewp.ai * Author: CodeWP Assistant * Author URI: https://codewp.ai * Description: This plugin exports all WooCommerce coupons as a CSV and saves the file to the...

Contact Form with Recaptcha Plugin

This WordPress plugin provides a simple yet secure contact form with conditional visibility of fields and Google Recaptcha integration. It ensures user inputs are sanitized, and email notifications are sent upon successful form submissions.

<?php /** * Plugin Name: Contact Form with Conditional Visibility and Recaptcha * Description: A simple contact form with conditional visibility and Recaptcha protection. * Version: 1.0 * Author: CodeWP Assistant * Author URI:...

Custom Dashboard Logo Plugin

This WordPress plugin allows users to customize the default WordPress dashboard logo by replacing it with their own logo. Users can easily select an image from the media library to serve as the new dashboard logo, enhancing their site's branding within the administrative interface.

<?php /** * Plugin Name: Custom Dashboard Logo * Plugin URI: https://codewp.ai * Description: This plugin replaces the WordPress logo in the dashboard with a custom logo selected from the media library, if set. * Version: 1.0 * Author:...

Custom WP Top/Admin Bar Dropdown Plugin

This WordPress plugin provides a convenient way to add a custom dropdown menu to the admin bar. It's designed to make important client-specific links easily accessible from anywhere within the admin area. The plugin is easily customizable to fit the needs of any WordPress site.

<?php /** * Plugin Name: Custom WP Top/Admin Bar Dropdown * Plugin URI: https://codewp.ai * Description: This plugin adds a custom dropdown with links for clients in the WordPress top/admin bar. * Version: 1.0 * Author: CodeWP Assistant *...

WooCommerce Cart Minimum Plugin

This WordPress plugin adds a minimum cart total requirement to WooCommerce stores. It hooks into WooCommerce settings to allow site administrators to define a minimum order total and displays a notice to customers if their cart total does not meet this requirement, preventing them from proceeding to checkout until the minimum is met.

<?php /** * Plugin Name: WooCommerce Cart Minimum * Plugin URI: https://codewp.ai * Author: CodeWP Assistant * Author URI: https://codewp.ai * Description: This plugin adds a mandatory minimum amount for WooCommerce cart and prevents...

RSS Feed to WordPress Post Plugin

The 'RSS Feed to WP Post' plugin is a WordPress plugin that automatically fetches items from a specified RSS feed and creates WordPress posts for each unique item. It allows for setting post type, status, and import limits, and runs on an hourly schedule to check for new content.

<?php /* Plugin Name: RSS Feed to WP Post Plugin URI: https://codewp.ai Description: This plugin automatically creates and publishes posts on WordPress from an RSS feed. Version: 1.0 Author: CodeWP Assistant Author URI: https://codewp.ai Text...

Gravity Forms Submissions DataTable

This WordPress plugin introduces a shortcode that leverages jQuery DataTables to present Gravity Forms submissions on your website. It's a useful tool for site administrators to display form entries in an organized, searchable, and sortable table. The plugin also takes care of loading necessary DataTables scripts and styles.

<?php /** * Plugin Name: Display GF Submissions * Plugin URI: https://codewp.ai * Description: This plugin adds a shortcode that displays Gravity Forms submissions on the frontend using jQuery DataTables. * Version: 1.0 * Author: CodeWP...

Award Sorting Functions

These PHP functions are designed to fetch and sort custom WordPress award posts. It uses an array of predefined categories and types to sort awards by year, category, and then by type, in that order.

<?php // Function to sort awards function codewp_sort_awards($a, $b) { // Define your specific order for categories and types $categories_order = array('Best Actor', 'Best Actress', 'Best Picture'); $types_order = array('Nominee',...

WordPress Awards Sorting Script

This PHP script for WordPress sorts a list of awards custom post types. It first retrieves the awards from the database including their year, category, and type. Then, it sorts them using a custom sorting function based on a predefined order set in the WordPress ACF options page for both categories and types, and by year.

<?php global $wpdb; // Get all awards $query = " SELECT p.ID, p.post_title, MAX(CASE WHEN pm.meta_key = 'awd_year' then pm.meta_value ELSE NULL END) as awd_year, MAX(CASE WHEN pm.meta_key = 'awd_sort_cat' then pm.meta_value ELSE NULL...

Award Custom Post Type

This WordPress file contains code to create a custom post type named 'awards' with additional meta fields to store award details such as year, category, and type. It also includes functions to add and save these meta fields, as well as a function to generate test data.

<?php // Register a new post type called "awards" function codewp_create_post_type() { register_post_type( 'awards', array( 'labels' => array( 'name' => __( 'Awards' ), 'singular_name' =>...

CWPAction - Create Post Form Action Class

The CWPAction class extends the Breakdance form actions, enabling the creation of new WordPress posts upon form submission. It captures the title and content from form fields and creates a new post with the current user as the author, saving it as a draft.

<?php // 1. Create an action class to represent your field class CWPAction extends \Breakdance\Forms\Actions\Action { public static function name() { return '[CODEWP] Create Post Action'; } // The slug method returns a...

Recently Published Badge Snippet

This PHP code snippet is designed to automatically display a 'Recently Published' badge on WordPress posts that were published within the last 48 hours. It works by comparing the post's publication time with the current time and adding a badge to the post if it meets the criteria.

<?php // get the post date $post_date = get_the_date('Y-m-d H:i:s'); // convert post date to timestamp $post_timestamp = strtotime($post_date); // get current date and time $current_timestamp = time(); // calculate the difference in...

CodeWP AI Image Thingamabob Plugin

This plugin integrates with OpenAI to provide automatic alt text, captions, and descriptions for images as they are added to the WordPress media library. It includes a settings page for entering an OpenAI API key and toggling the auto-fill feature.

<?php /* Plugin Name: CodeWP AI Image Thingamabob Plugin URI: https://codewp.ai Description: This WordPress plugin uses the OpenAI API to automatically add alt text, caption, and description to images when they are added to the media library. The...

Copyright Year Shortcode Plugin

This WordPress plugin provides a shortcode that outputs a dynamic copyright year, which can be set to display a range from a specified start year to the current year. It includes several attributes for customization such as start year, separator, date format, and optional text before and after the year range.

<?php /* Plugin Name: CodeWP Copyright Year Shortcode Plugin URI: https://codewp.ai Description: A flexible shortcode to display copyright years in WordPress posts and pages. Version: 1.0 Author: CodeWP Author URI: https://codewp.ai License: GPLv2...

WooCommerce Dry Ice Shipping Fee Function

This file contains a function for WooCommerce that calculates additional fees for cart items belonging to a specific shipping class, particularly for items requiring dry ice shipping. It adds a base fee for a defined initial quantity and calculates additional fees for each step quantity beyond that.

<?php add_action( 'woocommerce_cart_calculate_fees', 'cwpai_shipping_class_and_item_quantity_fee', 10, 1 ); function cwpai_shipping_class_and_item_quantity_fee( $cart ) { ## -------------- YOUR SETTINGS BELOW ------------ ## ...

Custom WP Die Handler Function

This file contains a custom WordPress function that handles specific error messages by redirecting users to a designated page if they reach their download limit. The function checks the error message for a download limit notice and, if it matches, verifies if the redirect page exists and is published before redirecting the user. If the redirect page is not valid, a default error message is displayed.

<?php function cwpai_custom_wp_die_handler( $message, $title = '', $args = array() ) { // Define the page ID where users will be redirected $redirect_page_id = 2; // Check if the message is about the download limit if ( strpos(...

Custom WooCommerce Download Limit Alert

This customization alters the default WooCommerce notification when a user reaches the download limit for a product. It enables a more tailored and potentially user-friendly message, improving the overall shopping experience.

<?php /** * Change the default WooCommerce download limit reached message */ function custom_wc_override_default_strings( $translated_text, $text, $domain ) { if ( $domain === 'woocommerce' && $text === 'Sorry, you have reached your...

WooCommerce Product Alternatives Plugin

This plugin allows WooCommerce store owners to display alternative product suggestions in place of the default "Out of Stock" message. When a customer views a product that is not available, they are presented with a list of alternative in-stock products to encourage continued shopping and potentially prevent lost sales.

<?php /** * Plugin Name: WooCommerce Product Alternatives * Description: A plugin to add the ability for customers to see alternative products if the main product is out of stock, replacing the "Out of Stock" message with a custom list. *...

CodeWP Featured Image Generator

This WordPress plugin leverages OpenAI's Dalle 3 AI to automatically generate featured images for posts. It adds a button to the post editor screen that, when clicked, sends a request to generate an image based on the post's content.

<?php /** * Plugin Name: CodeWP Featured Image Generator * Description: Generates featured images for posts using OpenAI's Dalle 3 AI. * Version: 1.0 * Author: CodeWP * Text Domain: cwpai-featured-image-generator */ // If this file is...

Hello World Shortcode

This file contains PHP code that defines a WordPress shortcode for displaying a simple greeting, 'Hello, Mom!'. When added to posts or pages using the [hello-world] tag, the shortcode calls a function that returns this friendly message, which is then rendered on the website.

<?php // Define the function that will handle the shortcode function hello_world_shortcode() { return 'Hello, Mom!'; } // Register the shortcode add_shortcode('hello-world', 'hello_world_shortcode'); ?>

Custom Excerpt Function

This file contains a WordPress function 'make_better_excerpt' that generates improved excerpts by stripping HTML tags, shortening to 100 characters, and neatly ending with an ellipsis.

<?php /** * Function to create better excerpts * * @param string $content The original content * @return string The modified content */ function make_better_excerpt($content) { $excerpt = strip_tags($content); // Remove...

Gravity Forms Address Autocomplete

The provided file is a WordPress PHP snippet that integrates Google Places Autocomplete into a WordPress form. It enqueues the necessary Google Maps API script and sets up a JavaScript function to automatically fill in address fields as the user types, improving data accuracy and user experience.

<?php add_action( 'wp_enqueue_scripts', 'enqueue_autocomplete_script' ); function enqueue_autocomplete_script() { $api_key = 'YOUR_API_KEY_HERE'; wp_enqueue_script( 'google-maps-api',...

Affiliate Top Bar for WooCommerce

This WordPress plugin introduces a customized top bar that appears for users referred by an affiliate link, enhancing their shopping experience. It checks for active AffiliateWP and WooCommerce plugins before displaying the affiliate's name on the top bar.

<?php /** * Plugin Name: CodeWP Affiliate Top Bar * Plugin URI: https://codewp.ai * Description: Displays a custom top bar for users referred by an affiliate. * Version: 1.0 * Author: CodeWP Assistant * Author URI: https://codewp.ai */ //...

WooCommerce Custom Fields Display

This WordPress plugin extends WooCommerce by adding a custom field column to the orders list on the My Account page and displaying the custom field value on the Order Details page. It requires WooCommerce to be installed and uses hooks to integrate the custom field into the order management interface.

<?php /** * Plugin Name: CodeWP WooCommerce Order Custom Fields Display (OOP Version) * Plugin URI: https://codewp.ai * Description: Display custom fields from orders on the WooCommerce My Account page and Order Details page, reworked as an...

Breakdance Forms to Klaviyo Integration

The CWPKlaviyoAction class provides a seamless integration between WordPress forms and Klaviyo. When a form is submitted, the run method is invoked, extracting the name and email from the submission and sending it to Klaviyo. It includes error handling for a robust solution.

<?php // 1. Create an action class to represent your field class CWPKlaviyoAction extends \Breakdance\Forms\Actions\Action { // The name method returns a string used to identify the action in the Form Builder Actions dropdown public...

Assign Tags To Posts from Tag Edit Screen

This PHP code integrates with WordPress and Advanced Custom Fields (ACF) to enhance tag management by allowing users to directly associate specific posts with a tag from within the tag's edit screen in the WordPress admin. When editing an individual tag, a custom field titled "Select Posts" is displayed, where users can select one or more posts to be tagged. Upon saving the tag, the selected posts are automatically assigned to that tag, streamlining the process of organizing content by tags. This functionality is especially useful for site administrators and content managers looking to efficiently manage and categorize posts within their WordPress site.

<?php /** * Conditional display of ACF field based on the current URL. */ function cwpai_conditional_acf_field_display($field) { // Get the current URL $current_url = $_SERVER['REQUEST_URI']; // Check if the URL is for the 'Add New...

WordPress 410 Status Code for 404 Pages

This file contains a WordPress function that changes the HTTP status code from 404 to 410 for pages that are not found. It's designed to inform search engines that the content is permanently removed, potentially improving SEO by preventing indexing of non-existent pages.

<?php /** * Sets the HTTP status code to 410 for 404 Not Found pages. * * This function checks if the current request resulted in a 404 error and, if so, * sets the HTTP status code to 410 (Gone). It should be attached to the...

WooCommerce Custom Delivery Checkout Fields

This file enhances the WooCommerce checkout process by adding custom fields for customers to select a preferred delivery date and to provide additional delivery instructions. It includes validation to ensure the date is in the future and sanitizes input data for security.

<?php /** * Enhances custom checkout fields for package delivery in WooCommerce. * This version registers fields for selecting a preferred delivery date and providing additional delivery instructions, such as gate codes or drop-off...

Require Phone Number for WooCommerce Subscriptions

This plugin enhances WooCommerce by requiring customers to provide a phone number when purchasing subscription products. Leveraging WooCommerce and Subscription extensions, it intelligently checks the cart contents and applies the requirement only when necessary, maintaining a smooth checkout process for other products.

<?php /** * Plugin Name: Require Phone Number for Subscriptions * Plugin URI: https://codewp.ai * Description: Makes the Phone Number field required only for subscription products. * Version: 1.0 * Author: CodeWP Assistant * Author URI:...

WordPress Auto-Logout Script

This file contains a set of functions that implement an automatic logout feature for 'customer' role users in WordPress after a period of inactivity. It uses JavaScript to track user activity and a WordPress AJAX action to handle the logout process securely.

<?php function cwpai_logout_script() { if (is_user_logged_in() && current_user_can('customer')) { $logout_time = 30; // Set the logout time in seconds $logout_nonce = wp_create_nonce('cwpai_logout_nonce'); $logout_url =...

CodeWP Ajax Search Plugin

The CodeWP Ajax Search Plugin provides a seamless search experience by integrating Ajax technology into WordPress. It enhances the default search by returning real-time results as users type, without the need for page reloads. The plugin is easily implementable via a shortcode and offers customizable assets for a cohesive look with your theme.

<?php /** * Plugin Name: CodeWP Ajax Search * Plugin URI: https://codewp.ai * Description: An advanced Ajax search solution for WordPress. * Version: 1.0.0 * Author: CodeWP Assistant * Author URI: https://codewp.ai * Text Domain: codewp ...

WooCommerce Demo Product Publisher

This file contains a WordPress function that automatically publishes a 'Demo' product to a WooCommerce shop upon initialization. It includes product details and ensures no duplicates by checking for an existing SKU.

<?php function cwpai_publish_demo_product() { $product_name = 'Demo'; $product_args = array( 'name' => $product_name, 'type' => 'simple', 'regular_price' => '100', 'description' => 'This is a demo...

User Profile Discount Field and Application

The PHP code provides functionality for adding a custom discount field to WordPress user profiles and applying the selected discount rate to WooCommerce product prices. It hooks into user profile display and save actions, as well as WooCommerce product price filters.

<?php /** * Adds a custom field (dropdown) for discounts in user profiles. */ function cwpai_add_user_discount_field($user) { // Check if $user is an object before trying to access its properties $user_id = is_object($user) ? $user->ID...

Gravity Forms Dynamic Price Modifier

This WordPress code snippet for Gravity Forms allows dynamic modification of product field prices based on form navigation. When a user reaches the second page of a multi-page form, it updates the price of a designated product field. This is useful for forms where pricing needs to adjust based on user input across different form pages.

<?php /** * Modify the value of a price field between pages in a multi-page Gravity Forms form. * * @param array $form The Gravity Forms form array. * @return array The modified form array. */ add_action('gform_pre_render',...

Disable Gutenberg for Custom Post Types

This WordPress file modifies the editor experience by disabling the Gutenberg editor for all custom post types, ensuring that only the classic editor is used. It maintains the use of the Gutenberg editor for standard posts, providing a selective experience based on the post type.

<?php function cwpai_disable_gutenberg_for_certain_post_types($can_edit, $post_type) { if ($post_type !== 'post') { return false; } return $can_edit; } add_filter('use_block_editor_for_post_type',...

Crypto Prices Dashboard Widget

This file adds a dashboard widget in WordPress that displays a table of cryptocurrency prices fetched from the CoinCap API. It enqueues Datatables assets for a responsive and interactive table experience and handles API errors gracefully.

<?php // Enqueue necessary Datatables CSS and JS function cwpai_enqueue_datatables_assets() { echo '<link rel="stylesheet" type="text/css" href="//cdn.datatables.net/2.0.7/css/dataTables.dataTables.min.css">'; echo '<script...

April Fools Admin Shuffle

This playful WordPress plugin introduces a button that shuffles the labels of links and buttons in the admin dashboard. It's a light-hearted April Fools' joke intended to bring a bit of fun to your admin area without affecting the site's functionality.

<?php /* Plugin Name: April Fools Admin Shuffle Description: Adds a button to the top of each WordPress admin page that shuffles the labels of links and buttons when clicked as an April Fools joke. Version: 1.0.0 Author: CodeWP Assistant...

user_chart_widget.php

The code provided is a WordPress plugin that adds a dashboard widget displaying user registrations over the past 7 days and over all time using Frappe Charts. The User Registration Charts Dashboard Widget plugin creates a class called UserRegistrationChartsWidget, which handles the functionality. The constructor of the class sets up hooks to enqueue the necessary scripts and add the dashboard widget. The display_widget method generates the necessary HTML and JavaScript code to render the bar chart for user registrations over the past 7 days and the line chart for user registrations over all time. The get_user_registrations method retrieves the user registration data from the WordPress database. Overall, this plugin provides a visual representation of user registrations for site administrators to track user growth.

<?php /* Plugin Name: User Registration Charts Dashboard Widget Description: This plugin adds a dashboard widget that displays user registrations over past 7 days with a bar chart and over all time with a line chart using Frappe Charts. Author:...

CodeWP Eleven Labs TTS Plugin

The CodeWP Eleven Labs TTS Plugin for WordPress allows site owners to integrate Eleven Labs' advanced Text-to-Speech technology into their website. Users can select from different voices and generate audio versions of their content, making their posts more accessible and engaging.

<?php /* Plugin Name: CodeWP Eleven Labs Text-to-Speech Integration Description: Integrate Eleven Labs Text-to-Speech into your WordPress site. Version: 1.4 Author: Your Name License: GPL2 */ if ( ! defined( 'ABSPATH' ) ) { exit; } class...

mandatory_cart_min.php

The provided PHP code creates a WordPress plugin, WooCommerce Mandatory Cart Minimum, which allows you to enforce a minimum cart total for WooCommerce checkout. This plugin adds an admin settings page where you can specify the minimum cart value. This is done using object-oriented programming (OOP) principles and WordPress hooks and functions. The plugin uses the 'woocommerce_check_cart_items' action hook to validate the cart total before checkout. If the cart total is less than the specified minimum, an error notice is added, and the checkout process is halted.

<?php /* Plugin Name: WooCommerce Mandatory Cart Minimum Description: Enforces a minimum cart total for WooCommerce checkout. Version: 1.0 Author: CodeWP */ if (!defined('ABSPATH')) exit; class WC_Mandatory_Cart_Minimum { private...

CodeWP - Code Snippets - AI Prompts & Code Snippets | Snippets AI