Magento Engineer
social
Wordpress

Wordpress

The industry's top wizards and other experts share their advice and research findings.

Create wprdpress posts by csv with featured image by code.

<?php
// Include WordPress bootstrap file
require_once 'wp-load.php';

// Path to your CSV file
$csv_file = '1.csv';

// Function to download and attach the image to the post
function attach_featured_image($post_id, $image_url) {
    // Download the image from the URL
    $image_contents = file_get_contents($image_url);
    
    if ($image_contents !== false) {
        // Get the filename from the URL
        $filename = basename($image_url);
        
        // Upload the image to the WordPress media library
        $upload = wp_upload_bits($filename, null, $image_contents);
        
        if (!$upload['error']) {
            // Prepare the attachment data
            $attachment_data = array(
                'post_mime_type' => $upload['type'],
                'post_parent' => $post_id,
                'post_title' => sanitize_file_name(pathinfo($filename, PATHINFO_FILENAME)),
                'post_content' => '',
                'post_status' => 'inherit'
            );
            // Insert the attachment into the database
            $attach_id = wp_insert_attachment($attachment_data, $upload['file']);
            // Set the featured image
            if (!is_wp_error($attach_id)) {
                set_post_thumbnail($post_id, $attach_id);
                return true;
            } else {
                return false;
            }
        }
    }
    return false;
}




// Open the CSV file for reading
if (($handle = fopen($csv_file, 'r')) !== false) {
    // Loop through each row in the CSV file
    while (($data = fgetcsv($handle, 1000, ',')) !== false) {
        // Extract data from CSV row
        $post_title    = $data[0]; // Assuming first column is post title        
        $custom_field1 = $data[1]; // Assuming fourth column is custom field 1 value
        $custom_field2 = $data[2]; // Assuming fifth column is custom field 2 value
        $custom_field3 = $data[3]; // Assuming fifth column is custom field 2 value
        $custom_field4 = $data[4]; // Assuming fifth column is custom field 2 value
        $image_url     = $data[5]; // Assuming third column is image URL
        $post_content  = $data[6]; // Assuming second column is post content        
        
        // Add more custom fields as needed
        //title   seo_title   seo_description keyword published_at    featured_image  content

        // Create post array with custom fields

        $existing_post = get_page_by_title($post_title, OBJECT, 'post');

        if ($existing_post) {
                    // Post already exists, update the post content and featured image
                    $post_id = $existing_post->ID;
                    $post_data = array(
                        'ID'           => $post_id,
                        'post_content' => $post_content,
                    );
                    wp_update_post($post_data);

                    // Attach featured image if URL is provided
                    if (!empty($image_url) && !is_wp_error($post_id)) {
                        attach_featured_image($post_id, $image_url);
                    }
                    
                    echo "Post updated: $post_title<br>";
                } else {

                    $new_post = array(
                        'post_title'   => $post_title,
                        'post_content' => $post_content,
                        // Add more fields as needed
                        'post_status'  => 'publish', // You can change post status if needed
                        'post_author'  => 1, // Change the author ID if needed
                        'post_type'    => 'post', // Change the post type if needed
                        'meta_input'   => array(
                            'seo_title'       => $custom_field1,
                            'seo_description' => $custom_field2,
                            'keyword'         => $custom_field3,
                            'published_at'    => $custom_field4,
                            'featured_img'    => $image_url,
                            // Add more custom fields as needed
                        ),
                    );
                }

        // Insert the post into the database
        $post_id = wp_insert_post($new_post);

        // Attach featured image if URL is provided
        if (!empty($image_url) && !is_wp_error($post_id)) {
            attach_featured_image($post_id, $image_url);
        }
        // Handle errors if any
        if (is_wp_error($post_id)) {
            $errors = $post_id->get_error_messages();
            foreach ($errors as $error) {
                echo $error . '<br>';
            }
        }
    }
    // Close the CSV file
    echo "CSV uploaded successfully!";
    fclose($handle);
} else {
    echo 'Error opening CSV file';
}
?>

