Magento Engineer
social
Php

Php

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

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

What is differences between PHP5 and PHP7 ?

Main differences between PHP5 and PHP7 are as below -

1. PHP 5 is using Zend Engine II while PHP7 is using PHPNG (that is PHP Next Generation)
2. Benchmarks for PHP 7 consistently show speeds twice as fast as PHP 5.6
3. In PHP7, error exception facility called Engine Exception is present in which you can mark the fatal error as exception
4. PHP7 supports 64-bit system while PHP5 does not support it
5. PHP7 introduced New Operators

Ad comes here

Basic & Advanced MySQL Interview Questions with Answers

MySQL Questions with Answers

Question : How can we know the total number of elements of Array?
Answer :
sizeof($array_var)
count($array_var)
If we just pass a simple var instead of a an array it will return 1.

Question : Different Types of Tables in Mysql?
Answer : There are Five Types Tables in Mysql
1)INNODB
2)MYISAM
3)MERGE
4)HEAP
5)ISAM

Question : What is the difference between the functions unlink and unset?
Answer :
unlink() deletes the given file from the file system.
unset() makes a variable undefined.

Question : In how many ways we can retrieve the data in the result set of MySQL using PHP?
Answer : You can do it by 4 Ways
1. mysql_fetch_row.
2. mysql_fetch_array
3. mysql_fetch_object
4. mysql_fetch_assoc


Question : What do DDL, DML, and DCL stand for?
Answer : DDL is the abbreviation for Data Definition Language dealing with database schemas as well as the description of how data resides in the database. An example is CREATE TABLE command. DML denotes Data Manipulation Language such as SELECT, INSERT etc. DCL stands for Data Control Language and includes commands like GRANT, REVOKE etc.

Question : What are the different types of strings in Database columns in MySQL?
Answer : Different types of strings that can be used for database columns are SET, BLOB, VARCHAR, TEX, ENUM, and CHAR.

Question : Is there an object oriented version of MySQL library functions?
Answer : MySQLi is the object oriented version of MySQL and it interfaces in PHP.

Question : How to display Nth highest salary from a table in a MySQL query?
Answer : Let us take a table named employee.

To find Nth highest salary is:
select distinct(salary) from employee order by salary desc limit n-1,1  

If you want to find 3rd largest salary:
select distinct(salary) from employee order by salary desc limit 2,1

Question : What is the difference between mysql_connect and mysql_pconnect?
Answer : Mysql_connect() is used to open a new connection to the database while mysql_pconnect() is used to open a persistent connection to the database. It specifies that each time the page is loaded mysql_pconnect() does not open the database.

Question : How many TRIGGERS are possible in MySql
Answer : Six triggers are possible to use in MySQL database .
1.Before Insert
2.After Insert
3.Before Update
4.After Update
5.Before Delete
6.After Delete

Question : How to delete only the repeated records from a USER table ?
Answer : First we need to select only those records which are repeated giving a constraint :count should be greater than one to make the signle record deletion work. Suppose repeating of record is considered by column name.

SELECT * FROM(SELECT id FROM user GROUP BY name HAVING COUNT(*) > 1) AS A

Then will apply the deletion on those records.
DELETE FROM user WHERE id IN(SELECT * FROM(SELECT id FROM user GROUP BY name HAVING COUNT(*) > 1) AS A)

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
Ad comes here
Ad comes here

How to run custom MySql query in Magento2 and fetch data?

<?php

//Connection with magento2 database

$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$resource = $objectManager->get('Magento\Framework\App\ResourceConnection');
$connection = $resource->getConnection('core_read');

//Now execute your mysql query

$fetch="SELECT * FROM catalog_product_entity";

$result = $connection->fetchAll($fetch);

?>

Ad comes here

How do you Encrypt and Decrypt a PHP String?

/**Function to encrypt or decrypt the given value**/
/**Create a function for Encryption url**/

