Notice: Function _load_textdomain_just_in_time was called incorrectly. Translation loading for the coder-elementor domain was triggered too early. This is usually an indicator for some code in the plugin or theme running too early. Translations should be loaded at the init action or later. Please see Debugging in WordPress for more information. (This message was added in version 6.7.0.) in /home/u262393194/domains/codestap.com/public_html/wp-includes/functions.php on line 6114

Notice: Function _load_textdomain_just_in_time was called incorrectly. Translation loading for the rank-math domain was triggered too early. This is usually an indicator for some code in the plugin or theme running too early. Translations should be loaded at the init action or later. Please see Debugging in WordPress for more information. (This message was added in version 6.7.0.) in /home/u262393194/domains/codestap.com/public_html/wp-includes/functions.php on line 6114

Notice: Function _load_textdomain_just_in_time was called incorrectly. Translation loading for the rocket domain was triggered too early. This is usually an indicator for some code in the plugin or theme running too early. Translations should be loaded at the init action or later. Please see Debugging in WordPress for more information. (This message was added in version 6.7.0.) in /home/u262393194/domains/codestap.com/public_html/wp-includes/functions.php on line 6114
WordPress - Code Stap
WordPress

Results for WordPress

4 posts available

How to Update Data in WordPress Database Using PHP with MySQL?
September 2, 2024

Updating data in a WordPress database using PHP with MySQL is a common task, especially when you need to modify existing data stored in the database. WordPress provides a safe and secure way to perform these operations using the $wpdb class, which is a global instance of the wpdb class. Below, I'll provide a detailed explanation along with a code example.

Step-by-Step Guide to Update Data in WordPress Database Using PHP

1. Access the $wpdb Object

The first step is to access the global $wpdb object, which is an instance of the wpdb class and allows you to interact with the WordPress database.

Example


global $wpdb;

2. Prepare the Table Name

It's important to get the correct table name. If you're working with custom tables, you might need to prefix the table name with the WordPress table prefix ($wpdb->prefix), which ensures that the code works regardless of the database prefix used during installation.

Example


$table_name = $wpdb->prefix . 'your_table_name';

3. Create the Data Array

Prepare an associative array where the keys are the column names, and the values are the new data you want to update.

Example


$data = array(
    'column1' => 'new_value1',
    'column2' => 'new_value2',
);

4. Create the Where Clause Array

The where clause is crucial as it determines which records should be updated. This is also an associative array where the keys are the column names used in the WHERE clause, and the values are the conditions.

Example


$where = array(
    'id' => 123,
);

5. Execute the Update Query

Use the update method of the $wpdb object to run the update query. This method takes three arguments:

  • The table name.
  • The data array (columns to be updated).
  • The where clause array (condition to match the row(s) to be updated).

Example


$wpdb->update( $table_name, $data, $where );

6. Handle the Result

The update method returns the number of rows affected by the query. You can use this value to check if the operation was successful.

Example


$rows_affected = $wpdb->update( $table_name, $data, $where );

if ( $rows_affected !== false ) {
    echo 'Update successful. Rows affected: ' . $rows_affected;
} else {
    echo 'Update failed.';
}

Full Code Example

Here's a complete example that updates a record in a custom table:

Example


<?php
// Include WordPress header to get access to the $wpdb object
require_once( dirname(__FILE__) . '/wp-load.php' );

// Access the global $wpdb object
global $wpdb;

// Define the table name
$table_name = $wpdb->prefix . 'your_table_name';

// Prepare the data to be updated
$data = array(
    'column1' => 'new_value1',
    'column2' => 'new_value2',
);

// Specify the condition (WHERE clause)
$where = array(
    'id' => 123,  // Update the row where id is 123
);

// Execute the update query
$rows_affected = $wpdb->update( $table_name, $data, $where );

// Check the result
if ( $rows_affected !== false ) {
    echo 'Update successful. Rows affected: ' . $rows_affected;
} else {
    echo 'Update failed.';
}
?>

Security Considerations

  • SQL Injection: The $wpdb->update() method is safe from SQL injection as it automatically escapes the values. However, always ensure that the data passed into these methods is sanitized.

  • Validation: Ensure that any data you update has been validated to avoid corrupting your database.

  • Backups: Before performing any database updates, it’s always a good practice to have a recent backup of your database in case something goes wrong.

Conclusion