Ad comes here

How to Move Your Blog/Website from WordPress.com to WordPress.org?

Many beginners often start with WordPress.com, but they soon realize its limitations and want to switch to the self-hosted WordPress.org platform.

In this step by step guide, we’ll show you how to properly move your blog from WordPress.com to WordPress.org.

Step1 - Login in the wordpress.com admin.
Step2 - Check "All-in-One WP Migration" from left sidebar and if it is not availble in your website then ping to  WordPress.com support team to add this.

Step3 - Open All-in-One WP Migration and click on export.

Step4 - Here you will see multiple export options, now choose FILE.
Step5 - Download will be started.

Step6 - The exported file will be in "wpress" format.
Step7 - Now run below command to extract and you will get Database and all wordpress files including plugin,theme,uploads.
Command: npx wpress-extract migration.wpress

Step8- Change wp-config.php and URL's from database and upload on new server.

That's it.
:) Enjoy

Ad comes here
Ad comes here

How do I add a external CDN CSS OR jQuery in WordPress theme header?

Rather then loading the stylesheet in your header.php file, you should load it in using wp_enqueue_style. In order to load your main stylesheet, you can enqueue it in functions.php

function bootstarp_to_head() {
    echo "<link href='https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css' rel='stylesheet' type='text/css'>";
}
add_action( 'wp_head', 'bootstarp_to_head' );

This will includes in theme header.

Ad comes here

How do I add a custom stylesheet in WordPress?

Rather then loading the stylesheet in your header.php file statically, you should load it in using wp_enqueue_style. In order to load your main stylesheet, you can enqueue it in functions.php

function theme_styles()  
{
    wp_register_style( 'responsive', get_template_directory_uri() . '/assets/css/responsive.css' );
    wp_enqueue_style('responsive');
    
}
add_action('wp_enqueue_scripts', 'theme_styles');

Ad comes here

How to create wordpress theme?

Introduction to WordPress Theme Development.

Create theme directory under the wordpress wp-content theme folder.
e.g Theme Name : developer
Now add basic files in the theme folder.
index.php
style.css
page.php

Above are very basic files to create wordpress theme.

Below are the some other files to improve your theme functioanlity.
header.php
footer.php
page.php
single.php
functions.php
404.php
screenshot.png

Using these template files you can put template tags within the index.php master file to include these other files where you want them to appear in the final generated page.

To include the header, use get_header().
To include the sidebar, use get_sidebar().
To include the footer, use get_footer().
To include the search form, use get_search_form().

Most Action Hooks are within the core PHP code of WordPress, so your Theme does not have to have any special tags for them to work. But a few Action Hooks do need to be present in your Theme, in order for Plugins to display information directly in your header, footer, sidebar, or in the page body. Here is a list of the special Action Hook Template Tags you need to include:

wp_enqueue_scripts
Used in the theme functions file. Used to load external scripts and stylesheets.

wp_head()
Goes in the <head> element of a theme, in header.php. Example plugin use: add JavaScript code.

wp_footer()
Goes in footer.php, just before the closing </body> tag. Example plugin use: insert PHP code that needs to run after everything else, at the bottom of the footer. Very commonly used to insert web statistics code, such as Google Analytics.

wp_meta()
Typically goes in the <li>Meta</li> section of a Theme's menu or sidebar; sidebar.php template. Example plugin use: include a rotating advertisement or a tag cloud.

comment_form()
Goes in comments.php directly before the file's closing tag (</div>). Example plugin use: display a comment preview.

Ad comes here

WooCommerce: Easily Get Product Info (ID, SKU, $) from $product Object

1. You have access to $product
You can declare the “global $product” inside your function.
// Get Product ID
 
$product->get_id(); (fixes the error: "Notice: id was called incorrectly. Product properties should not be accessed directly")
 
// Get Product General Info
 
$product->get_type();
$product->get_name();
$product->get_slug();
$product->get_date_created();
$product->get_date_modified();
$product->get_status();
$product->get_featured();
$product->get_catalog_visibility();
$product->get_description();
$product->get_short_description();
$product->get_sku();
$product->get_menu_order();
$product->get_virtual();
get_permalink( $product->get_id() );
 