function encrypt_decrypt($string){   
    $string_length=strlen($string);
    $encrypted_string="";     
    for ($position = 0;$position<$string_length;$position++){         
        $key = (($string_length+$position)+1);
        $key = (255+$key) % 255;
        $get_char_to_be_encrypted = SUBSTR($string, $position, 1);
        $ascii_char = ORD($get_char_to_be_encrypted);
        $xored_char = $ascii_char ^ $key;  //xor operation
        $encrypted_char = CHR($xored_char);
        $encrypted_string .= $encrypted_char;
    }
    /***Return the encrypted/decrypted string***/
    return $encrypted_string;
 }

/*** While passing the unique value to a link- Do the following steps ***/
$pid=88;//Let's 88 is the actual id
/***For more security multiply some value-You can set the multiplication value in config file*/
$passstring=$pid*12345;
$encrypted_string=encrypt_decrypt($passstring);
$param=urlencode($encrypted_string);

/*** Add this url to your anchor link***/
$url='your_target_path.php?id='.$param;
 
/*** While fetching the params in the target file- Do the following steps ***/
$getid=$_GET['id'];
$passstring=urldecode(stripslashes($getid));
$decrypted_string= encrypt_decrypt($passstring);
/***Divide the decrypted value with the same value we used for the multiplication***/
$your_actual_id= $decrypted_string/12345;

/*** Now fire your MySql query by this ID***/

Ad comes here

How to use Stripe payment gateway with Shopify ?

Here are the instructions to use Stripe as your payment gateway for your Shopify store:


    A- Login to your Shopify store.
    B- Click Settings.
    C- Click Payments.
    D- In the Accept Credit Cards section select Shopify Payments.
    E- Deactivate Shopify Payments.(When you deactivate shopify payment after then Stripe payment gateway will show)
    F- Now select stripe payment .
    G- Click Activate.
    H- Click Complete account setup.
    I- Enter the various details and submit.

Upon taking the steps above you’ll be able to accept credit card payments and, although Shopify Payments use Stripe, you won’t be able to view your Shopify Payments in the Stripe Dashboard.

Ad comes here

How to validate Alpha Numeric password validation ?

Must contain at least one number and one uppercase and lowercase letter and one special charectar, and at least 8 or more characters.

Method First:

<form action="#">
Password: <input type="password" name="password" id="password"
pattern="(?=.*?[A-Z])(?=.*?[a-z])(?=.*?[0-9])(?=.*?[^\w\s]).{8,}"
title="Must contain at least one number and one uppercase and lowercase letter and one special charectar, and at least 8 or more characters">
<input type="submit">
</form>

Method second through PHP validation :

$uppercase = preg_match('@[A-Z]@', $password); //uppercase
$lowercase = preg_match('@[a-z]@', $password); //lowercase
$number    = preg_match('@[0-9]@', $password); //numbers
$special   = preg_match('@[!@#$%^&*/()\-_=+{};:,<.>]@', $password); //special charectar

if(!$uppercase || !$lowercase || !$number || !$special || strlen($password) < 8) {
// tell the user something went wrong
}

Ad comes here

How to write databse query in mysql,pdo and mysqli format?

Databse query in mysql,pdo and mysqli format.

MySQL = Popular open source relational database management system.
MySQLi - Improved PHP MySQL extension Read here
PDO - PHP extension similar to MySQLi. Provides object oriented way to access database

MySqli

$mysqli =new mysqli("example.com","user","password","database"); 
$result = $mysqli->query("SELECT 'Hello, dear MySQL user!' AS _message FROM DUAL");
$row = $result->fetch_assoc(); echo htmlentities($row['_message']);

PDO

$pdo =new PDO('mysql:host=example.com;dbname=database','user','password'); 
$statement = $pdo->query("SELECT 'Hello, dear MySQL user!' AS _message FROM DUAL");
$row = $statement->fetch(PDO::FETCH_ASSOC); echo htmlentities($row['_message']);