Using the $wpdb class in WordPress allows you to safely and efficiently update records in your database. This method is particularly useful when working with custom tables or performing complex updates where you need fine control over the SQL queries.

Can't use SSL with wordpress NGINX
September 2, 2024

Expert [addtoany]

Sep '24

Using SSL with WordPress on an NGINX server can be tricky if not configured correctly. Below is a detailed guide on how to properly set up SSL with WordPress on NGINX, along with code examples.

Step 1: Obtain an SSL Certificate

You need an SSL certificate to enable HTTPS. You can obtain a free SSL certificate from Let's Encrypt, or you can purchase one from a Certificate Authority (CA).

Using Let's Encrypt with Certbot

To install Certbot and get an SSL certificate, follow these steps:

  1. Install Certbot:

Example


sudo apt-get update
sudo apt-get install certbot python3-certbot-nginx

Obtain the SSL Certificate:

Example


sudo certbot --nginx -d yourdomain.com -d www.yourdomain.com
  1. Replace yourdomain.com and www.yourdomain.com with your actual domain names.

  2. Follow the on-screen instructions to complete the installation. Certbot will automatically configure NGINX to use the SSL certificate.

Step 2: Configure NGINX for SSL

Once you have obtained the SSL certificate, you need to configure NGINX to use it.

  1. Edit Your NGINX Configuration File: Your configuration file is usually located in /etc/nginx/sites-available/yourdomain.com. Open it with a text editor:

Example


sudo nano /etc/nginx/sites-available/yourdomain.com

Modify the Server Block: Add the following configuration to your server block to enable SSL:

Example


server {
    listen 80;
    server_name yourdomain.com www.yourdomain.com;
    return 301 https://$host$request_uri;  # Redirect all HTTP requests to HTTPS
}

server {
    listen 443 ssl;
    server_name yourdomain.com www.yourdomain.com;

    ssl_certificate /etc/letsencrypt/live/yourdomain.com/fullchain.pem;
    ssl_certificate_key /etc/letsencrypt/live/yourdomain.com/privkey.pem;
    ssl_trusted_certificate /etc/letsencrypt/live/yourdomain.com/chain.pem;

    ssl_protocols TLSv1.2 TLSv1.3;
    ssl_prefer_server_ciphers on;
    ssl_ciphers "ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-GCM-SHA384";
    ssl_session_cache shared:SSL:10m;
    ssl_session_timeout 10m;
    ssl_session_tickets off;

    add_header Strict-Transport-Security "max-age=31536000; includeSubDomains" always;
    add_header X-Content-Type-Options nosniff;
    add_header X-Frame-Options DENY;
    add_header X-XSS-Protection "1; mode=block";

    root /var/www/yourdomain.com;
    index index.php index.html index.htm;

    location / {
        try_files $uri $uri/ /index.php?$args;
    }

    location ~ \.php$ {
        include snippets/fastcgi-php.conf;
        fastcgi_pass unix:/var/run/php/php7.4-fpm.sock;
        fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
        include fastcgi_params;
    }

    location ~ /\.ht {
        deny all;
    }
}

Test NGINX Configuration: Before restarting NGINX, test the configuration to ensure there are no errors:

Example


sudo nginx -t

Restart NGINX: If the test passes, restart NGINX to apply the changes:

Example


sudo systemctl restart nginx

Step 3: Update WordPress Configuration

To ensure WordPress uses HTTPS, you need to update a few settings.

  1. Update Site URL: Log in to your WordPress admin panel and go to Settings > General. Update the following fields:

    • WordPress Address (URL): https://yourdomain.com
    • Site Address (URL): https://yourdomain.com
  2. Force SSL in WordPress: To force SSL on your WordPress site, add the following lines to your wp-config.php file:

Example


define('FORCE_SSL_ADMIN', true);

if (strpos($_SERVER['HTTP_X_FORWARDED_PROTO'], 'https') !== false) {
    $_SERVER['HTTPS'] = 'on';
}

Step 4: Redirect HTTP to HTTPS

If you haven’t already added it in your NGINX configuration, you should add a redirect to ensure all HTTP requests are redirected to HTTPS. This is important for SEO and security.

In your NGINX configuration, ensure the following block exists:

Example


server {
    listen 80;
    server_name yourdomain.com www.yourdomain.com;
    return 301 https://$host$request_uri;
}