// Get Product Prices
 
$product->get_price();
$product->get_regular_price();
$product->get_sale_price();
$product->get_date_on_sale_from();
$product->get_date_on_sale_to();
$product->get_total_sales();
 
// Get Product Tax, Shipping & Stock
 
$product->get_tax_status();
$product->get_tax_class();
$product->get_manage_stock();
$product->get_stock_quantity();
$product->get_stock_status();
$product->get_backorders();
$product->get_sold_individually();
$product->get_purchase_note();
$product->get_shipping_class_id();
 
// Get Product Dimensions
 
$product->get_weight();
$product->get_length();
$product->get_width();
$product->get_height();
$product->get_dimensions();
 
// Get Linked Products
 
$product->get_upsell_ids();
$product->get_cross_sell_ids();
$product->get_parent_id();
 
// Get Product Variations
 
$product->get_attributes();
$product->get_default_attributes();
 
// Get Product Taxonomies
 
$product->get_categories();
$product->get_category_ids();
$product->get_tag_ids();
 
// Get Product Downloads
 
$product->get_downloads();
$product->get_download_expiry();
$product->get_downloadable();
$product->get_download_limit();
 
// Get Product Images
 
$product->get_image_id();
get_the_post_thumbnail_url( $product->get_id(), 'full' );
$product->get_gallery_image_ids();
 
// Get Product Reviews
 
$product->get_reviews_allowed();
$product->get_rating_counts();
$product->get_average_rating();
$product->get_review_count();
 
// source: https://docs.woocommerce.com/wc-apidocs/class-WC_Product.html


2. You have access to $product_id

If you have access to the product ID (once again, usually the do_action or apply_filters will make this possible to you), you have to get the product object first. Then, do the exact same things as above.
// Get $product object from product ID
 
$product = wc_get_product( $product_id );
 
// Now you have access to (see above)...
 
$product->get_type();
$product->get_name();
// etc.
// etc.


3. You have access to the Order object or Order ID

How to get the product information inside the Order? In this case you will need to loop through all the items present in the order, and then apply the rules above.
// Get $product object from $order / $order_id
 
$order = new WC_Order( $order_id );
$items = $order->get_items();
 
foreach ( $items as $item ) {
 
    $product = wc_get_product( $item['product_id'] );
 
    // Now you have access to (see above)...
 
    $product->get_type();
    $product->get_name();
    // etc.
    // etc.
 
}


4. You have access to the Cart object

How to get the product information inside the Cart? In this case, once again, you will need to loop through all the items present in the cart, and then apply the rules above.
// Get $product object from Cart object
 
$cart = WC()->cart->get_cart();
 
foreach( $cart as $cart_item ){
 
    $product = wc_get_product( $cart_item['product_id'] );
 
    // Now you have access to (see above)...
 
    $product->get_type();
    $product->get_name();
    // etc.
    // etc.
 
}






Ad comes here

How to get all posts from the specific / single category of custom post types in Wordpress ?

<div class="custom-post-entry">
    <?php query_posts( 'post_type=story&category_name=winner'); ?>       
    <?php if ( have_posts() ) while ( have_posts() ) : the_post(); ?>  
    <?php //get_template_part( 'content', 'page' ); ?>
    <?php get_template_part( 'content', get_post_format() ); ?>
    <?php comments_template( '', true ); ?>
    <div class="clear"></div>
</div><!--post-entry end-->
<?php endwhile; ?>

Ad comes here

Wordpress interview important question and answers.

Question1- What are the template tags in WordPress?

Answer. A template tag is code that instructs WordPress to “do” or “get” something. Like in header.php  we will use the tag bloginfo(‘name’) to get “Site Title” from wp-options table which is set in Setting > General at WordPress dashboard.

The the_title() template tag is used to display the post title.

wp_list_cats() is  for display categories.

get_header() for getting header.