MySQL

$c = mysql_connect("example.com","user","password"); 
mysql_select_db("database");
$result = mysql_query("SELECT 'Hello, dear MySQL user!' AS _message FROM DUAL");
$row = mysql_fetch_assoc($result); echo htmlentities($row['_message']);

Ad comes here

PHP Interview question and answers.

PHP Interview question and answers for experienced.

Question: What is the difference between unset() and unlink() ?
Answer: unset() sets a variable to “undefined” while unlink() deletes a file we pass to it from the file system.

Question: Can the value of a constant change during the script’s execution?
Answer: No, the value of a constant cannot be changed once it’s declared during the PHP execution.

Question: How would you declare a function that receives one parameter name hello?
Answer: If hello is true, then the function must print hello, but if the function doesn’t receive hello or hello is false the function must print bye.
Example:
<?php
function showMessage($hello=false){
  echo ($hello)?'hello':'bye';
}
?>

Question: The value of the variable input is a string 1,2,3,4,5,6,7. How would you get the sum of the integers contained inside input?
Answer: There is no unique answer to this question, but the answer must be similar to this one.You can use explode function.
Example:
<?php
echo array_sum(explode(',',$input));
?>

Question: How can we know the number of days between two given dates using PHP?
Answer:
<pre>$date1 = date(‘Y-m-d’);
$date2 = ’2006-07-01′;
$days = (strtotime() &ndash; strtotime()) / (60 * 60 * 24);
echo “Number of days since ’2006-07-01′: $days”;</pre>

Question: What are the differences between DROP a table and TRUNCATE a table?
Answer:
DROP TABLE table_name – This will delete the table and its data.
TRUNCATE TABLE table_name – This will delete the data of the table, but not the table definition.

Question: What are the differences between mysql_fetch_array(), mysql_fetch_object(), mysql_fetch_row()?
Answer:
mysql_fetch_array:
Fetch a result row as an associative array and a numeric array.

mysql_fetch_object:
Returns an object with properties that correspond to the fetched row and moves the internal data pointer ahead. Returns an object with properties that correspond to the fetched row, or FALSE if there are no more rows.

mysql_fetch_row():
Fetches one row of data from the result associated with the specified result identifier. The row is returned as an array. Each result column is stored in an array offset, starting at offset 0.

Ad comes here

How to remove .html and .php extensions from URL ?

Write this code to your htaccess file .

# Apache Rewrite Rules
 <IfModule mod_rewrite.c>
  Options +FollowSymLinks
  RewriteEngine On
  RewriteBase /