Step 5: Test SSL Configuration

  1. Check SSL Certificate: Use an online tool like SSL Labs to check your SSL configuration and ensure everything is working correctly.

  2. Verify HTTPS: Visit your site using https://yourdomain.com to ensure that everything is loading over HTTPS. You should see a padlock icon in your browser's address bar.

Step 6: Set Up Automatic SSL Renewal (Optional)

If you're using Let's Encrypt, you'll want to ensure your SSL certificates renew automatically.

  1. Check Certbot Renewal Process: Certbot usually installs a cron job to renew the certificates automatically. You can verify it by running:

Example


sudo certbot renew --dry-run

Set Up a Cron Job (if needed): If it's not set up automatically, you can create a cron job to renew your certificates by running:

Example


sudo crontab -e

Add the following line to the crontab:

Example


0 0 * * * /usr/bin/certbot renew --quiet

Troubleshooting Common Issues

  1. Mixed Content Warnings: If you see mixed content warnings, it means some assets (images, scripts, etc.) are still being served over HTTP. Use a plugin like Really Simple SSL or manually update the links in your content.

  2. SSL Not Working After Configurations: Double-check the file paths for your SSL certificates in the NGINX configuration. Ensure that your DNS records are correctly pointing to your server.

  3. Permission Issues: Ensure that NGINX has the correct permissions to read the SSL certificate files.

Conclusion

By following these steps, you should have SSL properly set up on your WordPress site using NGINX. This will help secure your site and improve SEO rankings by serving content over HTTPS.

How to change YITH subscription reccuring price on WooCommerce cart
September 2, 2024

Expert [addtoany]

Sep '24

To change the recurring price of a YITH Subscription on the WooCommerce cart using code, you'll need to tap into WooCommerce and YITH Subscription hooks and filters. Here’s a detailed guide on how to achieve this:

Steps to Change the Recurring Price in WooCommerce Cart

  1. Understand the Structure:

    • YITH WooCommerce Subscription plugin creates subscription products with recurring prices.
    • You need to target the recurring price in the cart and adjust it as necessary.
  2. Add Custom Code to Your Theme:

    • You should add custom code to your theme's functions.php file or create a custom plugin to avoid losing changes when updating the theme.
  3. Use Filters to Modify the Recurring Price:

    • Use hooks provided by WooCommerce and YITH to modify the recurring price.

Code Example

Here’s a code example to modify the recurring price for YITH Subscription products in the WooCommerce cart:

Example


add_action('woocommerce_before_calculate_totals', 'change_recurring_price_in_cart', 20, 1);

function change_recurring_price_in_cart($cart) {
    // Check if cart is empty
    if (is_admin() && !defined('DOING_AJAX')) return;

    // Loop through cart items
    foreach ($cart->get_cart() as $cart_item_key => $cart_item) {
        // Check if item is a subscription product
        if (isset($cart_item['data']) && $cart_item['data'] instanceof WC_Product_Subscription) {
            $product = $cart_item['data'];

            // Get the current subscription price
            $subscription_price = $product->get_price();

            // Calculate the new recurring price
            $new_recurring_price = $subscription_price * 1.2; // For example, increase by 20%

            // Set the new price for the cart item
            $cart_item['data']->set_price($new_recurring_price);
        }
    }
}

Explanation of the Code

  1. Hook into WooCommerce Cart Calculation:

    • woocommerce_before_calculate_totals: This hook runs before the cart totals are calculated. It's a suitable place to modify item prices before they are displayed or processed.
  2. Check if Cart is Empty:

    • Ensures that the code doesn’t run in the admin area or during AJAX requests.
  3. Loop Through Cart Items:

    • Loop through each item in the cart to check if it’s a subscription product.
  4. Check if Product is a Subscription:

    • Use instanceof WC_Product_Subscription to verify that the product is a subscription.
  5. Modify the Recurring Price:

    • Retrieve the current subscription price and apply your custom logic to calculate the new price.
    • Use $cart_item['data']->set_price($new_recurring_price); to set the new price.

Additional Considerations

  • Testing: Make sure to test the code thoroughly in a staging environment before deploying it to production.
  • Backup: Always back up your site before making changes to the code.
  • Custom Plugin: For easier management and future updates, consider placing this code into a custom plugin rather than adding it to the theme’s functions.php.

This example shows a simple way to modify recurring prices, but you can adapt the logic to meet more complex requirements or pricing rules as needed.

How to set the Woocommerce shop page in a way that user cannot see the contents that are updated in the product?
September 2, 2024

Expert [addtoany]

Sep '24