get_sidebar() for display the sidebar on page.

get_footer() for get the footer content on page.


Question2- What do next_posts_link() and previous_posts_link() do?

Answer. Because post queries are usually sorted in reverse chronological order, next_posts_link() usually points to older entries (toward the end of the set) and previous_posts_link() usually points to newer entries (toward the beginning of the set).

Question3- How to retrieve an image attachment’s alt text?

Answer. The wp_get_attachment_image() function which will return an HTML string containing these attributes:

    1.src
    2.class
    3.alt
    4.title

Ad comes here

How to register custom post type in Wordpress ?

Write this code in your function.php file.

function my_custom_post_homepage() {
    $labels = array(
        'name'               => _x( 'Homepage', 'post type general name' ),
        'singular_name'      => _x( 'Homepage', 'post type singular name' ),
        'add_new'            => _x( 'Add New', 'news' ),
        'add_new_item'       => __( 'Add New Homepage' ),
        'edit_item'          => __( 'Edit Homepage' ),
        'new_item'           => __( 'New Homepage' ),
        'all_items'          => __( 'All Homepage' ),
        'view_item'          => __( 'View Homepage' ),
        'search_items'       => __( 'Search Homepage' ),
        'not_found'          => __( 'No homepage found' ),
        'not_found_in_trash' => __( 'No homepage found in the Trash' ),
        'parent_item_colon'  => '',
        'menu_name'          => 'Homepage'
    );
    $args = array(
        'labels'        => $labels,
        'description'   => 'Holds our homepage specific data',
        'public'        => true,
        'menu_position' => 5,
        'supports'      => array( 'title', 'editor', 'thumbnail', 'excerpt', 'comments' ),
        'has_archive'   => true,
    );
    register_post_type( 'homepage', $args );    
}
add_action( 'init', 'my_custom_post_homepage' );



<p>Add this code where you want to show custom posts</p>

<div id="custompst">                
<?php query_posts( 'post_type=homepage'); ?>        
<?php if ( have_posts() ) while ( have_posts() ) : the_post(); ?>                    
<li><a href="<?php the_permalink(); ?>" rel="bookmark"><h1 class="adsnameleft"><?php the_title(); ?></h1></a></li>
<li><span class="date"><?php the_time(get_option('date_format')); ?></span></li>                    
<div class="custom-post-entry">
<?php the_content();?>
<div class="clear"></div>                    
</div><!--post-entry end-->
<?php endwhile; ?>
</div> <!--custompst end-->


<p>Add your css for custom posts </p>

#custompst{
    
    width:500px;
    height:auto;
    float:left;
    margin-top:15px;
}
.custom-post-entry{
    
    width:400px;
    height:auto;
    float:left;
}
.adsnameleft{
    background: none repeat scroll 0 0 rgb(185, 185, 185);
    width:400px;

Ad comes here

Upwork Test Answers | WordPress Upwork Test Answers 2017

Upwork Test Answers | WordPress Upwork Test Answers 2017

Q1.) select all the default taxonomies in wordpress.
Ans.)
1)category
2) post_tag
3) link_category
4) post_category
5) post_format
Q2.) which concept does wordpress uses to control user access to different features.
Ans.) Role
Q3.) Which of the following is a not default image size in WP?
Ans.) Small size
Q4.) What is the name of table in database which stores custom fields data?
Ans.) wp_postmeta
Q.5) What are WordPress hooks?
Ans.) group of plugins which control wordpress behavior
Q6.) How do you enable the network setup menu item(enable multisite) in wordpress?
Ans.) set WP_Allow_MULTISITE as true in wp_config.php
Q7.) how to style each list item background of the wordpress navigation separately.
Ans.)
    nav li:nth-child(1).current-menu-item
    {
    background-color: red;
    }
    nav li:nth-child(2).current-menu-item
    {
    background-color: blue;
    }
    nav li:nth-child(3).current-menu-item
    {
    background-color: green;
    }