# Add trailing slash to url
  RewriteCond %{REQUEST_FILENAME} !-f
  RewriteCond %{REQUEST_URI} !(\.[a-zA-Z0-9]{1,5}|/|#(.*))$
  RewriteRule ^(.*)$ $1/ [R=301,L]

# Remove .php-extension from url
  RewriteCond %{REQUEST_FILENAME} !-d
  RewriteCond %{REQUEST_FILENAME}\.php -f
  RewriteRule ^([^\.]+)/$ $1.php

# End of Apache Rewrite Rules
 </IfModule>

It only removes .php extension, if you want to remove other extension as well (e.g. .html), copy and paste 3rd block and replace php with other extension.
Don't forget to also remove extension from href anchors (links) .

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

How to reindex magento2 in XAMPP localhost ?

reindex magento2 in XAMPP localhost

Step1- Open your xampp control panel
step2- Goto Shell command panel
STEP3- open you computer drive where your project is install.

CD "YOUR DRIVE"
CD "YOUR XAMPP FOLDER"
write a command

STEP4- go to in "cd php"

STEP5-Now write this command

php d:\xampp\htodcs\"projectname"\bin\magento indexer:reindex

Ad comes here

How to check php email is working or not on the server?

<?php
$to = "to@youremail.com";
$subject = "Test email";
$message = "This is a test email.";
$from = "from@youremail.com";
$headers = "From:" . $from;
if (mail($to, $subject, $message, $headers)) {
    echo("Your message has been sent successfully");
    } else {
    echo("Sorry, your message could not be sent");
}
?>

Ad comes here

How many type of Inheritance in php ? And, Is multiple Inheritance support PHP?

Inheritance has three types, single, multiple and multi level inheritance. But, PHP supports only single inheritance, where, only one class can be derived from single parent class.

Even though, PHP is not supporting any other inheritance type except single inheritance, we can simulate multiple inheritance by using PHP interface.

In PHP, inheritance can be done by using extends keyword, meaning that, we are extending the derived class with some additional properties and methods of its parent class. The syntax for inheriting a class is as follows.

Child_class_name extends Parent_class_name{
...
.......
}

Ad comes here

BrainTree PayPal Payment Gateway Integrating With core PHP

BrainTree API is cool enough for you to understand, but you need to setup the prerequisites first.

.

A Developer Sandbox Account – Create here (braintreegateway.com)
.

BrainTree Client Framework within your application – Download from :http://www.hurricanesoftwares.com/goto/https://github.com/braintree/braintree_php

Now, let's create a php file called config.php and place the following code in it


require_once('lib/Braintree.php');
Braintree_Configuration::environment('sandbox');
Braintree_Configuration::merchantId('---YOUR MERCHANT ID---');
Braintree_Configuration::publicKey('---YOUR PUBLIC KEY---');
Braintree_Configuration::privateKey('---YOUR PRIVATE KEY---');
//Get the Client Token
$clientToken = Braintree_ClientToken::generate();



We will use Braintree Transparent Redirect to accept one time transactions.
Create a file called OneTime_Transactions.php and place the following code in it.

<?php
require_once 'config.php';
 
function braintree_text_field($label, $name, $result) {
    echo('<div>' . $label . '</div>');
    $fieldValue = isset($result) ? $result->valueForHtmlField($name) : '';
    echo('<div><input type="text" name="' . $name .'" value="' . $fieldValue . '" /></div>');
    $errors = isset($result) ? $result->errors->onHtmlField($name) : array();
    foreach($errors as $error) {
        echo('<div style="color: red;">' . $error->message . '</div>');
    }
    echo("\n");
}
?>
 
<html>
    <head>
        <title>Braintree Transparent Redirect</title>
    </head>
    <body>
        <?php
        if (isset($_GET["id"])) {
            $result = Braintree_TransparentRedirect::confirm($_SERVER['QUERY_STRING']);
        }
        if (isset($result) && $result->success) { ?>
            <h1>Braintree redirect Response</h1>
            <?php $transaction = $result->transaction; ?>
            <table>
                <tr><td>transaction id</td><td><?php echo htmlentities($transaction->id); ?></td></tr>
                <tr><td>transaction status</td><td><?php echo htmlentities($transaction->status); ?></td></tr>
                <tr><td>transaction amount</td><td><?php echo htmlentities($transaction->amount); ?></td></tr>
                <tr><td>customer first name</td><td><?php echo htmlentities($transaction->customerDetails->firstName); ?></td></tr>
                <tr><td>customer last name</td><td><?php echo htmlentities($transaction->customerDetails->lastName); ?></td></tr>
                <tr><td>customer email</td><td><?php echo htmlentities($transaction->customerDetails->email); ?></td></tr>
                <tr><td>credit card number</td><td><?php echo htmlentities($transaction->creditCardDetails->maskedNumber); ?></td></tr>
                <tr><td>expiration date</td><td><?php echo htmlentities($transaction->creditCardDetails->expirationDate); ?></td></tr>
            </table>
        <?php
        } else {
            if (!isset($result)) { $result = null; } ?>
            <h1>Braintree Transparent Redirect Example</h1>
            <?php if (isset($result)) { ?>
                <div style="color: red;"><?php echo $result->errors->deepSize(); ?> error(s)</div>
            <?php } ?>
            <form method="POST" action="<?php echo Braintree_TransparentRedirect::url() ?>" autocomplete="off">
                <fieldset>
                    <legend>Customer</legend>
                    <?php braintree_text_field('First Name', 'transaction[customer][first_name]', $result); ?>
                    <?php braintree_text_field('Last Name', 'transaction[customer][last_name]', $result); ?>
                    <?php braintree_text_field('Email', 'transaction[customer][email]', $result); ?>
                </fieldset>
 
                <fieldset>
                    <legend>Payment Information</legend>
 
                    <?php braintree_text_field('Credit Card Number', 'transaction[credit_card][number]', $result); ?>
                    <?php braintree_text_field('Expiration Date (MM/YY)', 'transaction[credit_card][expiration_date]', $result); ?>
                    <?php braintree_text_field('CVV', 'transaction[credit_card][cvv]', $result); ?>
                </fieldset>
 
<?php
$trans_data = Braintree_TransparentRedirect::transactionData(
array(
'redirectUrl' => "http://" . $_SERVER["SERVER_NAME"] . ":" . $_SERVER["SERVER_PORT"] . parse_url($_SERVER["REQUEST_URI"], PHP_URL_PATH),
'transaction' => array(
'amount' => '50.00',
 'type' => 'sale'
)))
?>
                <input type="hidden" name="tr_data" value="<?php echo $trans_data ?>" />
 
                <br />
                <input type="submit" value="Submit" />
            </form>
        <?php } ?>
    </body>
</html>

$result holds the processor responses from BrainTree.

$transaction = $result->transaction;

Now, we have the full information in $transaction and you can display the transaction information like
echo htmlentities($transaction->id);
    
echo htmlentities($transaction->id);

This is how you can use BrainTree Payment Gateway’s Transparent Redirect Method to make one time transactions. In the next part we are going to explain how to subscribe customers for recurring payments.

Ad comes here

Difference b/w Numeric Array and Associative Array?

Numeric Array:
These arrays can store numbers, strings and any object but their index will be represented by numbers.
By default array index starts from zero.

<?php
         /* First method to create array. */
         $numbers = array( 1, 2, 3);
         
         foreach( $numbers as $value ) {
            echo "Value is $value <br />";
         }
?>

Associative Arrays:

The associative arrays are very similar to Numeric arrays in term of functionality but they are different in terms of their index.
Associative array will have their index as string so that you can establish a strong association between key and values.

$numbers = array( "a"=>1, "b"=>2, "c"=>3);

Ad comes here

How to run custom MySql query in Magento ?

$db = Mage::getSingleton(‘core/resource’)->getConnection(‘core_write’);
$result=$db->query(“SELECT * FROM PCDSTable”);


$connect = Mage::getSingleton('core/resource')->getConnection('core_read');
$result=$db->query(“SELECT id FROM `customer_wishlists` WHERE `type`='wishlist'");

Ad comes here

Difference between break and continue in PHP?

Break ends a loop completely and continue just shortcuts of a current iteration and moves on to the next iteration.

while ($condition) {   <--------------------+
    continue;          --- goes back here --+
    break;             ----- jumps here ----+
}                                     |
                       <--------------------+

Ad comes here

array_map function

The array_map() function sends each value of an array to a user-made function, and returns an array with new values, given by the user-made function.

Example:

function myfunction($num) {

return($num*$num);

}

$a=array(1,2,3,4,5);

print_r(array_map("myfunction",$a));

Ad comes here

How to get some word from database using php and mysql?

Fetch content table from your database. I have stored this in $descp.

$descp=$row['YOUR MySql content table'];

$arr=array();//global array

$arr = explode(" ",html_entity_decode($descp));

$record = array();

$k =count($arr);

for($x=0;$x<=25;$x++){

if( $x < $k){

$record[] = $txt[$x];

}

}

echo "OutputData".$data =implode(" ",$record);

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