See Coding offers easy, practical solutions in PHP, CSS, Magento, WordPress, JavaScript, jQuery, and more. Our content is designed to simplify coding concepts, providing tips and step-by-step guides to help developers of all levels enhance their coding skills. With a focus on real-world applications, we cover debugging, optimization, and best practices, keeping you updated on the latest in the field. Whether you’re a beginner or an experienced coder, See Coding is here to support your learning.
If we want to change text-decoration in anchot tag.
Default text-decoration comes text-decoration: underline; if you want to remove
unaderline, we have to use text-decoration: none; is our css. Like below
How can we do the Collapsible Nested Sub Menu Items on Divi’s Mobile Menu ?
Solution:
Default DIVI mobile menu is shown in the image as below.
If we have to just use the below CSS and script in our site.
We can put below CSS and JS script going to WP-admin ->Divi Theme Options -> Integrations -> Add code to the body .
Or In child-theme (if you are using) style and js/script file.
We can do this using vey easy code. Below is the code to nerate random 5 characters string.
$seed = str_split('abcdefghijklmnopqrstuvwxyz'
.'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
.'0123456789!@#$%^&*()'); // and any other characters
shuffle($seed); // probably optional since array_is randomized; this may be redundant
$rand = '';
foreach (array_rand($seed, 5) as $k) $rand .= $seed[$k];
echo $rand;
The best solution I found was to override the ORDER BY for the query by calling a primitive method of the Collection class, here's the example they give:
$_productCollection = Mage::getModel('catalog/product')->getCollection();
$_productCollection->setOrder('weight', 'asc');
$_productCollection->getSelect()->reset(Zend_Db_Select::ORDER);
$_productCollection->getSelect()->order('CAST(`weight` AS SIGNED) ASC'));
STEP 2. Put the bellow code in functions.php in your theme file.
function my_ajax_callback_function()
{
print_r($_REQUEST);
}
add_action( 'wp_ajax_my_action_name', 'my_ajax_callback_function' ); // If called from admin panel
add_action( 'wp_ajax_nopriv_my_action_name', 'my_ajax_callback_function' ); // If called from front end
STEP 3. Make sure jquery libarary has been included for the page.
function create_slug($string){
$slug=preg_replace('/[^A-Za-z0-9-]+/', '-', $string);
return $slug;
}
echo create_slug('does this thing work or not');
//returns 'does-this-thing-work-or-not'
1. First create a controller. Suppose controller name is "test".
put this code here action name is "name".
class namespace_modulename_TestController extends Mage_Core_Controller_Front_Action{
public function nameAction()
{
$this->loadLayout();
$this->renderLayout();
}
}
2. After controller creation set layout go to design->template->layou open the xml file
put these code
page/1column.phtml
3. and last send request for controller "modulname/controller/actionname".
print the all data of test.phtml file.
You need to replace one line of code in your controller
where you want to change the layout of the page if you are not
able to do from xml through setlayout.
Mysql query to get all products images count in particular category
Below is mysql query to get all products images count in particular category
select count(*) from `catalog_product_entity_media_gallery` as t1 join `catalog_category_product` as t2 on t1.entity_id = t2.product_id
where t2.category_id = 3 and t1.attribute_id=88
In PHP, there are three types of runtime errors, they are:
Warnings:
These are important errors. Example: When we try to include () file which is not available. These errors are showed to the user by default but they will not result in ending the script.
Notices:
These errors are non-critical and trivial errors that come across while executing the script in PHP. Example: trying to gain access the variable which is not defined. These errors are not showed to the users by default even if the default behavior is changed.
Fatal errors: These are critical errors. Example: instantiating an object of a class which does not exist or a non-existent function is called. These errors results in termination of the script immediately and default behavior of PHP is shown to them when they take place. Twelve different error types are used to represent these variations internally.
1. One of the most amazing features about Magento is that you can design and
develop multiple web sites and they store and share one administrative interface.
This extremely flexible feature allows you to modify and control multiple web
sites. All of your products inventory and pricing can be controlled from one
central location. There is no longer a need to login to multiple locations to handle
multiple web sites. Magento has the ability to control them all.
2. Magento supports over sixty languages, multiple currencies, and tax rates. This
gives you the ability to easily expand in the global market.
3. Layered navigation gives users customized browsing options when viewing
products by categories. You can now sort products by price, size, color, and other
customizable attributes. 4. Magento also has built-in web services. This flexibility allows external applications
to access magento’s data without changing the underlying core code. Currently,
SOAP and XML-RPC protocols are available out of the box.
5. Magento has Search Engine Optimization (SEO) built in from the start. It has the
ability to handle friendly URL rewrites which make it easy for search engines to
index your store and products.
6. Not only does Magento offer real-time carrier rates and quotes, users can ship
products from one order to multiple shipping address. This makes gift shopping
especially easy.
7. Magento also has several reporting features built in. These allows for easy view of
sales reports, best-selling products, and customer reporting. They can even be
exported in a CSV format to integrate with excel and other database programs.
8. Magento has designed its file structure to three major sections: core, functionality,
and design. This allows for easy updating of images and CSS styling without
affecting the functionality of the site. Store functionality can also be easily
customized without affecting the Magento’s core. As a result, you can modify
Magento without having to worry about upgrading to newer versions in the future.
9. Magento has a huge community backing. In addition to a public forum and bug
tracking, Magento also has its own public repository of extensions called Magento
Connect. Magento Connect features both free and commercial extensions
to enhance the functionality of your web site.
10. Since Magento is released under the Open Software License (OSL), the Magento
Community Edition is available at no cost. In turn, this allows web site developers
and eCommerce web site owners to cut down on software costs.
But normally we would like to separate HTML and Javascript, so we don't use inline event handlers, but put a class on our link and add an event listener to it.
var elems = document.getElementsByClassName('confirmation');
var confirmIt = function (e) {
if (!confirm('Are you sure?')) e.preventDefault();
};
for (var i = 0, l = elems.length; i < l; i++) {
elems[i].addEventListener('click', confirmIt, false);
}
By jQuery
Just for fun, here is how this would look with jQuery
function initialize() {
var input = document.getElementById('searchTextField');
var autocomplete = new google.maps.places.Autocomplete(input);
}
google.maps.event.addDomListener(window, 'load', initialize);
Magento has inbuilt model for Country and State as seen in Checkout page.
In checkout page if you select Country like ‘France’ , a drop down will be seen in place of textbox for States.
I am writing here the code to directly get country name from ID and also to get States info from country.
$countryName = Mage::getModel('directory/country')->load('FR')->getName(); //get country name
echo 'Country Name ->'.$countryName.' ';
$states = Mage::getModel('directory/country')->load('FR')->getRegions();
//state names
foreach ($states as $state)
{
echo 'ID->'.$state->getId().' ';
echo 'Name->'.$state->getName().' ';
}
The first step in creating custom columns, is to make these columns available on the edit posts page. WordPress has a variable filter hook for this called manage_edit-{$post_type}_columns for all post types. Since the name of our post type is movie, the name of the hook you’d use is manage_edit-movie_columns.
What we’ll do here is overwrite all of the default columns and set it up however we want. In this example, we’re using five columns:
1. cb: The checkbox column.
2. title: The post title column, which we’re changing to read “Movie.”
3. duration: The column for the duration of the movie (custom metadata).
4. family: The column for the movie family (custom taxonomy).
5. date: The default post date column.
Filtering these columns is fairly simple. You only need to return an array of key/value pairs. The key is the column name and the value is the output of the column header/label.
The action hook in this case is manage_{$post_type}_posts_custom_column. Remember, the name of the post type is movie, so this hook becomes manage_movie_posts_custom_column.
add_action( 'manage_movie_posts_custom_column', 'my_manage_movie_columns', 10, 2 );
function my_manage_movie_columns( $column, $post_id ) {
global $post;
switch( $column ) {
/* If displaying the 'duration' column. */
case 'duration' :
/* Get the post meta. */
$duration = get_post_meta( $post_id, 'duration', true );
/* If no duration is found, output a default message. */
if ( empty( $duration ) )
echo __( 'Unknown' );
/* If there is a duration, append 'minutes' to the text string. */
else
printf( __( '%s minutes' ), $duration );
break;
/* If displaying the 'family' column. */
case 'family' :
/* Get the familys for the post. */
$terms = get_the_terms( $post_id, 'family' );
/* If terms were found. */
if ( !empty( $terms ) ) {
$out = array();
/* Loop through each term, linking to the 'edit posts' page for the specific term. */
foreach ( $terms as $term ) {
$out[] = sprintf( '%s',
esc_url( add_query_arg( array( 'post_type' => $post->post_type, 'family' => $term->slug ), 'edit.php' ) ),
esc_html( sanitize_term_field( 'name', $term->name, $term->term_id, 'family', 'display' ) )
);
}
/* Join the terms, separating them with a comma. */
echo join( ', ', $out );
}
/* If no terms were found, output a default message. */
else {
_e( 'No familys' );
}
break;
/* Just break out of the switch statement for everything else. */
default :
break;
}
}
Step 3. (If you want to ) Making custom columns sortable
The first step is making the duration column sortable by filtering the manage_edit-{$post_type}_sortable_columns hook as shown in the following code.
add_filter( 'manage_edit-movie_sortable_columns', 'my_movie_sortable_columns' );
function my_movie_sortable_columns( $columns ) {
$columns['duration'] = 'duration';
return $columns;
}
/* Only run our customization on the 'edit.php' page in the admin. */
add_action( 'load-edit.php', 'my_edit_movie_load' );
function my_edit_movie_load() {
add_filter( 'request', 'my_sort_movies' );
}
/* Sorts the movies. */
function my_sort_movies( $vars ) {
/* Check if we're viewing the 'movie' post type. */
if ( isset( $vars['post_type'] ) && 'movie' == $vars['post_type'] ) {
/* Check if 'orderby' is set to 'duration'. */
if ( isset( $vars['orderby'] ) && 'duration' == $vars['orderby'] ) {
/* Merge the query vars with our custom variables. */
$vars = array_merge(
$vars,
array(
'meta_key' => 'duration',
'orderby' => 'meta_value_num'
)
);
}
}
return $vars;
}
Now, we have the code in place which will fetch the most viewed products on call. Still, we need to add a block to show most viewed products in a desired location.
Create a file app/code/local/Mage/Catalog/Block/Product/Bestseller.php and the following lines of code in it
class Mage_Catalog_Block_Product_Bestseller extends Mage_Catalog_Block_Product_Abstract{
public function __construct(){
parent::__construct();
$storeId = Mage::app()->getStore()->getId();
$products = Mage::getResourceModel('reports/product_collection')
->addOrderedQty()
->addAttributeToSelect('*')
->addAttributeToSelect(array('name', 'price', 'small_image'))
->setStoreId($storeId)
->addStoreFilter($storeId)
->setOrder('ordered_qty', 'desc'); // most best sellers on top
Mage::getSingleton('catalog/product_status')->addVisibleFilterToCollection($products);
Mage::getSingleton('catalog/product_visibility')->addVisibleInCatalogFilterToCollection($products);
$products->setPageSize(3)->setCurPage(1);
$this->setProductCollection($products);
}
}
Step 2:
Create a file app/design/frontend/default/YourTheme/template/catalog/product/bestseller.phtml file and add the following lines of code in it
<?php if (($_products = $this->getProductCollection()) && $_products->getSize()): ?>
This above files will create a list of best selling products which can be shown anywhere on your Magento store. All you have to do is place the following line of code block in your template to show the best selling products.
Hooks are provided by WordPress to allow your plugin to 'hook into' the rest of WordPress, i.e., to call functions in your plugin at specific times, and thereby set your plugin in motion. There are two kinds of hooks:
Actions Hooks: Actions hooks are the hooks that the WordPress core launches at specific points during execution, or when specific events occur. Your plugin can specify that one or more of its PHP functions which are executed at these points, using the Action API.
Filters Hooks: Filters hooks are the hooks that WordPress launches to modify text of various types before adding it to the database or sending it to the browser screen. Your plugin can specify that one or more of its PHP functions which are executed to modify specific types of text at these times, using the Filter API.
Actions Function Examples:
has_action()
add_action()
do_action()
do_action_ref_array()
did_action()
remove_action()
remove_all_actions()
When we are submitting a form with fields username/email and password.
We have to login if user exist and register as new user if there user does not exist.
Below is the code which will help to fulfill our requirement.
global $wpdb;
$email = $_REQUEST['email'];
$password = $_REQUEST['password'];
// Function to login- If user exists
if( email_exists( $email )) {
$user = get_user_by( 'email', $email );
$user_id= $user->ID;
if ( $user && wp_check_password( $password, $user->data->user_pass, $user->ID) ){
$secure_cookie = is_ssl();
$secure_cookie = apply_filters('secure_signon_cookie', $secure_cookie, array());
global $auth_secure_cookie;
$auth_secure_cookie = $secure_cookie;
wp_set_auth_cookie($user_id, true, $secure_cookie);
$user_info = get_userdata($user_id);
do_action('wp_login', $user_info->user_login, $user_info);
$msg= 'You are logged In successfully.';
}else{
$msg= 'Username / Password is wrong. Please try again.';
}
exit($msg);
}else{
// Function to Register - If user does not exists
$username = explode("@", $email);
$username = sanitize_text_field( $username[0] );
$email = sanitize_text_field( $_REQUEST['email'] );
$password = $wpdb->escape( sanitize_text_field( $password));
$status = wp_create_user($username,$password,$email);
$user_id=$status;
update_user_meta( $user_id,'first_name', $username); //update user meta
//autologin start
$secure_cookie = is_ssl();
$secure_cookie = apply_filters('secure_signon_cookie', $secure_cookie, array());
global $auth_secure_cookie;
$auth_secure_cookie = $secure_cookie;
wp_set_auth_cookie($user_id, true, $secure_cookie);
$user_info = get_userdata($user_id);
do_action('wp_login', $user_info->user_login, $user_info);
//autologin end
exit('User is created successfully.');
}
How can we use WPDB Class To Connect and Fetch Data From Another Database?
Solution:
Let us say we have installed wordpress into the database wp_wordpress and we want to fetch some data from another independent database which has nothing to do with wordpress .
Here is how you can do it.
Query to Data Using WPDB
If we have used the wordpress global variable $wpdb before, querying for data is nothing different from what we have done previously.
Now, here is the trick. we have to instantiate a new WPDB instance.
$mydb = new wpdb('username','password','database','localhost');
$rows = $mydb->get_results("select Name from my_table");
echo "
";
foreach ($rows as $obj) :
echo "
".$obj->Name."
";
endforeach;
echo "
";
The benefit is the ability to use all the wpdb classes and functions like get_results, etc so that there's no need to re-invent the wheel.