To achieve a WooCommerce setup where users cannot see the contents that are updated in a product, you'll need to implement some custom logic. The goal here is to hide or restrict access to updated product details until certain conditions are met, such as approval or a specific status.

Here’s a detailed approach on how to accomplish this:

1. Add a Custom Product Status

First, you'll need to add a custom product status that you can use to mark products as “hidden” or “under review” until they are ready to be visible.

Add the following code to your theme’s functions.php file or a custom plugin:

Example


// Add a custom product status
function register_custom_product_status() {
    register_post_status('wc-hidden', array(
        'label'                     => _x('Hidden', 'Product status', 'woocommerce'),
        'public'                    => false,
        'exclude_from_search'       => true,
        'show_in_admin_all_list'    => true,
        'show_in_admin_status_list' => true,
        'label_count'               => _n_noop('Hidden <span class="count">(%s)</span>', 'Hidden <span class="count">(%s)</span>', 'woocommerce')
    ));
}
add_action('init', 'register_custom_product_status');

// Add custom status to the product status dropdown
function add_custom_product_status($statuses) {
    $statuses['wc-hidden'] = _x('Hidden', 'Product status', 'woocommerce');
    return $statuses;
}
add_filter('wc_product_statuses', 'add_custom_product_status');

2. Hide Products with Custom Status from Shop Page

To ensure that products with the “hidden” status do not appear on the shop page, use the following code in your functions.php file or custom plugin:

Example


// Exclude products with the 'hidden' status from the shop page
function exclude_hidden_products($query) {
    if (!is_admin() && $query->is_main_query() && is_post_type_archive('product')) {
        $query->set('post_status', array('publish')); // Only show published products
        $query->set('meta_query', array(
            array(
                'key'     => '_stock_status',
                'value'   => 'hidden',
                'compare' => '!='
            )
        ));
    }
}
add_action('pre_get_posts', 'exclude_hidden_products');

3. Control Product Visibility on the Single Product Page

To prevent users from seeing products with the “hidden” status on their individual product pages, use the following code:

Example


// Redirect users if they try to view a hidden product
function redirect_hidden_products() {
    if (is_product()) {
        global $post;
        if ('wc-hidden' === get_post_status($post->ID)) {
            wp_redirect(home_url()); // Redirect to the homepage or a custom URL
            exit;
        }
    }
}
add_action('template_redirect', 'redirect_hidden_products');

4. Manage Product Status in the Admin Panel

Make sure you can manage the new status in the admin product editing screen. Here’s how you can add the custom status to the bulk actions dropdown:

Example


// Add custom status to bulk actions
function add_custom_bulk_actions($actions) {
    $actions['mark_hidden'] = __('Mark as Hidden', 'woocommerce');
    return $actions;
}
add_filter('bulk_actions-edit-product', 'add_custom_bulk_actions');

// Handle bulk action
function handle_custom_bulk_actions($redirect, $action, $post_ids) {
    if ($action === 'mark_hidden') {
        foreach ($post_ids as $post_id) {
            $product = wc_get_product($post_id);
            $product->set_status('wc-hidden');
            $product->save();
        }
        $redirect = add_query_arg('marked_hidden', count($post_ids), $redirect);
    }
    return $redirect;
}
add_filter('handle_bulk_actions-edit-product', 'handle_custom_bulk_actions', 10, 3);

5. Add Custom Messages for Bulk Actions

Provide feedback to the admin when they perform a bulk action:

Example


// Add custom notice after bulk actions
function custom_bulk_action_notice() {
    if (isset($_GET['marked_hidden'])) {
        $count = intval($_GET['marked_hidden']);
        printf('<div id="message" class="updated notice is-dismissible"><p>' . _n('%s product marked as hidden.', '%s products marked as hidden.', $count, 'woocommerce') . '</p></div>', $count);
    }
}
add_action('admin_notices', 'custom_bulk_action_notice');

Summary

In summary, this setup involves:

  1. Adding a Custom Product Status: To mark products as hidden or under review.
  2. Modifying Query: To exclude products with the hidden status from the shop page.
  3. Redirecting Users: To ensure hidden products are not visible on their individual product pages.
  4. Managing Status: Allowing administrators to manage the custom status through bulk actions.
  5. Providing Feedback: Notifying administrators about bulk actions.

This approach ensures that products marked with a custom status do not appear on the shop page or individual product pages, thus keeping updated product contents hidden from users.