Q8.)If you need to store information temporarily, which wordpress system would you use :
Ans.) Transients
Q9.) how do you enable debug mode in WP?
Ans.) By setting WP_DEBUG as true in WP-Config.php
Q10.) what can the contributer role do?
Ans.) Edit Posts
Q11.)Which constant is NOT recognized in wp-config.php?
Ans.) wp_HOME_URL
Q12.)Which wp global object is used to execute custom databse queries?
Ans.) $wpdb
Q13.)Which one of the following files is located in the root of your wordpress installation directory and contains your website’s setup details, such as database connection info?
Ans.)wp_config.php
Q14.)what is user Management?
Ans.) WP User Manager. Managing your members, creating front-end profiles and custom login and registration pages should be easy. You easily add custom userregistration, login and password recovery forms to your WordPress website.
Q15.) How you can create a static page with wordpress?
Ans.) to create a static page in wordpress………
Q16.) Is it possible to create posts programmatically?
Ans.) Yes,with wp_insert_post() function
Q17.) which of the following is the correct way to register shortcode?
Ans.)
function foobar_func( $atts )
{
return “foo and bar”;
}
add_shortcode( ‘foobar’, ‘foobar_func’ );
Q18.) What is wordpress multisite?
Ans.) wp configuration features that supports multiple sites.
Q19.) Which of the following is not a default user role in wp?
Ans.) Blogger
Q20.) What does wp_rand() function?
Ans.) Generates a random number.
Q21.) Which of the following is not a wordpress role?
Ans.) System
Q22.) Which of the following is incorrect possible value for $show attribute of bloginfo($show) function?
Ans.) ‘homeurl’
Q23.) pick the correct default post types readily available to users or internally used by the wordpress installation.
Ans.)
1) post
2) page
Q24.) what is common to all these functions: next_post,previous_post,link_pages,the _author_url,wp_get_link?
Ans.) They are all deprecated.
Q25.)Wordpress navigation menu without sub menu.
Ans.) wp_nav_menu( array( ‘theme_location’ => ‘primary’, ‘menu_class’ => ‘nav-menu’,’depth’ => 1) ) );
Q26.)Which of the following post types are by default available in wordpress installation(choose all the apply)
Ans.) Post
Page
Q27.) What is the difference between the wp_title and the_title tags?
Ans.) wp_title() function is for use outside “The Loop” to display the title of a page. the_title() on the other hand is used within “The Loop”.
Q28.)Which of the following HTML tags are not allowed to be used in a post comment?
Ans.) Form
Img
Q29.) A wordpress___________ is a collection of files that work together produce a graphical interface with an underlying unifying design for a weblog.
Ans.) Theme
Q30.) Themes typically reside in the ______________ directory.
Ans.) wp-content/themes
Q31.) _________________ is the ability for readers to respond to articles writte in your blog.
Ans.) Comment Posting
Q32.) A/an __________ is a globally recognized avatar.
Ans.) gravatar
Q33.) _______________ make it possible for a person to have one avatar across              the entire web.
Ans.) Gravatar
<
Q34.) where are plugin options stored in WordPress ?.
Ans.) They are stored in WordPress plugin folder
Q35.) What is the default site update service that WordPress automatically notifies when you publish a new post?
Ans.) http://rpc.pingomatic.com
Q36.)  Pick the default template tag(s).
Ans.) wp_title
the_title
Q37.) WordPress uses a ____________ in conjucntion with the mod_rewrite       Apache module to produce permalinks?
Ans.) an .htaccess file
Q38.) What is permalink?
Ans.) The complete url of your wordpress site.
Q39.)Where can you change the Timezone used by WordPress in the dashboard?
Ans.)In Settings > General
Q40.) _____________ are condensed summaries of your blog posts.
Ans.) Excerpts
Q41.) What database does WordPress use?
Ans.) MySQL
Q42.)In manual installation,wp-config-sample.php shoud be renamed to_____.
Ans.) wp-config.php
Q43.) What is the default table prefix in WP?
Ans.) wp_

Ad comes here
Error's and solution's
Update Cookies Preferences