Snippets Collections
function product_dropdown_shortcode() {
    ob_start();

    // Query to get all products
    $products = get_posts(array(
        'post_type' => 'product',
        'posts_per_page' => -1,
    ));

    // Output the dropdown HTML
    ?>
    <select id="product_dropdown">
        <option value="">Select a product</option>
        <?php foreach ($products as $product) : ?>
            <option value="<?php echo esc_attr($product->ID); ?>"><?php echo esc_html($product->post_title); ?></option>
        <?php endforeach; ?>
    </select>
    <script>
        jQuery(function($) {
            // Initialize select2 for searchable dropdown
            $('#product_dropdown').select2();
        });
    </script>
    <?php

    return ob_get_clean();
}
add_shortcode('product_dropdown', 'product_dropdown_shortcode');
function enqueue_select2() {
    // Enqueue Select2 library
    wp_enqueue_script('select2', 'https://cdnjs.cloudflare.com/ajax/libs/select2/4.1.0-beta.1/js/select2.min.js', array('jquery'), '4.1.0-beta.1', true);
    wp_enqueue_style('select2', 'https://cdnjs.cloudflare.com/ajax/libs/select2/4.1.0-beta.1/css/select2.min.css', array(), '4.1.0-beta.1');
}
add_action('wp_enqueue_scripts', 'enqueue_select2');
<!--HTML Code-->
  
  <form id="contact_form" method="post">
    <div class="row">
        <div class="col-md-12 form-group g-mb-20">
            <input type="text" class="form-control" id="txtContactName" name="txtContactName" placeholder="Full Name" tabindex="201" required>
            <div class="error-message" id="txtContactName-error"></div>
        </div>

        <div class="col-md-12 form-group g-mb-20">
            <input type="email" class="form-control" id="txtContactEmail" name="txtContactEmail" placeholder="Email Address" tabindex="202" required>
            <div class="error-message" id="txtContactEmail-error"></div>
        </div>

        <div class="col-md-12 form-group g-mb-20">
            <input type="text" class="form-control" id="txtContactPhone" name="txtContactPhone" placeholder="Contact Number" maxlength="10" tabindex="203" required>
            <div class="error-message" id="txtContactPhone-error"></div>
        </div> 

        <div class="col-md-12 form-group g-mb-40">
            <textarea class="form-control" id="txtContactMessage" name="txtContactMessage" rows="7" placeholder="Message" maxlength="160" tabindex="204" required></textarea>
            <div class="error-message" id="txtContactMessage-error"></div>
        </div>
    </div>
    <input type="submit" class="btn btn-lg u-btn-primary g-font-weight-600 g-font-size-default rounded-0 text-uppercase g-py-15 g-px-30" id="btnContactSubmit" name="btnContactSubmit" value="SUBMIT">
</form>

<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.19.3/jquery.validate.min.js"></script>
<script>
	
</script>
<script>
    $(document).ready(function() {
        $('#contact_form').validate({
            rules: {
                txtContactName: "required",
                txtContactEmail: {
                    required: true,
                    email: true
                },
                txtContactPhone: {
                    required: true,
                    digits: true,
                    maxlength: 10
                },
                txtContactMessage: "required"
            },
            messages: {
                txtContactName: "Please enter your full name",
                txtContactEmail: {
                    required: "Please enter your email address",
                    email: "Please enter a valid email address"
                },
                txtContactPhone: {
                    required: "Please enter your contact number",
                    digits: "Please enter only digits",
                    maxlength: "Please enter a valid 10-digit phone number"
                },
                txtContactMessage: "Please enter your message"
            },
            errorPlacement: function(error, element) {
                error.appendTo(element.closest('.form-group').find('.error-message'));
            },
            submitHandler: function(form) {
                var formData = $(form).serialize();
                $.ajax({
                    type: 'POST',
                    url: 'mail.php',
                    data: formData,
                    success: function(response) {
                        $('#contact_form').append('<div class="success-message" style="color: green;">Message sent successfully!</div>');
                        setTimeout(function() {
                            $('#contact_form')[0].reset();
                        }, 4000);
                    },
                    error: function(xhr, status, error) {
                        console.error(xhr.responseText);
                        alert('Error: ' + xhr.responseText);
                    }
                });
            }
        });
    });
</script>

PHP Miler folder should be there
Create folder name with mail.php and add below code there 
<?php
// Include PHPMailer autoload file

use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\SMTP;
use PHPMailer\PHPMailer\Exception;

// Load Composer's autoloader
require 'phpmailer/vendor/autoload.php';

// Check if the form is submitted
if ($_SERVER["REQUEST_METHOD"] == "POST") {
    // Retrieve form data
    $name = $_POST['txtContactName'];
    $email = $_POST['txtContactEmail'];
    $phone = $_POST['txtContactPhone'];
    $message = $_POST['txtContactMessage'];

    // Initialize PHPMailer
    $mail = new PHPMailer(true);
    try {
        // SMTP settings
		$mail->IsSMTP();        // Sets Mailer to send message using SMTP
		$mail->SMTPAuth = true; // Authentication enabled
		$mail->SMTPSecure = 'tls'; // Secure transfer enabled REQUIRED for Gmail
		$mail->Host = 'smtp-relay.brevo.com';
		$mail->Port = 587;
		$mail->Username = 'advanceindiaprojectltd@gmail.com';
		$mail->Password = 'xsmtpsib-e66045ab99d2f28608d548ca33a5a3ac8cc14a6896d682cbdc5418c80154b5eb-6B5QJOyT18GvbzmZ';
		$mail->SMTPOptions = array(
			'ssl' => array(
				'verify_peer' => false,
				'verify_peer_name' => false,
				'allow_self_signed' => true
			)
		);

        // Recipients
        $mail->setFrom($email, $name);
        $mail->addAddress('roshan@teamvariance.com'); // Add recipient email address

        // Content
        $mail->isHTML(true);
        $mail->Subject = 'Contact Form Submission';
		// Construct HTML table for the email body
        $message = '
            <h3 align="center">Details</h3>
            <table border="1" width="100%" cellpadding="5" cellspacing="5">
                <tr>
                    <td width="30%">Name</td>
                    <td width="70%">' . $name . '</td>
                </tr> 
                <tr>
                    <td width="30%">Email</td>
                    <td width="70%">' . $email . '</td>
                </tr>
                <tr>
                    <td width="30%">Phone</td>
                    <td width="70%">' . $phone . '</td>
                </tr>
                <tr>
                    <td width="30%">Message</td>
                    <td width="70%">' . $message . '</td>
                </tr>
            </table>
        ';
        $mail->Body = $message;

        // Send email
        $mail->send();
        
        // Return success message
        echo "success";
    } catch (Exception $e) {
        // Return error message
        echo "error";
    }
}
?>



// Function to create the custom product dropdown shortcode
function custom_product_dropdown_shortcode() {
  ob_start(); // Start output buffering

  // Get the referring URL and selected product name
  $referring_url = wp_get_referer();
  $selected_product_name = '';
  $selected_product_id = ''; // Initialize for product ID selection

  if ($referring_url) {
    $url_parts = parse_url($referring_url);
    if (isset($url_parts['path'])) {
      $path_parts = explode('/', $url_parts['path']);
      $product_index = array_search('product', $path_parts);
      if ($product_index !== false && isset($path_parts[$product_index + 1])) {
        $selected_product_name = $path_parts[$product_index + 1];
        $selected_product_id = $path_parts[$product_index + 1]; // Assuming product ID in URL
      }
    }
  }

  // Create the dropdown with search functionality using Select2
  echo '<select id="product_name" name="product_name">';
  echo '<option value="">Select Product</option>';
  echo '<option data-tokens="Search Products" disabled hidden></option>'; // Search placeholder

  $products = array(); // Store product data for filtering

  $query = new WP_Query(array(
    'post_type' => 'product',
    'post_status' => 'publish',
    'posts_per_page' => '-1'
  ));

  if ($query->have_posts()) :
    while ($query->have_posts()) : $query->the_post();
      $product = wc_get_product(get_the_ID());
      $price = $product->get_price_html();
      $selected = '';
      // Use product name for comparison
      if (get_the_title() === $selected_product_name) {
        $selected = 'selected="selected"';
      }

      $products[] = array(
        'id' => get_the_title(), // Store product name instead of ID
        'text' => get_the_title() 
      );
    endwhile;
  else:
    echo '<option value="">No products found</option>';
  endif;

  wp_reset_postdata();

  foreach ($products as $product) {
    echo '<option value="' . $product['id'] . '" ' . $selected . '>' . $product['text'] . '</option>';
  }

  echo '</select>';

  // Enqueue JavaScript for search functionality
  wp_enqueue_script('select2'); // Assuming you've added the Select2 library
  ?>
  <script>
    jQuery(function($) {
      $('#product_name').select2({
        data: <?php echo json_encode(array_map(function($product) {
          return array('id' => $product['id'], 'text' => $product['text']);
        }, $products)); ?>,
        placeholder: 'Search Products'
      });
    });
  </script>
  <?php

  return ob_get_clean(); // Return the output and clean buffer
}

// Add the shortcode to WordPress
add_shortcode('custom_product_dropdown', 'custom_product_dropdown_shortcode');







//below code is same as above but instead of product name is saving in back the product ID is saving :






// Function to create the custom product dropdown shortcode
function custom_product_dropdown_shortcode() {
  ob_start(); // Start output buffering

  // Get the referring URL and selected product name
  $referring_url = wp_get_referer();
  $selected_product_name = '';
  $selected_product_id = ''; // Initialize for product ID selection

  if ($referring_url) {
    $url_parts = parse_url($referring_url);
    if (isset($url_parts['path'])) {
      $path_parts = explode('/', $url_parts['path']);
      $product_index = array_search('product', $path_parts);
      if ($product_index !== false && isset($path_parts[$product_index + 1])) {
        $selected_product_name = $path_parts[$product_index + 1];
        $selected_product_id = $path_parts[$product_index + 1]; // Assuming product ID in URL
      }
    }
  }

  // Create the dropdown with search functionality using Select2
  echo '<select id="product_name" name="product_name">';
  echo '<option value="">Select Product</option>';
  echo '<option data-tokens="Search Products" disabled hidden></option>'; // Search placeholder

  $products = array(); // Store product data for filtering

  $query = new WP_Query(array(
    'post_type' => 'product',
    'post_status' => 'publish',
    'posts_per_page' => '-1'
  ));

  if ($query->have_posts()) :
    while ($query->have_posts()) : $query->the_post();
      $product = wc_get_product(get_the_ID());
      $price = $product->get_price_html();
      $selected = '';
      // Use product ID for comparison
      if (get_the_ID() === $selected_product_id) {
        $selected = 'selected="selected"';
      }

      $products[] = array(
        'id' => get_the_ID(), // Add ID for selection
        'text' => get_the_title() 
      );
    endwhile;
  else:
    echo '<option value="">No products found</option>';
  endif;

  wp_reset_postdata();

  echo '</select>';

  // Enqueue JavaScript for search functionality
  wp_enqueue_script('select2'); // Assuming you've added the Select2 library
  ?>
  <script>
    jQuery(function($) {
      $('#product_name').select2({
        data: <?php echo json_encode(array_map(function($product) {
          return array('id' => $product['id'], 'text' => $product['text']);
        }, $products)); ?>,
        placeholder: 'Search Products'
      });
    });
  </script>
  <?php

  return ob_get_clean(); // Return the output and clean buffer
}

// Add the shortcode to WordPress
add_shortcode('custom_product_dropdown', 'custom_product_dropdown_shortcode');

ChatGPT








// by below code the search bar for page using shortcode not drodown a searchbar


function product_search_shortcode() {
    ob_start(); ?>

    <div class="product-search-container">
        <input type="text" id="product-search-input" placeholder="Search for a product...">
        <div id="product-search-results"></div>
    </div>

    <script>
    jQuery(document).ready(function($) {
        $('#product-search-input').keyup(function() {
            var searchQuery = $(this).val();

            $.ajax({
                url: '<?php echo admin_url('admin-ajax.php'); ?>',
                type: 'POST',
                data: {
                    'action': 'product_search',
                    'search_query': searchQuery
                },
                success: function(response) {
                    $('#product-search-results').html(response);
                }
            });
        });

        $(document).on('click', '.product-item', function() {
            var selectedProduct = $(this).text();
            $('#product-search-input').val(selectedProduct);
            $('#product-search-results').html('');
        });
    });
    </script>

    <?php
    return ob_get_clean();
}
add_shortcode('product_search', 'product_search_shortcode');

function product_search_callback() {
    $search_query = $_POST['search_query'];

    $products = wc_get_products(array(
        'status' => 'publish',
        'limit' => -1,
        's' => $search_query,
    ));

    if ($products) {
        foreach ($products as $product) {
            echo '<div class="product-item">' . $product->get_name() . '</div>';
        }
    } else {
        echo '<div class="product-item">No products found</div>';
    }

    wp_die();
}
add_action('wp_ajax_product_search', 'product_search_callback');
add_action('wp_ajax_nopriv_product_search', 'product_search_callback');

// ================================
// Extra Footer
// ================================

add_action('ava_before_footer','extra_footer');
    function extra_footer() { ?>
       
<?php }
<input                       
    type="text" 
    placeholder="Start date" 
    class="px-2 py-1 text-sm rounded text-gray-800" 
    x-init="new Pikaday({ field: $el })"
    x-on:change="$wire.startDate = formatDateToYYYYMMDD(new Date($el.value))"
/>
    // Exemple :
    $text = "<script>console.log('salut')</script>";
    echo $text; // Execute le script !
    echo filter_var($text, FILTER_SANITIZE_FULL_SPECIAL_CHARS); // Pas interprèter

    $email = "jean(du22)@toto.fr";
    echo $email; // output : jean(du22)@toto.fr
    echo filter_var($email, FILTER_SANITIZE_EMAIL); // output : jeandu22@toto.fr

    $number = "a10.5";
    echo filter_var($number, FILTER_SANITIZE_NUMBER_FLOAT, FILTER_FLAG_ALLOW_FRACTION | FILTER_FLAG_ALLOW_THOUSAND);

    $arr = [
        'email' => 'jean(a)@<gmail>.com',
        'text' => '<script>const a = 1</script>',
        'number' => 'aa12aaa'
    ];
    print_r(filter_var_array($arr, [
        'email' => FILTER_SANITIZE_EMAIL,
        'text' => [
            'filter' => FILTER_SANITIZE_FULL_SPECIAL_CHARS,
            'flags' =>  FILTER_FLAG_NO_ENCODE_QUOTES
        ],
        'number' => FILTER_SANITIZE_NUMBER_INT
    ]));


    $_POST = filter_input_array(INPUT_POST, [
        'firstname' => FILTER_SANITIZE_FULL_SPECIAL_CHARS,
        'email' => FILTER_SANITIZE_EMAIL,
        'date' => FILTER_SANITIZE_FULL_SPECIAL_CHARS
    ]);
/**
 * 	Show ID in Wordpress
 * 
	Add ID in the action row of list tables for pages, posts,
	custom post types, media, taxonomies, custom taxonomies,
	users amd comments
	
	Inspiration:
	https://wordpress.org/plugins/admin-site-enhancements/
	https://www.itsupportguides.com/knowledge-base/wordpress/using-wordpress-post_row_actions-php-filter/
*/

add_filter('post_row_actions', 'add_custom_action_for_specific_post_type', 11, 2);
add_filter('page_row_actions', 'add_custom_action_for_specific_post_type', 11, 2);
add_filter('cat_row_actions', 'add_custom_action_for_specific_post_type', 11, 2);
add_filter('tag_row_actions', 'add_custom_action_for_specific_post_type', 11, 2);
add_filter('media_row_actions', 'add_custom_action_for_specific_post_type', 11, 2);
add_filter('comment_row_actions', 'add_custom_action_for_specific_post_type', 11, 2);
add_filter('user_row_actions', 'add_custom_action_for_specific_post_type', 11, 2);

/* Output the ID in the action row */
function add_custom_action_for_specific_post_type( $actions, $object ) {
        
	if ( current_user_can( 'edit_posts' ) ) {
		// For pages, posts, custom post types, media/attachments, users
		if ( property_exists( $object, 'ID' ) ) {
			$id = $object->ID;
		}
		// For taxonomies
		if ( property_exists( $object, 'term_id' ) ) {
			$id = $object->term_id;
		}
		// For comments
		if ( property_exists( $object, 'comment_ID' ) ) {
			$id = $object->comment_ID;
		}
		$actions['show-id-now'] = '<span style="color: gray;">ID: ' . $id . '</span>';
	}
	return $actions;
}
if ( is_single() ) {
  $current_post_id = get_queried_object_id();
  $current_category_id = get_the_category( $current_post_id )[0]->cat_ID;

  $args = array(
    'category' => $current_category_id,
    'post__not_in' => array( $current_post_id ),
    'posts_per_page' => 3,
  );

  $related_posts = new WP_Query( $args );

  if ( $related_posts->have_posts() ) {
    echo '<h2>Related Posts:</h2>';
    while ( $related_posts->have_posts() ) {
      $related_posts->the_post();
      echo '<a href="' . get_the_permalink() . '">' . get_the_title() . '</a><br>';
    }
    wp_reset_postdata();
  }
}
wp.domReady(function () {
	wp.blocks.registerBlockStyle('core/button', {
		name: 'link-btn',
		label: 'Link Btn',
	});
});
/**
 * Filters the next, previous and submit buttons.
 * Replaces the form's <input> buttons with <button> while maintaining attributes from original <input>.
 *
 * @param string $button Contains the <input> tag to be filtered.
 * @param object $form Contains all the properties of the current form.
 *
 * @return string The filtered button.
 */
add_filter('gform_submit_button', 'input_to_button', 10, 2);
function input_to_button($button, $form)
{
  $dom = new DOMDocument();
  $dom->loadHTML('<?xml encoding="utf-8" ?>' . $button);
  $input = $dom->getElementsByTagName('input')->item(0);
  $new_button = $dom->createElement('button');
  $new_button->appendChild($dom->createTextNode($input->getAttribute('value')));
  $input->removeAttribute('value');
  foreach ($input->attributes as $attribute) {
    $new_button->setAttribute($attribute->name, $attribute->value);
  }

  $classes = $new_button->getAttribute('class');
  $classes .= " btn is-style-with-arrow";
  $new_button->setAttribute('class', $classes);
  $input->parentNode->replaceChild($new_button, $input);

  return $dom->saveHtml($new_button);
}
/**
 * Attach icon class to the menu title
 *
 * @param $sorted_menu_items
 * @param $args
 * @return mixed
 */
function wti_add_arrow_to_parent_menu_item($sorted_menu_items, $args)
{
	foreach ($sorted_menu_items as $menu_item) {
		if (array_search('menu-item-has-children', $menu_item->classes) != FALSE) {
			$menu_item->title = $menu_item->title . '<svg width="24" height="25" viewBox="0 0 24 25" fill="none" xmlns="http://www.w3.org/2000/svg">
				<path d="M19.9201 9.44995L13.4001 15.97C12.6301 16.74 11.3701 16.74 10.6001 15.97L4.08008 9.44995" stroke="#fff" stroke-width="1.5" stroke-miterlimit="10" stroke-linecap="round" stroke-linejoin="round"/>
				</svg>';
		}
	}

	return $sorted_menu_items;
}
// Dropdown arrows to parent menu items
add_filter('wp_nav_menu_objects', 'wti_add_arrow_to_parent_menu_item', 10, 2);
/* Remove WooCommerce block styles */
function ya_remove_block_css() {
    wp_dequeue_style( 'wc-block-style' ); // WooCommerce
}
add_action('wp_enqueue_scripts','ya_remove_block_css', 100);
// Avia Layout Builder in custom post types

function avf_alb_supported_post_types_mod( array $supported_post_types )
{
  $supported_post_types[] = 'case_studies';
  return $supported_post_types;
}
add_filter('avf_alb_supported_post_types', 'avf_alb_supported_post_types_mod', 10, 1);

function avf_metabox_layout_post_types_mod( array $supported_post_types )
{
 $supported_post_types[] = 'case_studies';
 return $supported_post_types;
}
add_filter('avf_metabox_layout_post_types', 'avf_metabox_layout_post_types_mod', 10, 1);
public function index(Travel $travel, ToursListRequest $request)
    {
        $tours = $travel->tours()
            ->when($request->priceFrom, function ($query) use ($request) {
                $query->where('price', '>=', $request->priceFrom * 100);
            })
            ->when($request->priceTo, function ($query) use ($request) {
                $query->where('price', '<=', $request->priceTo * 100);
            })
            ->when($request->dateFrom, function ($query) use ($request) {
                $query->where('starting_date', '>=', $request->dateFrom);
            })
            ->when($request->dateTo, function ($query) use ($request) {
                $query->where('starting_date', '<=', $request->dateTo);
            })
            ->when($request->sortBy, function ($query) use ($request) {
                if (! in_array($request->sortBy, ['price'])
                    || (! in_array($request->sortOrder, ['asc', 'desc']))) {
                    return;
                }

                $query->orderBy($request->sortBy, $request->sortOrder);
            })
            ->orderBy('starting_date')
            ->paginate();

        return TourResource::collection($tours);
    }
//in controller datatable
->addColumn('mass_delete', function ($row) {
  $selected = '';

  return  '<input type="checkbox" class="row-select test" value="'.$row->id.'">' ;
})


//in view table
 <th>_<input type="checkbox" value="1" id="select-all-row" data-table-id="incoming-messages-table"></th>

//in view datatable (to disable orderable on first column)
'columnDefs': [ {
  'targets': [0], /* column index */
  'orderable': false, /* true or false */
}]

//in view (action button and)
<button type="submit" class="btn btn-xs btn-primary" id="delete-selected">{{__('admin.delete selected')}}</button>
<form action="{{route('admin.incoming-messages.deleteArray')}}" method="post" id="delete_form">
  @csrf
<div class="inputs">

  </div>
</form>


//in view js
<script>
  $(document).on('click', '#select-all-row', function(e) {
    var table_id = $(this).data('table-id');
    if (this.checked) {
      $('#' + table_id)
        .find('tbody')
        .find('input.row-select')
        .each(function() {
        if (!this.checked) {
          $(this)
            .prop('checked', true)
            .change();
        }
      });
    } else {
      $('#' + table_id)
        .find('tbody')
        .find('input.row-select')
        .each(function() {
        if (this.checked) {
          $(this)
            .prop('checked', false)
            .change();
        }
      });
    }
  });


$(document).on('click', '#delete-selected', function(e){
  e.preventDefault();

  $ids = '';
  $html = '';
  $("input:checkbox:checked").each(function(){
    $ids += $(this).val() + ',';
    $html += '<input type="hidden" id="message_deleted" name="message[]" value="'+$(this).val()+'">';
  })
  $('.inputs').html($html);
  $('form#delete_form').submit() 
})
</script>

Here's a guide on how to start developing poker software, outlining key steps and code structure:

1. Define the Scope of Your Project:

    Game Variants: Choose which poker variants you'll include (e.g., Texas Hold'em, Omaha, 5-Card Draw).
    Features: Decide on essential features like player accounts, gameplay, betting, tournaments, chat, and multi-platform compatibility.
    Target Platforms: Determine if you're developing for web, desktop, mobile, or a combination.

2. Choose Your Programming Language and Development Environment:

    Common Languages: Python, Java, C++, C#, and JavaScript are popular choices for game development.
    Development Environments: Select an IDE (Integrated Development Environment) like Visual Studio Code, PyCharm, or Eclipse for efficient coding.

3. Structure Your Code:

    Classes: Create classes for representing cards, decks, hands, players, game tables, and the game logic itself.
    Functions: Write functions to handle shuffling, dealing, betting, evaluating hands, and managing game flow.

4. Implement Core Functionalities:

    Card Deck: Create a class to represent a deck of cards, with methods for shuffling and dealing cards.
    Player Hand: Implement a class to hold a player's hand, with methods for evaluating hand strength.
    Game Logic: Write the core game logic, including betting rounds, hand comparisons, and pot management.

5. Design the User Interface (UI):

    Visual Design: Create visually appealing UI elements using graphics libraries or frameworks.
    User Interaction: Implement intuitive controls for players to interact with the game.

6. Test Thoroughly:

    Unit Testing: Test individual code units to ensure they function as intended.
    Integration Testing: Verify that different parts of the code work together seamlessly.
    User Testing: Gather feedback from real users to identify bugs and areas for improvement.

7. Deploy and Maintain:

    Deployment: Make your poker software available to users on your chosen platforms.
    Maintenance: Address any bugs or issues, and update the software with new features or improvements over time.
//Les tableaux 
// Opérateurs + 
$a = [1, 2];
$b = [4, 5, 6];

print_r($a + $b); //Output = 1, 2, 6 
//Prends la valeur du tableaux de droite et si pas d'index prends la valeur de gauche

// Opérateurs == ne prends pas en compte l'ordre
// Opérateurs === prends en compte l'ordre

// Spread operator :
print_r([...$a, ...$b]); // [1, 2, 4, 5, 6]
// Le tableaux n'existe plus et on étend les valeurs 

//&$variable Récupère l'adresse mémoire d'une variable

// Assigner une valeur à un tableaux :
// Ajouter une valeur à l'index suivant
$arr = [1];
$arr[] = 2; //Output = [1, 2]
// Equivalence avec le spread :
$arr = [...$arr, 3]; // Assigne un nouveau tableau et spread l'ancien en assignant une nouvelle valeur
$arr = [-1, ...$arr]; //Ajoute une valeur au début
array_push($arr, 4);


// Return a random value
$arr = ['orrange', 'blue', 'yellow'];
$value = array_rand($arr);
echo $arr[$value];

// Remove duplicates
$arr2 = ['test', 'test', 1, 2, 3];
$res = array_unique($arr2);
return [
  ...
  'providers' => [
    ...
    \Intervention\Image\ImageServiceProvider::class,
  ],
  'aliases' => Facade::defaultAliases()->merge([
        ...
        'Image' => \Intervention\Image\Facades\Image::class,
    ])->toArray(),
]
<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

class ImageController extends Controller 
{
    public function compressImage(Request $request) 
    {
        $this->validate($request, [
            'image' => 'required|image|mimes:jpg,jpeg,png,gif,svg|max:2048'
        ]);

        $image = $request->file['image'];
        /* 
            Note: Use $image = base64_decode($request['image'])
            if the image is sent as a base64 encoded image.
        */
        $image_name = time().'_'.$image->getClientOriginalName();
        $path = public_path('uploads/') . "/" . $image_name;

        Image::make($image->getRealPath())->resize(150, 150)->save($path);
      
        return response()->json(
            [
                'data' => 'Image compressed and added'
            ], 
            201
        );
    }
}
add_filter( 'woocommerce_product_export_column_names', 'add_slug_export_column' );
add_filter( 'woocommerce_product_export_product_default_columns', 'add_slug_export_column' );

function add_slug_export_column( $columns ) {
	$columns['slug'] = 'Slug';
 
	return $columns;
}

add_filter( 'woocommerce_product_export_product_column_slug'  , 'add_export_data_slug', 10, 2 );
function add_export_data_slug( $value, $product ) {
    $value = $product->get_slug();
	
    return $value;
}

add_filter( 'woocommerce_csv_product_import_mapping_options', 'add_slug_import_option' );
function add_slug_import_option( $options ) {
  $options['slug'] = 'Slug';
 
  return $options;
}

add_filter( 'woocommerce_csv_product_import_mapping_default_columns', 'add_default_slug_column_mapping' );
function add_default_slug_column_mapping( $columns ) {
  $columns['Slug'] = 'slug';
 
  return $columns;
} 

add_filter( 'woocommerce_product_import_pre_insert_product_object', 'process_import_product_slug_column', 10, 2 );
function process_import_product_slug_column( $object, $data ) {
  if ( !empty( $data['slug'] ) ) {
    $object->set_slug( $data['slug'] );
  }
 
  return $object;
}
function woodmart_post_date( $args ) {
	$has_title = get_the_title() != '';
	$attr      = '';
	if ( ! $has_title && ! is_single() ) {
		$url  = get_the_permalink();
		$attr = 'window.location=\'' . $url . '\';';
	}
	$classes  = '';
	$classes .= ' ' . $args['style'];
	$classes .= woodmart_get_old_classes( ' woodmart-post-date' );
	?>
		<div class="post-date wd-post-date<?php echo esc_attr( $classes ); ?>" onclick="<?php echo esc_attr( $attr ); ?>">
			<span class="post-date-day">
				<?php echo get_the_time( 'd' ); ?>
			</span>
			<span class="post-date-month">
				<?php echo get_the_time( 'M' ); ?>
			</span>
			<span class="post-date-year">
				<?php echo get_the_time( 'Y' ); ?>
			</span>
		</div>
	<?php
}
function mergePdf($pdfArr){
    $pdf = new Mpdf();
    foreach($pdfArr as $currentPdf){
      $pagecount = $pdf->SetSourceFile($currentPdf);
      for($i = 1; $i <= $pagecount; $i++){
        $pdf->AddPage();
        $tplId = $pdf->importPage($i);
        $pdf->useTemplate($tplId);
      }
    }
    //direct show on browser
    $pdf->Output();
    
    //spacefic location save file
    $outputpath = 'location/output.pdf';
    $pdf->Output($outputpath, 'F');
}
function find_order_with_product_for_user($user_id, $product_id) {
	global $wpdb;

	// Get the order IDs for the user
	$order_ids = $wpdb->get_col("
        SELECT DISTINCT order_items.order_id
        FROM wp_woocommerce_order_items as order_items
        LEFT JOIN wp_woocommerce_order_itemmeta as order_itemmeta ON order_items.order_item_id = order_itemmeta.order_item_id
        LEFT JOIN wp_posts as posts ON order_items.order_id = posts.ID
        LEFT JOIN wp_postmeta as postmeta ON postmeta.post_id = posts.ID
        WHERE posts.post_type = 'shop_order'
        AND posts.post_status IN ('wc-processing', 'wc-completed')
        AND order_itemmeta.meta_key = '_product_id'
        AND order_itemmeta.meta_value = '$product_id'
        AND postmeta.meta_key = '_customer_user'
        AND postmeta.meta_value = '$user_id'
    ");

	// If orders are found, return the order IDs
	if ($order_ids) {
		return $order_ids;
	}

	return false;
}
function course_woocommerce_product_downloads_shortcode($atts) {
	// Extract shortcode attributes
	$atts = shortcode_atts(
		array(
			'product_id' => get_the_ID(), // Specify the product ID
		),
		$atts,
		'custom_woocommerce_product_downloads'
	);

	// Check if the product ID is provided
	if (empty($atts['product_id'])) {
		return '';
	}

	// Get the product object
	$product = wc_get_product($atts['product_id']);
	$order_ids = find_order_with_product_for_user(get_current_user_id(), $atts['product_id']);

	// Check if the product is downloadable
	if ($product && $product->is_downloadable() &&  wc_customer_bought_product(get_current_user_id(), get_current_user_id(), get_the_ID())) {
		$order = wc_get_order(current($order_ids));
		$downloads = $order->get_downloadable_items();
		// Check if there are downloads
		if ($downloads) {
			// Output a list of download files
			$output = '<h2>دانلود دوره خریداری شده ' . esc_html($product->get_name()) . '</h2>';
			$output .= '<ul>';
			foreach ($downloads as $download) {
				if($download['product_id'] != $atts['product_id']){
					continue;
				}
				$output .= '<li><a href="' . esc_url($download['download_url']) . '">' . esc_html($download['download_name']) . "</a></li>";
			}
			$output .= '</ul>';
		} else {
			$output = '<p>هیچ فایل دانلودی برای این دوره موجود نیست.</p>';
		}
	} else {
		$output = '<p>برای مشاهده فایل ها لطفا ابتدا دوره را خریداری کنید</p>';
	}

	return $output;
}
add_shortcode('course_woocommerce_product_downloads', 'course_woocommerce_product_downloads_shortcode');
function find_order_with_product_for_user($user_id, $product_id) {
	global $wpdb;

	// Get the order IDs for the user
	$order_ids = $wpdb->get_col("
        SELECT DISTINCT order_items.order_id
        FROM wp_woocommerce_order_items as order_items
        LEFT JOIN wp_woocommerce_order_itemmeta as order_itemmeta ON order_items.order_item_id = order_itemmeta.order_item_id
        LEFT JOIN wp_posts as posts ON order_items.order_id = posts.ID
        LEFT JOIN wp_postmeta as postmeta ON postmeta.post_id = posts.ID
        WHERE posts.post_type = 'shop_order'
        AND posts.post_status IN ('wc-processing', 'wc-completed')
        AND order_itemmeta.meta_key = '_product_id'
        AND order_itemmeta.meta_value = '$product_id'
        AND postmeta.meta_key = '_customer_user'
        AND postmeta.meta_value = '$user_id'
    ");

	// If orders are found, return the order IDs
	if ($order_ids) {
		return $order_ids;
	}

	return false;
}
function course_woocommerce_product_downloads_shortcode($atts) {
	// Extract shortcode attributes
	$atts = shortcode_atts(
		array(
			'product_id' => get_the_ID(), // Specify the product ID
		),
		$atts,
		'custom_woocommerce_product_downloads'
	);

	// Check if the product ID is provided
	if (empty($atts['product_id'])) {
		return '';
	}

	// Get the product object
	$product = wc_get_product($atts['product_id']);
	$order_ids = find_order_with_product_for_user(get_current_user_id(), $atts['product_id']);

	// Check if the product is downloadable
	if ($product && $product->is_downloadable() &&  wc_customer_bought_product(get_current_user_id(), get_current_user_id(), get_the_ID())) {
		$order = wc_get_order(current($order_ids));
		$downloads = $order->get_downloadable_items();
		// Check if there are downloads
		if ($downloads) {
			// Output a list of download files
			$output = '<h2>دانلود دوره خریداری شده ' . esc_html($product->get_name()) . '</h2>';
			$output .= '<ul>';
			foreach ($downloads as $download) {
				if($download['product_id'] != $atts['product_id']){
					continue;
				}
				$output .= '<li><a href="' . esc_url($download['download_url']) . '">' . esc_html($download['download_name']) . "</a></li>";
			}
			$output .= '</ul>';
		} else {
			$output = '<p>هیچ فایل دانلودی برای این دوره موجود نیست.</p>';
		}
	} else {
		$output = '<p>برای مشاهده فایل ها لطفا ابتدا دوره را خریداری کنید</p>';
	}

	return $output;
}
add_shortcode('course_woocommerce_product_downloads', 'course_woocommerce_product_downloads_shortcode');
brasero
sqlite3
postgres
firefox
chrome
chromium
emacs terminal
wezterm nigthly terminal
alacrity
tilix
dolphin
archivos
thunderbird
telegram
postman
discover
visual studio code 
la batalla por wesnoth
muon ssh clien
anydesk

una imagen es el empaquetador que contiene las dependencias el codigo y es lo que se comparte

un container son capas tras capas de imagenes

existen tres tipos de virtualizaciones en las VM virtualmachine
1.- para virtualizacion
en la paravirtualizacion intenta entregar la mayor cantidad de acceso del sistema anfitrion de su hardware a los cientes en el contenedor

2.- virtualizacion parcial
donde algunos componentes del hardware se virtualizan para en sistema operativo cliente

3.- virtualizacion completa:
donde absolutamente todos los componentes o hardware que esta utilizando el sistema operativo cliente son virtualizados de esta manera los sistemas operativos cliente no acceden en los absoluto al hardware

para todos los casos anteriores docker va a ser absolutamente superior y va a utilizar el kernel del sistema opetativo anfitrion y esto se traduce en rendimiento, los contenedores de docker parten casi que instantaneamente, obteniendo un rendimiento muy superior a todas las alternativas mencionadas anteriormente fin de la teoria


docker desktop es una maquina virtual se encuentra optimizada
corre linux
ejecuta containers
permite acceder al sistema de archivos y tambien a la red(interna y externa)

docker desktop no es una unica herramienta viene con otras herramientas que nos sirven para trabajar con nuestras imagenes y tambien con nuestros containers dentro de estas herramientes tenemos 

docker compose, docker cli ademas de otras herramientas

puede correr de manera nativa en windows con la herramienta WSL2(windows subsystem for linux)


existe una alternativa de instalacion para windows,linux y mac

para windows una sola opcion solamente es descargarlo y presionar siguiente siguiente siguente y listo

para mac existen dos alternatinas pulsar la de la derecha en la pagina web de docker

para linux docker ya tiene paquetes de instalacion pre compilados dependiendo de la version de linux que estes utilizando utiliza la alternativa que mas te funcione

que es dockerHUB: es un repositorio de imagenes o contenedores disponibles para comenzar a trabajar oficiales para utilizar

proceso para instalarlo
* docker images : devuelve un listado completo de todas las imagenes que hallamos descargado en nuestra maquina
donde repositorio te muestra el nombre de la imagen que se halla descargado, cada repositorio puede tener una o mas etiquetas con la version de la imagen

para descargar una imagen tenemos dos alternativas con el siguiente comando
1.-descargar la version que nosotros queremos
2.- no especificar nada esto va a descargar la ultima version de la imagen que queramos descargar
ejemplo:
* docker pull node

este comando te descargara cada una de las capas que componen la imagen de manera que si tenemos que descargar otra imagen y sus capas ya han sido descargadas por otro imagen las capas ya descargadas anteriormente ya no se volveran a descargar de esta manera de aprovecha espacio y tambien las distintas imagenes para optimizar un poco mas el espacio que estas van a utilizar en el disco duro

para descargar una version especifica de una imagen
* docker pull node:18

la imagen id es la misma que las otras versiones relativamente similares lo que cambia es la etiqueta de la version

para descargar la imagende mysql 
en mac se debe colocar 
* docker pull --platform linux/x86_64 mysql

normal es 

* docker pull mysql

tambien podemos indicar una version

* docker pull mysql:numeroversion

para eliminar una imagen en ejecucion el comando es

* docker image rm nombredelaimagen

la imagen de docker pull no necesita tantas configuraciones

Despues de descargar una imagen se procede a crear un contenedor

* docker create mongo (forma corta)

* docker container create mongo (forma larga) 

nos devuelve un id del contenedor (este id nos sirve para crear un contenedor)
el comando para ejecutar un contenedor es:

* docker start idContenedor (donde idcontenedor es el codigo id largo del contenedor) esto nos devuelve el id del contenedor nuevamente

* docker ps : este comando es como docker iamges pero se usa para ver los contenedores creados, cuando se crea un contenedor se le agrega un nombre de manera arbitraria al contenedor y ese nombre se puede usar en lugar del idcortocontenedor para eliminar el contenedor

* docker ps -a para ver todos los contenedores incluso los que no se estan ejecutando

para detener el contenedor se debe usar el comando

* docker stop idcortocontenedor

para asignar un nombre a un contenedor:

* docker create --name nombreContenedor esto nos devuelve el idlargo del contenedor indicando que ya se ha creado el contenedor

y como ya le hemos asignado un nombre al contenedor podemos iniciarlo con:

* Docker start nombreContenedorAsignado

para poder guardar datos dentro de un contenedor se debe mapear el puerto local al puerto del contenedor:

* docker create -p27017:27017 --name nombreContenedor nombreImagenBase donde lo que esta antes del : es el puerto de la maquina nuestra la maquina local y lo que esta despues del : es el puerto interno del contenedor, siempre asignale un puerto a cada contenedor creado por que si dejas que docker asigne un puerto los va a asignar por encima del puerto 50mil

con el comando 
docker logs nombreContenedor  puedes ver todos los logs que este nos muestra y tambien puedes verlo con

* docker logs --follow nombreContenedor la diferencia es que este se queda escuchando y mostrando los logs en tiempo real

el comando docker run hace tres cosas 
1.-descarga la imagen
2.-crea el contenedor
3.-inicia el contenedor

* ejemplo docker run mongo
docker run mongo

los siguientes dos comandos devulven el id del contenedor creado
docker run -d mongo este nos asigna un nombre arbitrariamente por docker
docker run --name nombreContenedor -p27017:27017 -d imagenbase este comando nos permite crear un contenedor mas personalizado

luego para ver el contenedor usa el comando 
* docker ps

configuracion del archivo dockerfile
tomar una aplicacion de docker un meterla dentro de un container
el archivo dockerfile no puede tener otro nombre se tiene que llamar dockerfile, este archivo se utiliza para que nosotros podamos construir nuestros containers, aqui nosotros vamos a escribir las instrucciones que necesita nuestro contenedor para poder crearse,m todas las imagenes que nosotros creemos siempre se tienen que basar en alguna otra imagen

ejemplo
* FROM node:etiquetaversion

RUN mkdir -p /home/app --esto es donde vamos a meter el codigo fuente de nuestra aplicacion, esta ruta no es una ruta fisita en nuestra maquina sino que es una ruta en el contenedor 

COPY . /home/app

EXPOSE 3000 ruta donde se va a ejecutar la aplicacion

CMD ["node","/home/app/index.js"]

ahora vamos a aprender a crear redes en docker

* docker ls : lista todas las redes existentes

* docker network create mired : este comando creara una nueva red dentro de docker este nos devolvera el id de la red creada

* docker network rm mired este comando elimina la red creada anteriormente

el siguiente comando recibe dos argumentos (nombreDadoPorMI,rutanodenosencontramos ) y se utiliza para construir contenedores en base a un archivo dockerfile

* docker build -t miapp:etiquetaversiondadapormi .

*docker create -P27017:27017 --name monguito --network mired -e MONGO_INITDB_ROOT_USERNAME=nico -e MONGO_INIT_DB_ROOT_PASSWORD=password mongo

ahora para colocar el contenedor de la aplicacion que nosotros acabamos de colocar dentro de una imagen

*docker create -p3000 --name chanchito --network mired miapp:1

*luego escribir docker ps -a

luego de hacer esto debemos arrancar los dos contenedores que creamos y que estan dentro de una misma red
sudo docker start monguito
sudo docker start chanchito

resumen de pasos para poder crear contenedores y tambien conectarlos
descargar la imagen
crear una red
crear el contenedor
	asignar puertos 
    asignar un nombre
    variables de entorno
    especificar la red
    indicar la imagen:consuetiqueta
todo esto por cada contenedor

para automatizar todo los pasos anteriores existe la herramienta docker compose
para esto debemos crear y editar un archivo con extension.yml

la estructura de este archivo es la siguiente
version:"3.9"
services:
	chanchito:
		build: .
        ports:
			-"3000:3000"
		links:
			-monguito
	monguito:
		imagen:mongo
        	ports:"27017:27017"
		environment:
			- MONGO_INITDB_ROOT_USERNAME=nico
			- MONGO_INITDB_ROOT_PASSWORD=password

ahora para ejecutar un archivo docker yml o docker compose se utiliza el siguiente comando:
docker compose up

luego verificas las imagenes creadadas con 

*docker images

con el comando 
docker compose down que es lo contrario de docker compose up, para eliminartodo lo que se creo anteriormente con docker compose up

para trabajar con volumenes vamos al final del archivo compose 
version:"3.9"
services:
	chanchito:
		build: .
        ports:
			-"3000:3000"
		links:
			-monguito
	monguito:
		imagen:mongo
        	ports:"27017:27017"
		environment:
			- MONGO_INITDB_ROOT_USERNAME=nico
			- MONGO_INITDB_ROOT_PASSWORD=password
		volumes:
			-mongo-data:/data/db
            # mysql -> var/lib/mysql
            # postgres -> var/lib/postgresql/data
volumes:
	mongo_data:

para crear multiples ambientes de desarrollo mientras estamos trabajando con docker
primero debemos crear un archivo con extension.dev ejemplo dockerfile.yml ya que el archivo que teniamos anterior mente quizas queramos usarlo para produccion ejemplo dockerfile.dev la estructura este este archivo es parecida al archivo dockerfile anterior con algunas diferencias

FROM node:18

RUN npm i -g nodemon
RUN mkdir -p /home/app

WORKDIR /home/app

EXPOSE 3000

CMD ["nodemon","index.js"]

ademas de este archivo demos crear un archivo compose para desarrollo tambien al cual llamaremos docker-compose-dev.yml con la siguiente estructura
version:"3.9"
services:
	chanchito:
		build: 
        context: .
        dockerfile:dockerfile.dev
        ports:
			-"3000:3000"
		links:
			-monguito
		volumes: 
			- .:/home/app
	monguito:
		imagen:mongo
        	ports:"27017:27017"
		environment:
			- MONGO_INITDB_ROOT_USERNAME=nico
			- MONGO_INITDB_ROOT_PASSWORD=password
		volumes:
			-mongo-data:/data/db
            # mysql -> var/lib/mysql
            # postgres -> var/lib/postgresql/data
volumes:
	mongo_data:

para provar el archivo que acabamos de construir utilizamos el siguiente comando, un archivo docker compose completamente customisado que no sea docker-compose.yml

docker compose -f docker-compose-dev.yml up
$.ajax({
  type: "POST",
  url: url,
  data: data,
  success: success,
  dataType: dataType
});
sudo apt-get install alacritty
      //				tilix
		//				wezterm-nightly  --esto se consigue como un archivo app
// Loop through each item in the order
                        // This loop processes each individual item within the order to extract its specific info
                        foreach ($order->get_items() as $item_id => $item) {

                            // Retrieve the ID of the product associated with the current item in the order
                            $product_id = $item->get_product_id();
                            // Check if the current item's product ID matches the product ID we're processing in this loop iteration
                            if ($product_id == $pid) {
                                // Get the total price and subtotal price specific to this order item
                                // These values are specific to each item in the order, rather than the order as a whole
                                $line_total = wc_get_order_item_meta($item_id, '_line_total', true);
                                $line_subtotal = wc_get_order_item_meta($item_id, '_line_subtotal', true);
                                // ... extract other relevant data ... for now the amounts are ok
            
                                // Build the report entry for this product
                                array_push($order_data,[
                                    'order_id'         => $order_id,
                                    'customer_first'   => $order->get_billing_first_name(),
                                    'customer_last'    => $order->get_billing_last_name(),
                                    'order_created'    => date("d/m/Y",strtotime($order->get_date_created())),
                                    'email'            => $order->get_billing_email(),
                                    'phone'            => $order->get_billing_phone(),
                                    'orders_status'    => $order_status,
                                    'invoice_no'       => $formatted_invoice_number,
                                    'credit_note'      => $credit_note,
                                    'invoice_date'     => $invoice_date,
                                    'credit_note_date' => $credit_note_date,//date("d/m/Y",strtotime($credit_note_date)),
                                    'wooco_currency'   => $currency_symbol,
                                    'gross'            => round($line_subtotal,2),
                                    'discount'         => round($order->get_total_discount(),2),
                                    'net_total'        => round($line_total,2),
                                    'course_id'        => self::get_product_sku($pid),
                                    'course_start'     => $course_start,
                                    'course_ends'      => $course_end,
                                    'student_id'       => $assign_student_id_value
                                ]);
                            }  
                        }
// func that is going to set our title of our customer magically
function w2w_customers_set_title( $data , $postarr ) {

    // We only care if it's our customer
    if( $data[ 'post_type' ] === 'w2w-customers' ) {

        // get the customer name from _POST or from post_meta
        $customer_name = ( ! empty( $_POST[ 'customer_name' ] ) ) ? $_POST[ 'customer_name' ] : get_post_meta( $postarr[ 'ID' ], 'customer_name', true );

        // if the name is not empty, we want to set the title
        if( $customer_name !== '' ) {

            // sanitize name for title
            $data[ 'post_title' ] = $customer_name;
            // sanitize the name for the slug
            $data[ 'post_name' ]  = sanitize_title( sanitize_title_with_dashes( $customer_name, '', 'save' ) );
        }
    }
    return $data;
}
add_filter( 'wp_insert_post_data' , 'w2w_customers_set_title' , '99', 2 );
function update_post( $post_id ) {
   $post = array(
     'ID'         => $post_id,
     'post_title' => '#'.$post_id,
     'post_name'  => $post_id,
   );
   wp_update_post( $post );
   update_post_meta($post_id, 'order', $post_id);
}
add_action('save_post_booking', 'update_post', 20);
/*
* Plugin Name: Course Taxonomy
* Description: A short example showing how to add a taxonomy called Course.
* Version: 1.0
* Author: developer.wordpress.org
* Author URI: https://codex.wordpress.org/User:Aternus
*/

function wporg_register_taxonomy_course() {
	 $labels = array(
		 'name'              => _x( 'Courses', 'taxonomy general name' ),
		 'singular_name'     => _x( 'Course', 'taxonomy singular name' ),
		 'search_items'      => __( 'Search Courses' ),
		 'all_items'         => __( 'All Courses' ),
		 'parent_item'       => __( 'Parent Course' ),
		 'parent_item_colon' => __( 'Parent Course:' ),
		 'edit_item'         => __( 'Edit Course' ),
		 'update_item'       => __( 'Update Course' ),
		 'add_new_item'      => __( 'Add New Course' ),
		 'new_item_name'     => __( 'New Course Name' ),
		 'menu_name'         => __( 'Course' ),
	 );
	 $args   = array(
		 'hierarchical'      => true, // make it hierarchical (like categories)
		 'labels'            => $labels,
		 'show_ui'           => true,
		 'show_admin_column' => true,
		 'query_var'         => true,
		 'rewrite'           => [ 'slug' => 'course' ],
	 );
	 register_taxonomy( 'course', [ 'post' ], $args );
}
add_action( 'init', 'wporg_register_taxonomy_course' );
<?php
$args = array(
	'post_type'      => 'product',
	'posts_per_page' => 10,
);
$loop = new WP_Query($args);
while ( $loop->have_posts() ) {
	$loop->the_post();
	?>
	<div class="entry-content">
		<?php the_title(); ?>
		<?php the_content(); ?>
	</div>
	<?php
}
mv mover y tambien sirve para cambiar el nombre
mv nombrearchivoacambiar nuevomobre.ext && mv nuevonombre.ext /rutadondeguardarlo
principio de la tabla:
[
  'class' => 'yii\grid\ActionColumn',
            'contentOptions' => ['style' => 'text-align:center; width:2%; vertical-align:middle;'],
 ]
Final de la tabla:
'class' => 'yii\grid\ActionColumn',
            'contentOptions' => ['style' => 'text-align:center; width:2%; vertical-align:middle;'],
  
listas:
'id_reporte' => [
            'attribute' => 'id_reporte',
            'headerOptions' => ['style' => 'text-align:center; width:5%;text-color:white;'],
            'contentOptions' => ['style' => 'text-align:center; vertical-align:middle; white-space: pre-line;'],
            'label' => 'Tipo de Reporte',
            'filter' => app\models\Reportes::lista(),
            'format' => 'html',
            'value' => function ($data) {
                $s = app\models\Reportes::find()->where(['id_reporte' => $data->id_reporte])->one();
                $desc_reporte = ($s) ? $s->desc_reporte : '';
                $desc_reporte = nl2br($desc_reporte);
                $desc_reporte = wordwrap($desc_reporte, 20, "<br>\n");
                return $desc_reporte;
            }
        ],

campos:
'attribute' => 'fecha_hora',
            'value' => 'fecha_hora',
            'headerOptions' => ['style' => 'text-align:center; width:10%;text-color:white;'],
            'contentOptions' => ['style' => 'text-align:center; vertical-align:middle;'],
add_action('wp_ajax_add_product_to_cart', 'add_product_to_cart_ajax');
add_action('wp_ajax_nopriv_add_product_to_cart', 'add_product_to_cart_ajax');

function add_product_to_cart_ajax() {
    $product_id = isset($_POST['product_id']) ? intval($_POST['product_id']) : 0;
    $quantity = isset($_POST['quantity']) ? intval($_POST['quantity']) : 1;

    if ($product_id > 0) {
        WC()->cart->add_to_cart($product_id, $quantity);
        wp_send_json('Product added to cart');
    } else {
        wp_send_json('Invalid product');
    }
}

//second custom code to direct checkout.

add_filter('woocommerce_add_to_cart_redirect', 'custom_add_to_cart_redirect');

function custom_add_to_cart_redirect($url) {
    global $woocommerce;
    $checkout_url = wc_get_checkout_url();

    return $checkout_url;
}
<html>
  <head>
    <link rel="stylesheet" type="text/css" href="style.css">

  </head>

  <body>
      <button onclick="changeColor()">Repaint!</button>
  </body>
  
      <script>
        function getRandomColor(){
          let letters = '0123456789ABCDEF';
          let color = '#';
          for (let i = 0; i < 6; i++) {
            color += letters[Math.floor(Math.random() * 16)];
          }
          return color;
        }
        function changeColor(){
          let newColor = getRandomColor();
          document.body.style.backgroundColor = newColor;
        }
    </script>
  
</html>
function custom_product_price($price, $product) {
    // Change the price for product with ID 46
    if ($product && $product->get_id() === 46) {
        $price = '500.00'; // Set the desired price
    }

    return $price;
}

add_filter('woocommerce_get_price_html', 'custom_product_price', 10, 2);
add_filter('woocommerce_cart_item_price', 'custom_product_price', 10, 2);
add_filter('woocommerce_cart_item_subtotal', 'custom_product_price', 10, 3);
    
// Form to add a record   to display products dropdown v1.2 starts
echo '<form id="add-record-form" style="display: flex; flex-direction: row;">
<div class="main_container" style="margin-right: 20px;">
    <label for="product_name">Product Name:</label>
    <select id="product_name" name="product_name">';
    
// Retrieve product names from the database
$query = new WP_Query(array(
    'post_type' => 'product',
    'post_status' => 'publish',
    'posts_per_page' => '-1'
));

if ($query->have_posts()) :
    while ($query->have_posts()) : $query->the_post();
        echo '<option value="' . get_the_title() . '">' . get_the_title() . '</option>';
    endwhile;
    wp_reset_postdata();
else:
    echo '<option value="">No products found</option>';
endif;

echo '</select>
</div>';

// v1.2 stops
// Modify quantity input and add remove icon
add_filter('woocommerce_checkout_cart_item_quantity', 'bbloomer_checkout_item_quantity_input', 9999, 3);

function bbloomer_checkout_item_quantity_input($product_quantity, $cart_item, $cart_item_key) {
    $product = apply_filters('woocommerce_cart_item_product', $cart_item['data'], $cart_item, $cart_item_key);
    $product_id = apply_filters('woocommerce_cart_item_product_id', $cart_item['product_id'], $cart_item, $cart_item_key);

    if (!$product->is_sold_individually()) {
        $product_quantity = woocommerce_quantity_input(array(
            'input_name'  => 'shipping_method_qty_' . $product_id,
            'input_value' => $cart_item['quantity'],
            'max_value'   => $product->get_max_purchase_quantity(),
            'min_value'   => '0',
        ), $product, false);

        // Add remove icon
        $product_quantity .= '<a href="#" class="remove-product" data-product-key="' . $cart_item_key . '">x</a>';

        $product_quantity .= '<input type="hidden" name="product_key_' . $product_id . '" value="' . $cart_item_key . '">';
    }

    return $product_quantity;
}

// Add JavaScript to handle product removal
add_action('wp_footer', 'add_product_removal_script');

function add_product_removal_script() {
    ?>
    <script>
        document.addEventListener('click', function (event) {
            if (event.target.classList.contains('remove-product')) {
                event.preventDefault();
                const productKey = event.target.getAttribute('data-product-key');
                const form = event.target.closest('form');

                if (form && productKey) {
                    // Remove the product from the cart via AJAX
                    jQuery.ajax({
                        type: 'POST',
                        url: wc_checkout_params.ajax_url,
                        data: {
                            action: 'remove_product_from_cart',
                            product_key: productKey
                        },
                        success: function (response) {
                            // Reload the checkout page to reflect the updated cart
                            window.location.reload();
                        }
                    });
                }
            }
        });
    </script>
    <?php
}
add_action('wp_ajax_remove_product_from_cart', 'remove_product_from_cart');

function remove_product_from_cart() {
    if (isset($_POST['product_key'])) {
        $product_key = sanitize_text_field($_POST['product_key']);
        WC()->cart->remove_cart_item($product_key);
        echo 'success';
    }

    wp_die();
}


// Detect Quantity Change and Recalculate Totals
add_action('woocommerce_checkout_update_order_review', 'bbloomer_update_item_quantity_checkout');

function bbloomer_update_item_quantity_checkout($post_data) {
    parse_str($post_data, $post_data_array);
    $updated_qty = false;
    $updated_remove = false;

    foreach ($post_data_array as $key => $value) {
        if (substr($key, 0, 20) === 'shipping_method_qty_') {
            $id = substr($key, 20);
            WC()->cart->set_quantity($post_data_array['product_key_' . $id], $post_data_array[$key], false);
            $updated_qty = true;
        } elseif (substr($key, 0, 15) === 'remove_product_') {
            $cart_item_key = substr($key, 15);
            WC()->cart->remove_cart_item($cart_item_key);
            $updated_remove = true;
        }
    }

    if ($updated_qty || $updated_remove) {
        WC()->cart->calculate_totals();
    }
}
<?php

require 'vendor/autoload.php';

// Create a client with a base URI

$client = new \GuzzleHttp\Client(['base_uri' => 'https://rbt5.namnguyen68.repl.co']);

// Send a request

$response = $client->request('GET', 'html/begin');

$body = $response->getBody();

echo $body;

// Send a request

$response = $client->request('GET', 'title/a');

$body = $response->getBody();

echo $body;

// Send a request

$response = $client->request('GET', 'body/begin');

$body = $response->getBody();

echo $body;

?>

<?php

// Create a client with a base URI

$client = new \GuzzleHttp\Client(['base_uri' => 'https://rbt5.namnguyen68.repl.co']);

// Send a request

$response = $client->request('GET', 'html/end');

$body = $response->getBody();

echo $body;

?>

alt + z = ajuta la lineas de codigo para que se vea la linea completa en la pantalla
ctrl + shift + a= comenta varias lineas de cdigo
ctrl + f = buscar en el codigo o buscar en archivos debo seleccionar el lugar en donde voy a buscar
ctrl + shift + p = abre la paleta de comandos
DOCTYPE: html
  html lang="en"
    head
    #text: ⏎␣␣
      title
      #text: Sample page
      #text: ⏎␣
    #text: ⏎␣
    body
    #text: ⏎␣␣
      h1
      #text: Sample page
      #text: ⏎␣␣
      p
        #text: This is a
        a href="demo.html"
      	 #text: simple
      #text: sample.
      #text: ⏎␣␣
      #comment: this is a comment
     #text: ⏎␣⏎
$my_repeater = get_field('cosa_facciamo_home');

            // Verifica se il campo ripetitore esiste
            if ($my_repeater) :
                
                // Loop attraverso le istanze del campo ripetitore
                foreach ($my_repeater as $item) :
                    // Recupera il campo di gruppo all'interno del ripetitore
                    $my_group = $item['cosa_facciamo_items'];

                    // Recupera i valori all'interno del campo di gruppo
                    $field_value_1 = $my_group['titolo_cosa-facciamo'];
                    $field_value_2 = $my_group['testo_cosa_facciamo'];

                    // Puoi ora utilizzare questi valori come desideri
                    echo 'Valore del campo personalizzato 1: ' . $field_value_1 . '<br>';
                    echo 'Valore del campo personalizzato 2: ' . $field_value_2 . '<br>';
                endforeach;
            endif;
function edit_button_shortcode() {
    // Check if the user is logged in
    if (is_user_logged_in()) {
        global $wpdb;
        $user_id = get_current_user_id();

        // Check if the user's ID exists in the wp_fluentform_submissions table
        $results = $wpdb->get_results($wpdb->prepare("SELECT * FROM {$wpdb->prefix}fluentform_submissions WHERE user_id = %d", $user_id));

        // If the user's ID exists in the table, display the "Edit" button
        if ($results) {
            return '<a href="YOUR_EDIT_URL_HERE" class="edit-button">Edit</a>';
        }
    }
    return '';  // If the user is not logged in or their ID doesn't exist in the table, return an empty string
}
add_shortcode('edit_button', 'edit_button_shortcode');
brew install shivammathur/php/php@8.2

brew unlink php@7.4 && brew link --force --overwrite php@8.2

add_filter( 'woocommerce_checkout_cart_item_quantity', 'bbloomer_checkout_item_quantity_input', 9999, 3 );
  
function bbloomer_checkout_item_quantity_input( $product_quantity, $cart_item, $cart_item_key ) {
   $product = apply_filters( 'woocommerce_cart_item_product', $cart_item['data'], $cart_item, $cart_item_key );
   $product_id = apply_filters( 'woocommerce_cart_item_product_id', $cart_item['product_id'], $cart_item, $cart_item_key );
   if ( ! $product->is_sold_individually() ) {
      $product_quantity = woocommerce_quantity_input( array(
         'input_name'  => 'shipping_method_qty_' . $product_id,
         'input_value' => $cart_item['quantity'],
         'max_value'   => $product->get_max_purchase_quantity(),
         'min_value'   => '0',
      ), $product, false );
      $product_quantity .= '<input type="hidden" name="product_key_' . $product_id . '" value="' . $cart_item_key . '">';
   }
   return $product_quantity;
}
 
// ----------------------------
// Detect Quantity Change and Recalculate Totals
 
add_action( 'woocommerce_checkout_update_order_review', 'bbloomer_update_item_quantity_checkout' );
 
function bbloomer_update_item_quantity_checkout( $post_data ) {
   parse_str( $post_data, $post_data_array );
   $updated_qty = false;
   foreach ( $post_data_array as $key => $value ) {   
      if ( substr( $key, 0, 20 ) === 'shipping_method_qty_' ) {         
         $id = substr( $key, 20 );   
         WC()->cart->set_quantity( $post_data_array['product_key_' . $id], $post_data_array[$key], false );
         $updated_qty = true;
      }     
   }  
   if ( $updated_qty ) WC()->cart->calculate_totals();
}
define( 'RECOVERY_MODE_EMAIL', 'myemail@example.com' );
add_filter('woocommerce_add_to_cart_redirect', 'custom_add_to_cart_redirect');

function custom_add_to_cart_redirect($url) {
    global $woocommerce;
    $checkout_url = wc_get_checkout_url();

    return $checkout_url;
}
function custom_checkout_text_change( $translated_text, $text, $domain ) {
    if ( $domain === 'woocommerce' && $text === 'Billing details' ) {
        $translated_text = 'Billing Details';
    }
    return $translated_text;
}
add_filter( 'gettext', 'custom_checkout_text_change', 20, 3 );
for "laravel-mix": "^6.0.49",

"scripts": {
    "dev": "npm run development",
    "development": "mix",
    "watch": "mix watch",
    "watch-poll": "mix watch -- --watch-options-poll=1000",
    "hot": "mix watch --hot",
    "prod": "npm run production",
    "production": "mix --production"
},




"scripts": {
    "dev": "npm run development",
    "development": "mix",
    "watch": "mix watch",
    "watch-poll": "mix watch -- --watch-options-poll=1000",
    "hot": "mix watch --hot",
    "prod": "npm run production",
    "production": "mix --production"
},
require_once __DIR__ . '/vendor/autoload.php';

$klein = new \Klein\Klein();

$klein->respond('GET', 'name/[:name]', function ($request) {
    return 'Hello ' . $request->name;
});

$klein->dispatch();
function bulk_modifier_page() {
    global $wpdb;

    if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_FILES['csv_file'])) {
        // Check if a CSV file is uploaded successfully
        if ($_FILES['csv_file']['error'] == UPLOAD_ERR_OK) {
            $file = $_FILES['csv_file']['tmp_name'];

            // Read the CSV file
            $csv_data = array_map('str_getcsv', file($file));
            $csv_headers = array_shift($csv_data); // Get headers

            // Define the mapping of CSV columns to database columns for wp_za_groups table
            $group_column_mapping = array(
                'group_name' => 'title',
                'priority' => 'priority',
                'apply_to' => 'apply_to',
                'author_id' => 'admin_id',
                'created_at' => 'created_at',
                'created_at_gmt' => 'created_at_gmt',
                'updated_at' => 'updated_at',
                'updated_at_gmt' => 'updated_at_gmt'
            );

            // Define the mapping of CSV columns to database columns for wp_za_types table
            $type_column_mapping = array(
                'title_name' => 'title',
                'type' => 'type',
                'status' => 'status',
                'description' => 'description',
                'required' => 'required',
                'display_description_on_expansion' => 'display_description_on_expansion',
                'hide_description' => 'hide_description',
                'tooltip_description' => 'tooltip_description',
                'created_at' => 'created_at',
                'created_at_gmt' => 'created_at_gmt',
                'updated_at' => 'updated_at',
                'updated_at_gmt' => 'updated_at_gmt'
            );

            // Define the mapping of CSV columns to database columns for wp_za_values table
            $value_column_mapping = array(
                'addons_title' => 'title',
                'price' => 'price',
                'description_value' => 'description',
                'sku' => 'sku',
            );

            // Insert data into the wp_za_groups, wp_za_types, wp_za_values, wp_za_products_to_groups, and wp_za_categories_to_groups tables
            foreach ($csv_data as $row) {
                // Prepare data for wp_za_groups table
                $group_data = array();
                foreach ($csv_headers as $key => $header) {
                    if (isset($group_column_mapping[$header])) {
                        $group_data[$group_column_mapping[$header]] = $row[$key];
                    }
                }

                // Set default values for created_at, created_at_gmt, updated_at, updated_at_gmt
                $group_data['created_at'] = current_time('mysql');
                $group_data['created_at_gmt'] = current_time('mysql', true);
                $group_data['updated_at'] = current_time('mysql');
                $group_data['updated_at_gmt'] = current_time('mysql', true);

                // Insert data into the wp_za_groups table
                $wpdb->insert($wpdb->prefix . 'za_groups', $group_data);
                $group_id = $wpdb->insert_id; // Get the group ID

                // Prepare data for wp_za_types table
                $type_data = array(
                    'group_id' => $group_id,
                    'step' => 0, // Default value
                    'accordion' => 'open', // Default value
                );

                // Map CSV columns to database columns for wp_za_types table and set default values
                foreach ($csv_headers as $key => $header) {
                    if (isset($type_column_mapping[$header])) {
                        if ($header === 'status' && !isset($type_data['status'])) {
                            // Set default status if not present in CSV
                            $type_data['status'] = 'enable';
                        } elseif ($header === 'description' && !isset($type_data['description'])) {
                            // Set default description if not present in CSV
                            $type_data['description'] = 'none';
                        } elseif ($header === 'required' && !isset($type_data['required'])) {
                            // Set default required value if not present in CSV
                            $type_data['required'] = 0;
                        } elseif ($header === 'display_description_on_expansion' && !isset($type_data['display_description_on_expansion'])) {
                            // Set default display_description_on_expansion value if not present in CSV
                            $type_data['display_description_on_expansion'] = 0;
                        } elseif ($header === 'hide_description' && !isset($type_data['hide_description'])) {
                            // Set default hide_description value if not present in CSV
                            $type_data['hide_description'] = 0;
                        } elseif ($header === 'tooltip_description' && !isset($type_data['tooltip_description'])) {
                            // Set default tooltip_description value if not present in CSV
                            $type_data['tooltip_description'] = 0;
                        } else {
                            $type_data[$type_column_mapping[$header]] = $row[$key];
                        }
                    }
                }

                // Set default values for created_at, created_at_gmt, updated_at, updated_at_gmt
                $type_data['created_at'] = current_time('mysql');
                $type_data['created_at_gmt'] = current_time('mysql', true);
                $type_data['updated_at'] = current_time('mysql');
                $type_data['updated_at_gmt'] = current_time('mysql', true);

                // Insert data into the wp_za_types table
                $wpdb->insert($wpdb->prefix . 'za_types', $type_data);
                $type_id = $wpdb->insert_id; // Get the type ID

                // Prepare data for wp_za_values table
                $value_data = array(
                    'type_id' => $type_id,
                    'step' => $wpdb->get_var("SELECT COUNT(*) FROM " . $wpdb->prefix . "za_values WHERE type_id = $type_id") + 1, // Increment step
                );

                // Map CSV columns to database columns for wp_za_values table and set default values
                foreach ($csv_headers as $key => $header) {
                    if (isset($value_column_mapping[$header])) {
                        if ($header === 'description_value' && !isset($value_data['description'])) {
                            // Set default description if not present in CSV
                            $value_data['description'] = 'no value';
                        } elseif ($header === 'checked' && !isset($value_data['checked'])) {
                            // Set default checked value if not present in CSV
                            $value_data['checked'] = 0;
                        } elseif ($header === 'hide_description' && !isset($value_data['hide_description'])) {
                            // Set default hide_description value if not present in CSV
                            $value_data['hide_description'] = 0;
                        } else {
                            $value_data[$value_column_mapping[$header]] = $row[$key];
                        }
                    }
                }

                // Set default values for created_at, created_at_gmt, updated_at, updated_at_gmt
                $value_data['created_at'] = current_time('mysql');
                $value_data['created_at_gmt'] = current_time('mysql', true);
                $value_data['updated_at'] = current_time('mysql');
                $value_data['updated_at_gmt'] = current_time('mysql', true);

                // Insert data into the wp_za_values table
                $wpdb->insert($wpdb->prefix . 'za_values', $value_data);
                $value_id = $wpdb->insert_id; // Get the value ID

                // Prepare data for wp_za_products_to_groups table
                $product_names = explode(',', $row[array_search('products_name', $csv_headers)]);
                foreach ($product_names as $product_name) {
                    $product_id = $wpdb->get_var("SELECT ID FROM " . $wpdb->posts . " WHERE post_title = '$product_name' AND post_type = 'product'");

                    if ($product_id) {
                        $product_to_group_data = array(
                            'product_id' => $product_id,
                            'group_id' => $group_id,
                        );

                        // Insert data into the wp_za_products_to_groups table
                        $wpdb->insert($wpdb->prefix . 'za_products_to_groups', $product_to_group_data);
                    }
                }

                // Prepare data for wp_za_categories_to_groups table
                $category_names = explode(',', $row[array_search('category_names', $csv_headers)]);
                foreach ($category_names as $category_name) {
                    // Get the category ID based on the category name
                    $category_id = $wpdb->get_var($wpdb->prepare("SELECT term_id FROM $wpdb->terms WHERE name = %s", $category_name));

                    if ($category_id) {
                        $category_to_group_data = array(
                            'category_id' => $category_id,
                            'group_id' => $group_id,
                        );

                        // Insert data into the wp_za_categories_to_groups table
                        $wpdb->insert($wpdb->prefix . 'za_categories_to_groups', $category_to_group_data);
                    }
                }
            }

            echo '<div class="updated"><p>Data imported successfully!</p></div>';
        } else {
            echo '<div class="error"><p>Error uploading CSV file.</p></div>';
        }
    }

    // Display the upload form
    ?>
   
    <div class="wrap">
        <h2>Bulk Modifier Upload</h2>
        <form method="post" action="" enctype="multipart/form-data">
            <input type="file" name="csv_file">
            <input type="submit" class="button button-primary" value="Upload CSV & Apply">
        </form>
    </div>
    
    <?php
}
aptitude search bash-completion
           //   bash sh-sequence-bash-completion
Ejecutamos este comando -basta con copy&paste- en la consola "sudo gedit /etc/bash.bashrc".
Descomentamos las tres últimas líneas de ese fichero que se ha abierto, quedando así:
if [ -f /etc/bashcompletion ]; then
. /etc/bashcompletion
fi

Una vez esté todo como el código que os mostramos podremos guardar de nuevo el fichero. Un apunte: antes de la primera línea hay un comentario que podéis dejar o eliminar. Yo personalmente os diría que no lo eliminéis para que sepáis para que sirve ese fichero en un futuro. Probad a comenzar a escribir un comando y pulsad TAB, veréis como se completa el comando automáticamente.

Un ejemplo muy básico para probar esta función es escribir "cd /h" y pulsar el tabulador, automáticamente debería aparecer "cd /home" en pantalla. Le dais a enter y ya tendréis el comando ejecutado.
https://code.visualstudio.com/docs/editor/tasks#vscode
<script type="application/ld+json">
    "@context" : "https://schema.org/",
    {{ $slot }}
</script>
function remove_core_updates(){
global $wp_version;
return (object) array(
'last_checked' => time(),
'version_checked' => $wp_version,
'updates' => array()
);
}
add_filter('pre_site_transient_update_core', 'remove_core_updates');
add_filter('pre_site_transient_update_plugins', 'remove_core_updates');
add_filter('pre_site_transient_update_themes', 'remove_core_updates');
{
    "editor.fontFamily": "Fira Code",
    "editor.fontLigatures": true,
    "window.zoomLevel": 1,
    "git.openRepositoryInParentFolders": "never",
    "security.workspace.trust.untrustedFiles": "open",
    "workbench.iconTheme": "material-icon-theme",
    "prettier.bracketSameLine": true,
    "editor.wordWrap": "on",
    "screencastMode.fontSize":20,
    "editor.tabSize": 2,
    "screencastMode.verticalOffset": 3,
    "settingsSync.ignoredExtensions": [
        "ms-ceintl.vscode-language-pack-es"
    ],
    "application.shellEnvironmentResolutionTimeout": 25,
    "workbench.colorTheme": "Night Owl",
    "launch": {
        "configurations": [
            
 
        ]
    }
}
Html:
Nota;para colocar el codigo Html solamente tipea !.

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Document</title>
</head>
<body>
  <div id="app">
    {{mensaje}}
    <hr>
    <input type="button" @click="mostrar=!mostrar" value="Click">
    <input v-if="mostrar" v-model="mensaje2">
  </div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.0.3/vue.js"></script>
</body>
</html>

JavaScript:
const app = new Vue ({
el:"#app",
  data: {
    mensaje:"Aja",
    mensaje2:"Hola Bomboncito",
    mostrar:false
  }
})
Salida:
add_action( 'woocommerce_product_options_pricing', 'genius_set_percentage_discount' );
 
function genius_set_percentage_discount() {
   global $product_object;
   woocommerce_wp_select(
      array(
         'id' => '_pc_discount',
         'value' => get_post_meta( $product_object->get_id(), '_pc_discount', true ),
         'label' => 'Discount %',
         'options' => array(
            '0' => '0',
            '10' => '10',
            '25' => '25',
            '50' => '50',
         ),
      )
   );
}
 
add_action( 'save_post_product', 'genius_save_percentage_discount' );
   
function genius_save_percentage_discount( $product_id ) {
    global $typenow;
    if ( 'product' === $typenow ) {
        if ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE ) return;
      if ( isset( $_POST['_pc_discount'] ) ) {
            update_post_meta( $product_id, '_pc_discount', $_POST['_pc_discount'] );
        }
    }
}
  
add_filter( 'woocommerce_get_price_html', 'genius_alter_price_display', 9999, 2 );
  
function genius_alter_price_display( $price_html, $product ) {
    if ( is_admin() ) return $price_html;
    if ( '' === $product->get_price() ) return $price_html;
    if ( get_post_meta( $product->get_id(), '_pc_discount', true ) && get_post_meta( $product->get_id(), '_pc_discount', true ) > 0 ) {
        $orig_price = wc_get_price_to_display( $product );
        $price_html = wc_format_sale_price( $orig_price, $orig_price * ( 100 - get_post_meta( $product->get_id(), '_pc_discount', true ) ) / 100 );
    }
    return $price_html;
}
  
add_action( 'woocommerce_before_calculate_totals', 'genius_alter_price_cart', 9999 );
  
function genius_alter_price_cart( $cart ) {
    if ( is_admin() && ! defined( 'DOING_AJAX' ) ) return;
    if ( did_action( 'woocommerce_before_calculate_totals' ) >= 2 ) return;
    foreach ( $cart->get_cart() as $cart_item_key => $cart_item ) {
        $product = $cart_item['data'];
      if ( get_post_meta( $product->get_id(), '_pc_discount', true ) && get_post_meta( $product->get_id(), '_pc_discount', true ) > 0 ) {
           $price = $product->get_price();
           $cart_item['data']->set_price( $price * ( 100 - get_post_meta( $product->get_id(), '_pc_discount', true ) ) / 100 );
      }
    }
}
<?php include 'FILENAME';?>
<?php Pjax::begin(); 
    $gridColumns = [
[
                'attribute' => 'avance',
                'headerOptions' => ['style' => 'text-align:center; '],
                'contentOptions' => ['style' => 'text-align:center; vertical-align:middle;'],
                'format' => 'raw',
                'value' => function($model) {
                    $string = $model->observacion;
                    $wrappedString = wordwrap($string, 40, "\n");
                    return '<div style="max-height: 80px; overflow: auto; max-width: 200px;">' . nl2br($wrappedString) . '</div>';
                },
                
            ],
            [
                'attribute' => 'observacion',
                'headerOptions' => ['style' => 'text-align:center; '],
                'contentOptions' => ['style' => 'text-align:center; vertical-align:middle;'],
                'format' => 'raw',
                'value' => function($model) {
                    $string = $model->observacion;
                    $wrappedString = wordwrap($string, 40, "\n");
                    return '<div style="max-height: 80px; overflow: auto; max-width: 200px;">' . nl2br($wrappedString) . '</div>';
                },
            ],
]; ?>
    Route::get('/notification', function () {
        $documentManagerFiles = DocumentManagerFile::where('ocr_project_id', 1)->where('revision', '>', 0 )->take(5)->get();
        // dd($documentManagerFiles);
        return (new DocumentManagerFileCreatedNotification($documentManagerFiles))
                    ->toMail(Auth::user());
    });
response = zoho.people.getRecords("P_Department");
$to = "recipient@example.com";
$subject = "Test Email";
$message = "This is a test email sent using PHP's mail() function.";
$headers = "From: sender@example.com";

if (mail($to, $subject, $message, $headers)) {
    echo "Email sent successfully.";
} else {
    echo "Email sending failed.";
}
    <?php
    $file_data = "Stuff you want to add\n";
    $file_data .= file_get_contents('database.txt');
    file_put_contents('database.txt', $file_data);
    ?>
$fp_source = fopen('database.txt', 'r');
$fp_dest = fopen('database_temp.txt', 'w'); // better to generate a real temp filename
fwrite($fp_dest, 'new content');
while (!feof($fp_source)) {
    $contents .= fread($fp_source, 8192);
    fwrite($fp_dest, $contents);
}
fclose($fp_source);
fclose($fp_dest);
unlink('database.txt');
rename('database_temp.txt','database.txt');
<?php
// error_reporting(E_ALL);
// ini_set('display_errors', 1);
error_reporting(0);
date_default_timezone_set('Asia/Kolkata');
function get($url)
{
  // Initialize a CURL session.
  $ch = curl_init();

  // Return Page contents.
  curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);

  //grab URL and pass it to the variable.
  curl_setopt($ch, CURLOPT_URL, $url);

  $result = curl_exec($ch);

  return $result;
}

$user = $_POST['user'];
$offer = $_POST['offer'];
$cname = $_POST['cname'];
$event = $_POST['event'];

$rp = get('https://nextpower.cashinmedia.in/api/v1/checkRefer/0a51d09c-f329-4436-89d5-bdbb52bea07c/' . $offer . '?number=' . $user . '');

// JSON response from the URL
$response = $rp;

// Decode the JSON response
$response_data = json_decode($response, true);

$totalClicks = $response_data['clicks'];

$count = $response_data['count'];

// Extract the 'data' section from the response
$data = $response_data['data'];

// Check if there's any data to display
if (count($data) > 0) {
  // Echo the table header
//     echo '<table border="1">
//         <tr>
//             <th>Click</th>
//             <th>User Amount</th>
//             <th>Refer Amount</th>
//             <th>User</th>
//             <th>Refer</th>
//             <th>Event</th>
//             <th>Status</th>
//             <th>Payment Status</th>
//             <th>Payment Message</th>
//             <th>Created At</th>
//         </tr>';

  //     // Loop through each data entry and display in table rows
//     foreach ($data as $entry) {
//     $userEncoded = preg_replace('/\d{5}(?=\d{4}$)/', 'xxxxx', $entry['user']);

  //     echo '<tr>';
//     echo '<td>' . $entry['click'] . '</td>';
//     echo '<td>' . $entry['userAmount'] . '</td>';
//     echo '<td>' . $entry['referAmount'] . '</td>';
//     echo '<td>' . $userEncoded . '</td>'; // Display encoded user
//     echo '<td>' . $entry['refer'] . '</td>';
//     echo '<td>' . $entry['event'] . '</td>';
//     echo '<td>' . $entry['status'] . '</td>';
//     echo '<td>' . $entry['referPaymentStatus'] . '</td>';
//     echo '<td>' . $entry['payMessage'] . '</td>';
//     echo '<td>' . $entry['createdAt'] . '</td>';
//     echo '</tr>';
// }

  //     // Close the table
//     echo '</table>';
// } else {
//     // If there's no data, show a JavaScript alert
//     echo '<script>alert("No data found.");</script>';
// }
  ?>
  <html lang="en" dir="ltr">


  <head>
    <meta charset="utf-8">
    <title>FokatCash</title>
    <link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Montserrat:wght@300;400;500;600&display=swap">
    <link rel="stylesheet" href="report.css">
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.4.1/jquery.min.js" charset="utf-8"></script>
    <meta name="viewport" content="width=device-width">
  </head>
  <style>
    .data-table td,
    .data-table th {
      font-size: 17px;
      /* Adjust the value as needed */
    }

    .credited {
      color: #FFA500;
      /* Orange color */
    }
  </style>

  <body>
    <center>
      <div class="login-form">
        <h1>
          <font color='#0f0f0f'>REPORT
        </h1>
        <center>

  </body>

  </html>

  <div class="statics">
    <center><br>
      <fieldset>Refferer:
        <?php echo $user; ?>
        <hr>Camp:
        <?php echo $cname; ?>
        <hr>Total Clicks:
        <?php echo $totalClicks; ?>
        <hr>Total Conversions: <span id="totalLeads">Calculating...</span> <!-- Placeholder for total leads -->
        <hr>
        <font color="#008000"> Cashback Sent: Rs. <span id="totalAcceptedReferAmount">Calculating...</span> </font>
        <!-- Placeholder for total refer amount -->
        <hr>
        <font color="#FFA500">Pending Cashback : Rs.<span id="totalPendingReferAmount">Calculating...</span></font>
        <hr>
      </fieldset><br><br>
      <table class="data-table">
        <tr>

          <th>Camp Name</th>
          <th>Refer Amount</th>
          <!--<th>Refer Status</th>-->
          <th>Cashback Status</th>
          <th>Time</th>
        </tr>
        <?php
        foreach ($data as $entry) {
          $userEncoded = preg_replace('/\d{5}(?=\d{4}$)/', 'xxxxx', $entry['user']);
          $dateTime = new DateTime($entry['createdAt']);

          // Convert to IST timezone
          $dateTime->setTimezone(new DateTimeZone('Asia/Kolkata'));

          // Format the time in desired format
          $istTimeFormatted = $dateTime->format('Y-m-d H:i:s');

          if ($entry['referPaymentStatus'] === 'REJECTED' || $entry['referPaymentStatus'] === 'BLOCKED') {
            continue;
          }

          if ($entry['referPaymentStatus'] == 'ACCEPTED' || $entry['referPaymentStatus'] == 'UNKNOWN' || $entry['referPaymentStatus'] == 'FAILURE') {
            $cashbackStatus = '<b><span style="color: #198754;">Credited</span></b>';
          } elseif ($entry['referPaymentStatus'] == 'PENDING') {
            $cashbackStatus = '<b><span style="color: #FFA500;">Processing</span></b>';
          } else {
            // Handle other cases or set a default value for $cashbackStatus
            // For example: $cashbackStatus = 'Unknown Status';
            $cashbackStatus = $entry['referPaymentStatus'];
          }


          if ($entry['referAmount'] > 0) {
            echo '<tr>';
            // echo '<td>' . $entry['click'] . '</td>';
            // echo '<td>' . $entry['userAmount'] . '</td>';
            echo '<td>' . $cname . '</td>';
            echo '<td>' . $entry['referAmount'] . '</td>';
            // echo '<td>' . $userEncoded . '</td>'; // Display encoded user
            // echo '<td>' . $entry['refer'] . '</td>';
            // echo '<td>' . $entry['event'] . '</td>';
            // echo '<td>' . $entry['status'] . '</td>';
            echo '<td>' . $cashbackStatus . '</td>';
            // echo '<td>' . $entry['payMessage'] . '</td>';
            echo '<td>' . $istTimeFormatted . '</td>';
            echo '</tr>';
          }
        }
        // Close the table
        echo '</table>';
} else {
  // If there's no data, show a JavaScript alert
  ?>
        <html lang="en" dir="ltr">


        <head>
          <meta charset="utf-8">
          <title>FokatCash</title>
          <link rel="stylesheet"
            href="https://fonts.googleapis.com/css2?family=Montserrat:wght@300;400;500;600&display=swap">
          <link rel="stylesheet" href="report.css">
          <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.4.1/jquery.min.js" charset="utf-8"></script>
          <meta name="viewport" content="width=device-width">
        </head>
        <style>
          .data-table td,
          .data-table th {
            font-size: 17px;
            /* Adjust the value as needed */
          }

          .credited {
            color: #FFA500;
            /* Orange color */
          }
        </style>

        <body>
          <center>
            <div class="login-form">
              <h1>
                <font color='#0f0f0f'>REPORT
              </h1>
              <center>

        </body>

        </html>

        <div class="statics">
          <center><br>
            <fieldset>Refferer:
              <?php echo $user; ?>
              <hr>Camp:
              <?php echo $cname; ?>
              <hr>Total Clicks:
              <?php echo $totalClicks; ?>
              <hr>Total Conversions: <span id="totalLeads">Calculating...</span> <!-- Placeholder for total leads -->
              <hr>
              <font color="#008000"> Cashback Sent: Rs. <span id="totalAcceptedReferAmount">Calculating...</span> </font>
              <!-- Placeholder for total refer amount -->
              <hr>
              <font color="#FFA500">Pending Cashback : Rs.<span id="totalPendingReferAmount">Calculating...</span></font>
              <hr>
            </fieldset><br><br>

            <h5>No data Found</h5>
            <?php


}
?>
    </table>
    <!-- ... Your existing code ... -->
    <script>
  // JavaScript to calculate and display the total leads count and total refer amounts
  document.addEventListener("DOMContentLoaded", function () {
    // Calculate the total leads count and total refer amounts based on the payment statuses and refer amount conditions
    var totalLeads = 0;
    var totalAcceptedReferAmount = 0;
    var totalPendingReferAmount = 0;
    var totalFailedReferAmount = 0;
    var totalUnknownReferAmount = 0;
    var event = "<?php echo $event; ?>";

    <?php foreach ($data as $entry): ?>
      <?php if ($entry['referPaymentStatus'] !== 'REJECTED' && $entry['referPaymentStatus'] !== 'BLOCKED' && $entry['referAmount'] > 0): ?>
        totalLeads++;
        <?php if ($entry['referPaymentStatus'] === 'ACCEPTED'): ?>
          totalAcceptedReferAmount += parseFloat(<?php echo $entry['referAmount']; ?>);
        <?php elseif ($entry['referPaymentStatus'] === 'PENDING'): ?>
          totalPendingReferAmount += parseFloat(<?php echo $entry['referAmount']; ?>);
        <?php elseif ($entry['referPaymentStatus'] === 'FAILURE'): ?>
          totalFailedReferAmount += parseFloat(<?php echo $entry['referAmount']; ?>);
        <?php elseif ($entry['referPaymentStatus'] === 'UNKNOWN'): ?>
          totalUnknownReferAmount += parseFloat(<?php echo $entry['referAmount']; ?>);
        <?php endif; ?>
      <?php endif; ?>
    <?php endforeach; ?>

    // Update the HTML content to display the calculated totals
    var totalLeadsElement = document.getElementById("totalLeads");
    totalLeadsElement.textContent = totalLeads;

    var totalAcceptedReferAmountElement = document.getElementById("totalAcceptedReferAmount");
    totalAcceptedReferAmountElement.textContent = totalAcceptedReferAmount.toFixed(2);

    var totalPendingReferAmountElement = document.getElementById("totalPendingReferAmount");
    totalPendingReferAmountElement.textContent = totalPendingReferAmount.toFixed(2);

    var totalFailedReferAmountElement = document.getElementById("totalFailedReferAmount");
    totalFailedReferAmountElement.textContent = totalFailedReferAmount.toFixed(2);

    var totalUnknownReferAmountElement = document.getElementById("totalUnknownReferAmount");
    totalUnknownReferAmountElement.textContent = totalUnknownReferAmount.toFixed(2);
  });
</script>



    <br><br><br>
    <footer id="footer">
      <div class="copyright">
        &copy; Copyright <strong><span>FokatCash</span></strong>
      </div>
    </footer><!-- End Footer -->
</div><!-- End statics div -->
</center><!-- End center div -->
</body><!-- End body tag -->

</html><!-- End HTML document -->
/**
 * Add activity ratio.
 */
function add_activity_ratio() {
  /** @var \Drupal\Core\Entity\EntityLastInstalledSchemaRepositoryInterface $schema_repository */
  $schema_repository = \Drupal::service('entity.last_installed_schema.repository');
  /** @var Drupal\Core\Entity\EntityTypeBundleInfo $entity_bundle_info */
  $entity_bundle_info = \Drupal::service('entity_type.bundle.info');
  /** @var Drupal\Core\Entity\EntityFieldManager $entity_field_manager */
  $entity_field_manager = \Drupal::service('entity_field.manager');
  $definitions = \Drupal::entityTypeManager()->getDefinitions();
  $entities = [];
  foreach ($definitions as $entity_type_id => $definition) {
    if (!$definition instanceof ConfigEntityType) {
      $entities[] = $entity_type_id;
    }
  }
  $spec = [
    'type' => 'numeric',
    'unsigned' => TRUE,
    'precision' => 5,
    'scale' => 2,
  ];
  $database = \Drupal::database();
  $schema = $database->schema();
  foreach ($entities as $entity_type_id) {
    $bundles = $entity_bundle_info->getBundleInfo($entity_type_id);
    foreach ($bundles as $bundle_id => $bundle) {
      $field_definitions = $entity_field_manager->getFieldDefinitions($entity_type_id, $bundle_id);
      foreach ($field_definitions as $field_definition) {
        if ($field_definition->getType() === 'pos_nace_field_type') {
          /** @var Drupal\field\Entity\FieldStorageConfig $storage */
          $storage = $field_definition->getFieldStorageDefinition();
          $storage->setSetting('activity_ratio', FALSE);
          $key_value = \Drupal::keyValue('entity.storage_schema.sql');
          $key_name = $entity_type_id . '.field_schema_data.' . $field_definition->getName();
          $storage_schema = $key_value->get($key_name);
          if ($storage instanceof FieldStorageConfig || $storage->isMultiple()) {
            foreach ([
              $entity_type_id . '__' . $field_definition->getName(),
              $entity_type_id . '_revision' . '__' . $field_definition->getName(),
            ] as $table) {
              $field_name = $field_definition->getName();
              if ($schema->tableExists($table) && !$schema->fieldExists($table, $field_name . '_activity_ratio')) {
                $schema->addField($table, $field_name . '_activity_ratio', $spec);
              }
            }
          }
          else {
            $table = $entity_type_id . '_field_data';
            $field_name = $field_definition->getName();
            if ($schema->tableExists($table) && !$schema->fieldExists($table, $field_name . '__activity_ratio')) {
              $schema->changeField($table, $field_name, $field_name . '__value', [
                'type' => 'varchar',
                'length' => 255,
                'binary' => FALSE,
              ]);
              $schema->addField($table, $field_name . '__activity_ratio', $spec);
              $storage_schema[$table]['fields'][$field_name . '__value'] = [
                'type' => 'varchar',
                'length' => 255,
                'binary' => FALSE,
              ];
              if (isset($storage_schema[$table]['fields'][$field_name])) {
                unset($storage_schema[$table]['fields'][$field_name]);
              }
              $storage_schema[$table]['fields'][$field_name . '__activity_ratio'] = $spec;
            }
          }
          $schema_repository->setLastInstalledFieldStorageDefinition($storage);
          $key_value->set($key_name, $storage_schema);
        }
      }
    }
  }
}
<?php
$month = date('m');
$year = date('Y');

// Get the first day of the month
$firstDayOfMonth = mktime(0, 0, 0, $month, 1, $year);

// Number of days in the month
$numberDays = date('t', $firstDayOfMonth);

// Get the name of the month
$monthName = date('F', $firstDayOfMonth);

// Get the day of the week for the first day of the month
$dayOfWeek = date('D', $firstDayOfMonth);

// Create a table to organize the calendar
echo "<h1>$monthName $year</h1>";
echo "<table>";
echo "<tr><th>Sun</th><th>Mon</th><th>Tue</th><th>Wed</th><th>Thu</th><th>Fri</th><th>Sat</th></tr><tr>";

// Pad the calendar with empty cells if the month doesn't start on a Sunday
if($dayOfWeek != 'Sun') {
  $blankDaysBefore = date('w', $firstDayOfMonth);
  for($i = 0; $i < $blankDaysBefore; $i++) {
    echo "<td></td>";
  }
}

// Fill in the rest of the calendar with the days of the month
for($dayCounter = 1; $dayCounter <= $numberDays; $dayCounter++) {
  $currentDay = mktime(0, 0, 0, $month, $dayCounter, $year);
  if(date('w', $currentDay) == 0) {
    echo "</tr><tr>";
  }
  echo "<td>$dayCounter</td>";
}

echo "</tr></table>";
?>
 $j==10<?php
for($i=1;$i<=10;$i++) {
    for($j=1;$j<=10;$j++) {
        if(($i==1 && $j>5) || ($i==10 && $j<=5) || ($j==1 && $i<=5) || ( $j==10 &&  $i>5) || ($j==5) || ($i==5) ) {
            echo "*  ";
        } else {
            echo "   ";
        }
    }
    echo "\n";
}
?>
********************************front-page.php********************************
<div class="popular-products">
    <?php echo do_shortcode('[products limit="4" orderby="popularity"]'); ?>
</div>

********************************function.php********************************
// Customize the classes inside the <ul> element for the products list.
function custom_woocommerce_product_loop_start($loop_output) {
    // Add custom classes to the <ul> element.
    $loop_output = str_replace('products', 'products custom-ul-class', $loop_output);
    return $loop_output;
}
add_filter('woocommerce_product_loop_start', 'custom_woocommerce_product_loop_start', 10, 1);
********************************style.css********************************

/* Custom styles for the popular products list */
ul.products.custom-ul-class {
    /* Add your custom styles here */
}

/**
 * Custom Fonts
 */

 function enqueue_custom_fonts() {
if(!is_admin()) {
wp_register_style('source_sans_pro','https://fonts.googleapis.com/css2?family=Indie+Flower&family=Montserrat:wght@900&family=Roboto:ital,wght@0,400;0,700;1,300;1,400&display=swap' );
wp_register_style('nunito','https://fonts.googleapis.com/css2?family=Nunito:ital,wght@0,400;0,700;1,400;1,700&display=swap' );
wp_enqueue_style('source_sans_pro' );
wp_enqueue_style('nunito' );
};
};

add_action('wp_enqueue_scripts','enqueue_custom_fonts');
// [current_user_display_name]
function display_current_user_display_name () {
    $user = wp_get_current_user();
    $display_name = $user->display_name;
    return $user->display_name;
}
add_shortcode('current_user_display_name', 'display_current_user_display_name');
#!/bin/bash

# Crea la base de datos
createdb 'nombre_de_tu_base_de_datos'

# Conecta a la base de datos
psql 'nombre_de_tu_base_de_datos' << EOF

# Crea la tabla
CREATE TABLE 'nombre_de_tu_tabla' (
  'nombre_de_tu_columna_1' tipo_de_dato_1,
  'nombre_de_tu_columna_2' tipo_de_dato_2,
  'nombre_de_tu_columna_3' tipo_de_dato_3,
  ...
);

# Sal del cliente de PostgreSQL
\q

EOF
#!/bin/bash

# Crea la base de datos
createdb 'nombre_de_tu_base_de_datos'

# Conecta a la base de datos
psql 'nombre_de_tu_base_de_datos' << EOF

# Crea la tabla
CREATE TABLE 'nombre_de_tu_tabla' (
  'nombre_de_tu_columna_1' tipo_de_dato_1,
  'nombre_de_tu_columna_2' tipo_de_dato_2,
  'nombre_de_tu_columna_3' tipo_de_dato_3,
  ...
);

# Sal del cliente de PostgreSQL
\q

EOF
//INDEX.PHP
<?php session_start();
//when login button pushed
if (isset($_POST['login'])){
//    if username and password not empty
    if (!empty($_POST['username']) && !empty($_POST['password'])){
//        store
        $_SESSION['username']  = $_POST["username"];
        $_SESSION['password']  = $_POST["password"];
//    take you to home.php
        header("Location: home.php");
    }else{
        echo "Missing username or password";
    }
}

?>
  
  
  
  
  //HOME.PHP
  <?php
session_start();
//if logout pressed
if (isset($_POST['logout'])){
//    destroys session
    session_destroy();
//    rerouts you to index
    header("Location: index.php");
}
echo $_SESSION['username'] . "<br>";
echo $_SESSION['password'] . "<br>";;



?>
<?php

setcookie("fav_food","pizza", time() + (86400 * 2), "/");
setcookie("fav_drink","water", time() + (86400 * 3), "/");
setcookie("fav_dessert","cookies", time() + (86400 * 4), "/");

foreach ($_COOKIE as $key => $value){
    echo "{$key} = {$value} <br>";
}


if (isset($_COOKIE['fav_food'])){
    echo "BUY SOME {$_COOKIE['fav_food']}";
}else{
    echo "I dont know ypu fav food";
}
<?php
    if (isset($_POST['submit'])){
        $username = filter_input(INPUT_POST, "username", FILTER_SANITIZE_SPECIAL_CHARS);
        echo "Hello {$username}";
    }
?>

<!doctype html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
</head>

<body>
    <form action="index.php" method="post">
        <input type="text" name="username" id="username">
        <input type="submit" name="submit">
    </form>

</body>

</html>
<?php
$result = null;
if(isset($_POST['submit'])) {

   $foods = $_POST['foods'];

   foreach ($foods as $food){
       echo "You like {$food} <br>";
   }
}

?>



<form action="index.php" method="post">
    <input type="checkbox" name="foods[]" value="pizza"> pizza <br>
    <input type="checkbox" name="foods[]" value="hamburger">Hamburger <br>
    <input type="checkbox" name="foods[]" value="hotdog"> hotdog <br>
    <input type="checkbox" name="foods[]" value="taco"> taco <br>

    <input type="submit" value="Submit" name="submit">
</form>
sudo apt-get clean all
sudo rm -rf /var/lib/apt/lists/*
sudo apt-get update --fix-missing
sudo apt-get upgrade

instalar dependencias faltantes 
sudo apt -f install
 $taxonomy = 'product_cat'; 
   $primary_cat_id=get_post_meta($product->id,'_yoast_wpseo_primary_' . $taxonomy, true);
    if($primary_cat_id){
       $primary_cat = get_term($primary_cat_id, $taxonomy);
       if(isset($primary_cat->name)) 
           echo $primary_cat->name;
    }
/wp-admin/admin-ajax.php?action=function_name
<?php
// Enter your code here, enjoy!
// function calculateDistance($lat1, $lon1, $lat2, $lon2) {
//     // approximate radius of Earth in km
//     $R = 6371.0;

//     // convert degrees to radians
//     $lat1 = deg2rad($lat1);
//     $lon1 = deg2rad($lon1);
//     $lat2 = deg2rad($lat2);
//     $lon2 = deg2rad($lon2);

//     // calculate the differences in latitude and longitude
//     $dlat = $lat2 - $lat1;
//     $dlon = $lon2 - $lon1;

//     // apply the Haversine formula
//     $a = sin($dlat / 2) ** 2 + cos($lat1) * cos($lat2) * sin($dlon / 2) ** 2;
//     $c = 2 * atan2(sqrt($a), sqrt(1 - $a));

//     // calculate the distance
//     $distance = $R * $c;

//     return $distance;
// }

// // Array of coordinates
// $coordinates = array(
//     array(-14.537804, 40.672439, "NA1"),  // NA1
//     array(-14.532698, 40.674953, "NA2"),  // NA2
//     array(-14.529319, 40.675874, "NA3"),  // NA3
//     array(-14.523059, 40.675931, "NA4"),  // NA4
//     array(-14.459071, 40.674796, "NB5"),  // NB5
//     array(-14.460408, 40.678548, "NB6"),  // NB6
//     array(-14.461540, 40.680757, "NB7")   // NB7
// );

// // Calculate distances between points
// $pointCount = count($coordinates);
// for ($i = 0; $i < $pointCount - 1; $i++) {
//     $coord1 = $coordinates[$i];
//     $coord2 = $coordinates[$i + 1];
    
//     $j = $i + 1;

//     $lat1 = $coord1[0];
//     $lon1 = $coord1[1];
//     $lat2 = $coord2[0];
//     $lon2 = $coord2[1];

//     $distance = calculateDistance($lat1, $lon1, $lat2, $lon2);
//     echo "Distance between point {$coord1[2]} and point {$coord2[2]}: {$distance} km\n";
// }


function calculateDistance($lat1, $lon1, $lat2, $lon2) {
    // approximate radius of Earth in km
    $R = 6371.0;

    // convert degrees to radians
    $lat1 = deg2rad($lat1);
    $lon1 = deg2rad($lon1);
    $lat2 = deg2rad($lat2);
    $lon2 = deg2rad($lon2);

    // calculate the differences in latitude and longitude
    $dlat = $lat2 - $lat1;
    $dlon = $lon2 - $lon1;

    // apply the Haversine formula
    $a = sin($dlat / 2) ** 2 + cos($lat1) * cos($lat2) * sin($dlon / 2) ** 2;
    $c = 2 * atan2(sqrt($a), sqrt(1 - $a));

    // calculate the distance
    $distance = $R * $c;

    return $distance;
}

// Array of coordinates
$coordinates = array(
    array(-14.537804, 40.672439, 'NA1'),
    array(-14.532698, 40.674953, 'NA2'),
    array(-14.529319, 40.675874, 'NA3'),
    array(-14.523059, 40.675931, 'NA4'),
    array(-14.459071, 40.674796, 'NB5'),
    array(-14.460408, 40.678548, 'NB6'),
    array(-14.461540, 40.680757, 'NB7')
);

// Calculate distances between each point
$pointCount = count($coordinates);
for ($i = 0; $i < $pointCount - 1; $i++) {
    $coord1 = $coordinates[$i];
    $lat1 = $coord1[0];
    $lon1 = $coord1[1];

    for ($j = $i + 1; $j < $pointCount; $j++) {
        $coord2 = $coordinates[$j];
        $lat2 = $coord2[0];
        $lon2 = $coord2[1];

        $distance = calculateDistance($lat1, $lon1, $lat2, $lon2);
        echo "Distance between point {$coord1[2]} and point {$coord2[2]}: {$distance} km\n";
    }
}

$digits = 3;
echo rand(pow(10, $digits-1), pow(10, $digits)-1);
 if (!defined('ABSPATH')) exit;

    new My_Cron();

    class My_Cron {

        public function __construct() {
            add_filter('cron_schedules', array($this, 'cron_time_intervals'));
            add_action( 'wp',  array($this, 'cron_scheduler'));
            add_action( 'cast_my_spell', array( $this, 'auto_spell_cast' ) );
        }

        public function cron_time_intervals($schedules)
        {
            $schedules['minutes_10'] = array(
                'interval' => 10 * 60,
                'display' => 'Once 10 minutes'
            );
            return $schedules;
        }

        function cron_scheduler() {
            if ( ! wp_next_scheduled( 'cast_my_spell' ) ) {
                wp_schedule_event( time(), 'minutes_10', 'cast_my_spell');
            }
        }

        function auto_spell_cast(){
            My_Plugin_Class::instance()->launch_spell();
        }
    }
cntrl + shift + t: abrir una ventana del navegador que ya habias cerrado con anterioridad
windows + l: bloquea el ordenador y guarda todo el trabajo
;MainWP Requriement - cURL timeout
default_socket_timeout = 300
;END MainWP Requriement
  // Only from inside the same class
  $this->processSomething([__CLASS__, 'myStaticCallback']);
  // From either inside or outside the same class
  $myObject->processSomething(['\Namespace\MyClass', 'myStaticCallback']);
  $myObject->processSomething(['\Namespace\MyClass::myStaticCallback']); // PHP 5.2.3+
  $myObject->processSomething([MyClass::class, 'myStaticCallback']); // PHP 5.5.0+
get_intermediate_image_sizes(); // get all the image size names.
wp_get_additional_image_sizes(); // get all the additional image size data.
wp_get_registered_image_subsizes(); // get all the image size data.
$post_id = wp_insert_post(array (
   'post_type' => 'your_post_type',
   'post_title' => $your_title,
   'post_content' => $your_content,
   'post_status' => 'publish',
   'comment_status' => 'closed',
   'ping_status' => 'closed',
   'meta_input' => array(
      '_your_custom_1' => $custom_1,
      '_your_custom_2' => $custom_2,
      '_your_custom_3' => $custom_3,
    ),
));
$post_id = wp_insert_post(array (
   'post_type' => 'your_post_type',
   'post_title' => $your_title,
   'post_content' => $your_content,
   'post_status' => 'publish',
   'comment_status' => 'closed',
   'ping_status' => 'closed',
   'meta_input' => array(
      '_your_custom_1' => $custom_1,
      '_your_custom_2' => $custom_2,
      '_your_custom_3' => $custom_3,
    ),
));
$files = scandir('/some/random/folder') ?: [];
$user = $_POST['user'] ?? $_SESSION['user'] ?? $_COOKIE['user'] ?? '';
<?php
    var_dump(5 ?: 0); // 5
    var_dump(false ?: 0); // 0
    var_dump(null ?: 'foo'); // 'foo'
    var_dump(true ?: 123); // true
    var_dump('rock' ?: 'roll'); // 'rock'
?>
   function save_function()
{

    $subject_term = 'subject';
    $my_subject_term = term_exists($subject_term, 'my_custom_taxonomy');   // check if term in website or no
    // Create Term if it doesn't exist
    if (!$my_subject_term) {
        $my_subject_term = wp_insert_term($subject_term, 'my_custom_taxonomy');
    }
    $custom_tax = array(
        'my_custom_taxonomy' => array(
            $my_subject_term['term_taxonomy_id'],
        )
    );

    // MESSAGE FIELDS
    $public_post = array(
        'post_title' => filter_input(INPUT_POST, 'title'),
        'post_author' => 1,
        'post_type' => 'message',
        'post_status' => 'pending',
        'tax_input' => $custom_tax
    );

    $post_id = wp_insert_post($public_post);

    
}
Supongamos que estamos desarrollando una aplicación de gestión de proyectos. Cada proyecto tiene un solo gerente, pero un gerente puede estar a cargo de varios proyectos. Además, cada proyecto puede tener varios miembros del equipo, y cada miembro del equipo puede estar asignado a varios proyectos.

1.-modelo(app/models/Proyecto.php)

<?php

namespace app\models;

use yii\db\ActiveRecord;

class Proyecto extends ActiveRecord
{
    public static function tableName()
    {
        return 'proyectos';
    }

    public function getGerente()
    {
        return $this->hasOne(Gerente::className(), ['id' => 'id_gerente']);
    }

    public function getMiembrosEquipo()
    {
        return $this->hasMany(MiembroEquipo::className(), ['id_proyecto' => 'id']);
    }
}

En este ejemplo, estamos creando un modelo llamado Proyecto que extiende de la clase ActiveRecord de Yii2. Este modelo representa la tabla proyectos de la base de datos PostgreSQL y tiene una relación de uno a uno con la tabla gerentes y una relación de uno a muchos con la tabla miembros_equipo.

2.-Modelo(app/models/Gerente.php)

<?php

namespace app\models;

use yii\db\ActiveRecord;

class Gerente extends ActiveRecord
{
    public static function tableName()
    {
        return 'gerentes';
    }

    public function getProyectos()
    {
        return $this->hasMany(Proyecto::className(), ['id_gerente' => 'id']);
    }
}

En este ejemplo, estamos creando un modelo llamado Gerente que extiende de la clase ActiveRecord de Yii2. Este modelo representa la tabla gerentes de la base de datos PostgreSQL y tiene una relación de uno a muchos con la tabla proyectos.


3.-Modelo(app/models/MiembroEquipo.php)

<?php

namespace app\models;

use yii\db\ActiveRecord;

class MiembroEquipo extends ActiveRecord
{
    public static function tableName()
    {
        return 'miembros_equipo';
    }

    public function getProyecto()
    {
        return $this->hasOne(Proyecto::className(), ['id' => 'id_proyecto']);
    }

    public function getEmpleado()
    {
        return $this->hasOne(Empleado::className(), ['id' => 'id_empleado']);
    }
}

En este ejemplo, estamos creando un modelo llamado MiembroEquipo que extiende de la clase ActiveRecord de Yii2. Este modelo representa la tabla miembros_equipo de la base de datos PostgreSQL y tiene una relación de uno a uno con la tabla proyectos y una relación de uno a uno con la tabla empleados.


4.-Modelo(app/models/Empleado.php)

<?php

namespace app\models;

use yii\db\ActiveRecord;

class Empleado extends ActiveRecord
{
    public static function tableName()
    {
        return 'empleados';
    }

    public function getMiembrosEquipo()
    {
        return $this->hasMany(MiembroEquipo::className(), ['id_empleado' => 'id']);
    }
}

En este ejemplo, estamos creando un modelo llamado Empleado que extiende de la clase ActiveRecord de Yii2. Este modelo representa la tabla empleados de la base de datos PostgreSQL y tiene una relación de uno a muchos con la tabla miembros_equipo.

5.-Controlador(app/controllers/ProyectoController.php)

<?php

namespace app\controllers;

use yii\web\Controller;
use app\models\Proyecto;

class ProyectoController extends Controller
{
    public function actionIndex()
    {
        $proyectos = Proyecto::find()->with('gerente', 'miembrosEquipo.empleado')->all();
        return $this->render('index', ['proyectos' => $proyectos]);
 }
}

En este ejemplo, estamos creando un controlador llamado ProyectoController que tiene un método llamado actionIndex que se encarga de obtener todos los proyectos de la base de datos y sus relaciones con gerentes y miembros del equipo utilizando los modelos Proyecto, Gerente, MiembroEquipo y Empleado. Luego, se renderiza la vista index y se le pasa como parámetro los proyectos obtenidos.

6.-Vista(app/views/proyecto/index.php)

<table>
    <thead>
        <tr>
            <th>ID</th>
            <th>Nombre</th>
            <th>Gerente</th>
            <th>Miembros del equipo</th>
        </tr>
    </thead>
    <tbody>
        <?php foreach ($proyectos as $proyecto): ?>
            <tr>
                <td><?= $proyecto->id ?></td>
                <td><?= $proyecto->nombre ?></td>
                <td><?= $proyecto->gerente->nombre ?></td>
                <td>
                    <ul>
                        <?php foreach ($proyecto->miembrosEquipo as $miembroEquipo): ?>
                            <li><?= $miembroEquipo->empleado->nombre ?></li>
                        <?php endforeach ?>
                    </ul>
                </td>
            </tr>
        <?php endforeach ?>
    </tbody>
</table>

<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script>
    $(document).ready(function() {
        // Código de jQuery aquí
    });
</script>

En este ejemplo, estamos creando una vista llamada index que muestra una tabla con los proyectos, sus gerentes y sus miembros del equipo. También estamos incluyendo la librería de jQuery y un bloque de código jQuery vacío que se ejecutará cuando el DOM esté listo.

7.-Codigo Jquery (app/web/js/mi-script.js)

En este ejemplo, estamos utilizando jQuery para hacer una petición AJAX al servidor cuando el usuario hace clic en una fila de la tabla de proyectos. La petición se realiza al controlador ProyectoController y al método actionGet, que se encarga de obtener los detalles del proyecto con el ID especificado y devolverlos en formato JSON.
Recuerda que debes ajustar los nombres de los archivos y las rutas según la estructura de tu aplicación Yii2 y PostgreSQL.
Espero que esto te ayude a entender cómo podrías implementar relaciones de 1 a 1, 0 a 1 y muchos a muchos utilizando Yii2, PostgreSQL, MVC, OOP y jQuery.

8.- código SQL para crear las tablas utilizadas en el ejemplo de la aplicación web que utiliza Yii2, PostgreSQL, MVC, OOP y jQuery para implementar relaciones de 1 a 1, 0 a 1 y muchos a muchos:

Tabla proyectos ()
CREATE TABLE proyectos (
    id SERIAL PRIMARY KEY,
    nombre VARCHAR(255) NOT NULL,
    id_gerente INTEGER REFERENCES gerentes(id)
);

En esta tabla, estamos creando un campo id que es una clave primaria autoincremental, un campo nombre que almacena el nombre del proyecto y un campo id_gerente que es una clave foránea que hace referencia al campo id de la tabla gerentes.

9.-tabla gerentes

CREATE TABLE gerentes (
    id SERIAL PRIMARY KEY,
    nombre VARCHAR(255) NOT NULL
);

En esta tabla, estamos creando un campo id que es una clave primaria autoincremental y un campo nombre que almacena el nombre del gerente.

10.- tabla miembros_equipo

CREATE TABLE miembros_equipo (
    id_proyecto INTEGER REFERENCES proyectos(id),
    id_empleado INTEGER REFERENCES empleados(id),
    PRIMARY KEY (id_proyecto, id_empleado)
);

En esta tabla, estamos creando dos campos id_proyecto e id_empleado que son claves foráneas que hacen referencia a los campos id de las tablas proyectos y empleados, respectivamente. Además, estamos creando una clave primaria compuesta por ambos campos para asegurarnos de que no haya duplicados.

11.-tabla empleados

CREATE TABLE empleados (
    id SERIAL PRIMARY KEY,
    nombre VARCHAR(255) NOT NULL
);

En esta tabla, estamos creando un campo id que es una clave primaria autoincremental y un campo nombre que almacena el nombre del empleado.

Recuerda que debes ajustar los nombres de las tablas y los campos según la estructura de tu aplicación. Además, debes asegurarte de que las claves foráneas estén correctamente definidas y que las relaciones entre las tablas sean coherentes.

posibles consultas que podrías hacer utilizando el código SQL de la aplicación web que utiliza Yii2, PostgreSQL, MVC, OOP y jQuery para implementar relaciones de 1 a1, 0 a 1 y muchos a muchos:

1.-Obtener todos los proyectos con sus gerentes y miembros del equipo:

SELECT p.nombre AS proyecto, g.nombre AS gerente, e.nombre AS empleado
FROM proyectos p
LEFT JOIN gerentes g ON p.id_gerente = g.id
LEFT JOIN miembros_equipo me ON p.id = me.id_proyecto
LEFT JOIN empleados e ON me.id_empleado = e.id;

En esta consulta, estamos obteniendo todos los proyectos con sus gerentes y miembros del equipo utilizando las tablas proyectos, gerentes, miembros_equipo y empleados. Estamos utilizando un LEFT JOIN para asegurarnos de que se incluyan todos los proyectos, incluso aquellos que no tienen gerente o miembros del equipo.


2.-Obtener todos los proyectos que tienen un gerente asignado:

SELECT p.nombre AS proyecto, g.nombre AS gerente
FROM proyectos p
INNER JOIN gerentes g ON p.id_gerente = g.id;

En esta consulta, estamos obteniendo todos los proyectos que tienen un gerente asignado utilizando las tablas proyectos y gerentes. Estamos utilizando un INNER JOIN para asegurarnos de que solo se incluyan los proyectos que tienen un gerente asignado.

3.-Obtener todos los proyectos en los que trabaja un empleado específico:

SELECT p.nombre AS proyecto, e.nombre AS empleado
FROM proyectos p
INNER JOIN miembros_equipo me ON p.id = me.id_proyecto
INNER JOIN empleados e ON me.id_empleado = e.id
WHERE e.nombre = 'Juan';

En esta consulta, estamos obteniendo todos los proyectos en los que trabaja un empleado específico utilizando las tablas proyectos, miembros_equipo y empleados. Estamos utilizando un INNER JOIN para asegurarnos de que solo se incluyan los proyectos en los que trabaja el empleado específico y estamos utilizando una cláusula WHERE para filtrar por el nombre del empleado.

4.-Obtener todos los empleados que trabajan en un proyecto específico:

SELECT e.nombre AS empleado
FROM empleados e
INNER JOIN miembros_equipo me ON e.id = me.id_empleado
INNER JOIN proyectos p ON me.id_proyecto = p.id
WHERE p.nombre = 'Proyecto A';

En esta consulta, estamos obteniendo todos los empleados que trabajan en un proyecto específico utilizando las tablas empleados, miembros_equipo y proyectos. Estamos utilizando un INNER JOIN para asegurarnos de que solo se incluyan los empleados que trabajan en el proyecto específico y estamos utilizando una cláusula WHERE para filtrar por el nombre del proyecto.
Recuerda que debes ajustar las consultas según la estructura de tu aplicación y las relaciones entre las tablas.

{
   error: {
     message: "Unauthorized"
   }
}


If you removed Auth middleware but still getting unauthorized means there may be route cache. Try using php artisan route:clear and check.


<?php

function isSubstring($string, $substring) 
{
    return strpos($string, $substring) !== false;
}

// Usage example:
$mainString = "Hello, World!";
$substring = "World";
if (isSubstring($mainString, $substring)) {
    echo "The substring '$substring' is found in the main string.";
} else {
    echo "The substring '$substring' is not found in the main string.";
}
function custom_add_attribute_thumbnail_field( $term ) {
    $thumbnail_id = get_term_meta( $term->term_id, '_thumbnail_id', true );
    $image_url = wp_get_attachment_image_url( $thumbnail_id, 'thumbnail' ); // Imposta la dimensione dell'immagine desiderata (esempio: 'thumbnail', 'medium', 'large')
    ?>
    <tr class="form-field">
        <th scope="row" valign="top"><label for="attribute_thumbnail"><?php esc_html_e( 'Attribute Thumbnail', 'text-domain' ); ?></label></th>
        <td>
            <div id="attribute_thumbnail_preview">
                <?php if ( $image_url ) : ?>
                    <img src="<?php echo esc_url( $image_url ); ?>" alt="<?php echo esc_attr( $term->name ); ?>" style="max-width:100px; max-height:100px;">
                <?php endif; ?>
            </div>
            <input type="hidden" id="attribute_thumbnail" name="attribute_thumbnail" value="<?php echo esc_attr( $thumbnail_id ); ?>">
            <button type="button" id="upload_attribute_thumbnail_button" class="button"><?php esc_html_e( 'Upload/Add image', 'text-domain' ); ?></button>
            <button type="button" id="remove_attribute_thumbnail_button" class="button"><?php esc_html_e( 'Remove image', 'text-domain' ); ?></button>
            <script>
                jQuery(document).ready(function($) {
                    // Carica l'immagine
                    $('#upload_attribute_thumbnail_button').click(function() {
                        var custom_uploader = wp.media({
                            title: '<?php esc_html_e( "Choose or Upload Image", "text-domain" ); ?>',
                            button: {
                                text: '<?php esc_html_e( "Use Image", "text-domain" ); ?>'
                            },
                            multiple: false
                        }).on('select', function() {
                            var attachment = custom_uploader.state().get('selection').first().toJSON();
                            $('#attribute_thumbnail').val(attachment.id);
                            $('#attribute_thumbnail_preview').html('<img src="' + attachment.url + '" alt="<?php echo esc_attr( $term->name ); ?>" style="max-width:100px; max-height:100px;">');
                        }).open();
                    });

                    // Rimuovi l'immagine
                    $('#remove_attribute_thumbnail_button').click(function() {
                        $('#attribute_thumbnail').val('');
                        $('#attribute_thumbnail_preview').html('');
                    });
                });
            </script>
            <p class="description"><?php esc_html_e( 'Upload or select an image to set as the attribute thumbnail.', 'text-domain' ); ?></p>
        </td>
    </tr>
    <?php
}
add_action( 'pa_attributo_add_form_fields', 'custom_add_attribute_thumbnail_field', 10, 2 );
add_action( 'pa_attributo_edit_form_fields', 'custom_add_attribute_thumbnail_field', 10, 2 );

function custom_save_attribute_thumbnail( $term_id ) {
    if ( isset( $_POST['attribute_thumbnail'] ) ) {
        $thumbnail_id = absint( $_POST['attribute_thumbnail'] );
        update_term_meta( $term_id, '_thumbnail_id', $thumbnail_id );
    }
}
add_action( 'edited_pa_attributo', 'custom_save_attribute_thumbnail', 10, 2 );
  <?php
  $taxonomy     = 'product_cat';
  $orderby      = 'menu_order';  
  $show_count   = 0;      // 1 for yes, 0 for no
  $pad_counts   = 0;      // 1 for yes, 0 for no
  $hierarchical = 1;      // 1 for yes, 0 for no  
  $title        = '';  
  $empty        = 0;

  $args = array(
         'taxonomy'     => $taxonomy,
         'orderby'      => $orderby,
         'show_count'   => $show_count,
         'pad_counts'   => $pad_counts,
         'hierarchical' => $hierarchical,
         'title_li'     => $title,
         'hide_empty'   => $empty
  );
 $all_categories = get_categories( $args );
 foreach ($all_categories as $cat) {
    if($cat->category_parent == 0) {
        $category_id = $cat->term_id;       
        //echo '<br /><a href="'. get_term_link($cat->slug, 'product_cat') .'">'. $cat->name .'</a>';

        $args2 = array(
                'taxonomy'     => $taxonomy,
                'child_of'     => 0,
                'parent'       => $category_id,
                'orderby'      => $orderby,
                'show_count'   => $show_count,
                'pad_counts'   => $pad_counts,
                'hierarchical' => $hierarchical,
                'title_li'     => $title,
                'hide_empty'   => $empty
        );
        $sub_cats = get_categories( $args2 );
        if($sub_cats) {
            foreach($sub_cats as $sub_category) {
                // echo  $sub_category->name ;
                 echo '<br /><a href="'. get_term_link($sub_category->slug, 'product_cat') .'">'. $sub_category->name .'</a>';
                echo '<br /><a href="'. get_term_link($sub_category->slug, 'product_cat') .'">'. $sub_category->name .'</a>';
            }   
        }
    }       
}
?>
//Disable Comments

add_action('admin_init', function () {
    // Redirect any user trying to access comments page
    global $pagenow;

    if ($pagenow === 'edit-comments.php') {
        wp_redirect(admin_url());
        exit;
    }

    // Remove comments metabox from dashboard
    remove_meta_box('dashboard_recent_comments', 'dashboard', 'normal');

    // Disable support for comments and trackbacks in post types
    foreach (get_post_types() as $post_type) {
        if (post_type_supports($post_type, 'comments')) {
            remove_post_type_support($post_type, 'comments');
            remove_post_type_support($post_type, 'trackbacks');
        }
    }
});

// Close comments on the front-end
add_filter('comments_open', '__return_false', 20, 2);
add_filter('pings_open', '__return_false', 20, 2);

// Hide existing comments
add_filter('comments_array', '__return_empty_array', 10, 2);

// Remove comments page in menu
add_action('admin_menu', function () {
    remove_menu_page('edit-comments.php');
});

// Remove comments links from admin bar
add_action('init', function () {
    if (is_admin_bar_showing()) {
        remove_action('admin_bar_menu', 'wp_admin_bar_comments_menu', 60);
    }
});
<a href="#" class="facebook"> </a>
<a href="#" class="instagram"> </a>
<a href="#" class="pinterest"> </a>
<a href="#" class="email"> </a>
<a href="#" class="youtube"> </a>
<a href="#" class="linkedin"> </a>
// Parse the initial value using Carbon
$dateTime = Carbon::parse($dateTimeString);

// Format the date and time as desired
$formattedDateTime = $dateTime->format('d-m-Y h:i:sA');
// Parse the initial value using Carbon
$dateTime = Carbon::parse($dateTimeString);

// Format the date and time as desired
$formattedDateTime = $dateTime->isoFormat('Do MMMM YYYY h:mm:ssa');
<?php
$usernames = ['username1', 'username2', ...]; // An array of the usernames of the users you want to change the role for
$new_role = 'new_role'; // The new role you want to assign to the users

foreach ($usernames as $username) {
    $user = get_user_by('login', $username);
    if (!empty($user)) {
        $user->set_role($new_role);
    }
}
?>
$oOrder = OrderAPI::getByID( $lLabID );
if( $oOrder ) {
	//$sFeld = $oOrder->getValueByMethod( "KURZ" );
	$oOrderRoot = $oOrder->getWorkflowRootOrderV2(  );
	if( $oOrderRoot ) {
}
VariablesClass::alertMsg(
	// Zeigt eine Meldung an
	$objResponse, // XAJAX Antwort, nicht aendern!
	$lModuleID, // ID des aufrufenden Moduls, nicht aendern!
	"Bitte Auftrag speichern!", // Nachricht
	"TITLE", // Titel der Meldung
	ALERT_ERROR, // Typ der  Meldung  (ALERT_DEFAULT, ALERT_OK, ALERT_WARNING, ALERT_ERROR)
	"" // (optional) Beschriftung des Buttons
);
<?php
$user = get_userdatabylogin('YOUR_USERNAME');
grant_super_admin($user->ID);
?>
implode(', ', array_column($array, 'colName'));
$coordinator = [];
$coordinatorFirstPage = Api::schoolTeacher()->index($schoolId, $filter);
$coordinator[] = $coordinatorFirstPage->data();
$lastPage = $coordinatorFirstPage->meta('last_page') ?? 1;

$promCordinators = Http::pool(function (Pool $pool) use ($lastPage, $schoolId, $filter) {
    for ($c = 2; $c <= $lastPage; $c++) {
        $filter['page'] = $c;
        $pool->withToken(Auth::user()->token())
            ->get(Api::schoolTeacher()->index($schoolId, $filter, true), $filter);
    }
});

foreach ($promCordinators as $wraped) {
    $coordinator[] = json_decode($wraped->getBody(), true)['data'] ?? [];
}

$coordinator = collect($coordinator)->flatten(1)->toArray();
dd($coordinator);
\DB::enableQueryLog(); // Enable query log

// Your Eloquent query executed by using get()

dd(\DB::getQueryLog()); // Show results of log
<?php

namespace App\Http\Middleware;

use Illuminate\Auth\Middleware\Authenticate as Middleware;
use Illuminate\Http\Request;

class Authenticate extends Middleware
{
    /**
     * Get the path the user should be redirected to when they are not authenticated.
     */
    protected function redirectTo(Request $request): ?string
    {
        return $request->expectsJson() ? null : route('login');
    }

    protected function unauthenticated($request, array $guards)
    {
        abort(response()->json(
            [
                'status' => 'false',
                'message' => 'Unauthenticated',
            ], 401));
    }
}
$tournament = app('App\Http\Controllers\TournamentController')->read_tournament_details($request, $tournament_id)->getData(true);
        
echo gmdate("H:i:s", $time_in_seconds);
$name = implode('.', [
    md5_file($file->getPathname()),
    $file->getClientOriginalExtension()
]);
MyTable::whereDate( 'created_at', '<=', now()->subDays(30))->delete();

<?php

    // Get absolute path
    $path = getcwd(); // /home/user/public_html/test/test.php.   

    $path = substr($path, 0, strpos($path, "public_html"));

    $root = $path . "public_html/";

    echo $root; // This will output /home/user/public_html/
// Get array of all source files
$files = scandir("source");
// Identify directories
$source = "source/";
$destination = "destination/";
// Cycle through all source files
foreach ($files as $file) {
  if (in_array($file, array(".",".."))) continue;
  // If we copied this successfully, mark it for deletion
  if (copy($source.$file, $destination.$file))
  {
      $delete[] = $source.$file;
  }
}
// Delete all successfully-copied files
foreach ($delete as $file)
{
    unlink($file);
}
// Adds a new sortable "last updated" column to posts and pages backend.
function custom_columns($defaults) {
    $defaults['last_updated'] = __('Last Updated', 'your-textdomain');
    return $defaults;
}
add_filter('manage_posts_columns', 'custom_columns');
add_filter('manage_pages_columns', 'custom_columns');

function custom_columns_content($column_name, $post_id) {
    if ($column_name == 'last_updated') {
        $last_updated = get_the_modified_date();
        echo $last_updated;
    }
}
add_action('manage_posts_custom_column', 'custom_columns_content', 10, 2);
add_action('manage_pages_custom_column', 'custom_columns_content', 10, 2);

function custom_columns_sortable($columns) {
    $columns['last_updated'] = 'last_updated';
    return $columns;
}
add_filter('manage_edit-post_sortable_columns', 'custom_columns_sortable');
add_filter('manage_edit-page_sortable_columns', 'custom_columns_sortable');

function custom_columns_orderby($query) {
    if (!is_admin()) {
        return;
    }

    $orderby = $query->get('orderby');

    if ('last_updated' == $orderby) {
        $query->set('orderby', 'modified');
    }
}
add_action('pre_get_posts', 'custom_columns_orderby');
Go to public folder Just delete/remove the storage link inside public/

Then Run the command


 php artisan storage:link

 
the above command will link storage again
/**
 * @snippet       Variable Product Price Range: "From: min_price"
 * @how-to        Get CustomizeWoo.com FREE
 * @author        Rodolfo Melogli
 * @compatible    WooCommerce 6
 * @donate $9     https://businessbloomer.com/bloomer-armada/
 */
 
add_filter( 'woocommerce_variable_price_html', 'bbloomer_variation_price_format_min', 9999, 2 );
 
function bbloomer_variation_price_format_min( $price, $product ) {
   $prices = $product->get_variation_prices( true );
   $min_price = current( $prices['price'] );
   $max_price = end( $prices['price'] );
   $min_reg_price = current( $prices['regular_price'] );
   $max_reg_price = end( $prices['regular_price'] );
   if ( $min_price !== $max_price || ( $product->is_on_sale() && $min_reg_price === $max_reg_price ) ) {
      $price = 'From: ' . wc_price( $min_price ) . $product->get_price_suffix();
   }
   return $price;
}
     $table->id();
            $table->string('model');
            $table->unsignedBigInteger('manufacturer_id');
            $table->foreign('manufacturer_id')->references('id')->on('manufacturers');
            $table->timestamps();
add_action( 'elementor/theme/register_conditions', function( $conditions_manager ) {
class Subcategory_Archive extends \ElementorPro\Modules\ThemeBuilder\Conditions\Taxonomy {
	private $taxonomy;

	public function get_name() {
		return 'child_of_' . $this->taxonomy->name;
	}

	public function get_label() {
		return sprintf( __( 'Direct Child %s Of', 'elementor-pro' ), $this->taxonomy->labels->singular_name );
	}

	public function __construct( $data ) {
		parent::__construct( $data );

		$this->taxonomy = $data['object'];
	}

	public function is_term() {
		$taxonomy = $this->taxonomy->name;
		$current = get_queried_object();
		return ( $current && isset( $current->taxonomy ) && $taxonomy === $current->taxonomy );
	}

	public function check( $args ) {
		$id = (int) $args['id'];
		/**
		 * @var \WP_Term $current
		 */
		$current = get_queried_object();
		if ( ! $this->is_term() || 0 === $current->parent ) {
			return false;
		}

		while ( $current->parent > 0 ) {
			if ( $id === $current->parent ) {
				return true;
			}
			$current = get_term_by( 'id', $current->parent, $current->taxonomy );
		}

		return $id === $current->parent;
	}
}
$taxonomy = get_taxonomy('product_cat');
$conditions_manager->get_condition( 'product_archive' )->register_sub_condition( new Subcategory_Archive([ 'object' => $taxonomy ]) );
}, 100);
$mysqli = mysqli_connect('localhost', 'DATABASE_USERNAME', 'DATABASE_PASSWORD', 'DATABASE_NAME');
<!DOCTYPE html>
<html>
​
<body>
The content of the body element is displayed in your browser.
</body>
​
</html>
​
exec("java -jar WaveAppender.jar " . implode (' ', $theFiles));
//encrypt user password

//    hash produces a fixed length string
    $hashFormat = "$2y$10$";

//    Random characters
    $salt = "HZTym3F5Ade6tvnVf5rXve";

//    combine the hash and salt
    $hashFormat_salt = $hashFormat . $salt;
    
//    password encrypted
    $password = crypt($password,$hashFormat_salt);
function deleteRow(){
    global $connection;
    $id = $_POST['id'];

    $query = "DELETE FROM users ";
    $query .= "WHERE id = $id ";

    $result = mysqli_query($connection, $query);

    if (!$result) {
        die("Query Failed" . mysqli_error($connection));
    }
}
function updateTable() {
    global $connection;

    $username = $_POST['username'];
    $password = $_POST['password'];
    $id = $_POST['id'];

    $query = "UPDATE users SET ";
    $query .= "username = '$username', ";
    $query .= "password = '$password' ";
    $query .= "WHERE id = $id ";

    $result = mysqli_query($connection, $query);

    if (!$result) {
        die("Query Failed" . mysqli_error($connection));
    }

}

// HTML FILE
<?php
if(isset($_POST['submit'])){
    updateTable();
}

?>
  
  <form action="update.php" method="post">
    <select name="id" id="">

        <?php
        showAllData();

        ?>

    </select>

    <input type="text" name="username">
    <input type="password" name="password">
    <button type="submit" name="submit">Update</button>
</form>
function readAll(){
  // Connect to db
    global $connection;
  // make result global so you can use it in the other file
    global $result;

    $query = "SELECT * FROM USERS";

    $result = mysqli_query($connection, $query);
}


// HTML FILE
<?php
readAll();
while ($row = mysqli_fetch_assoc($result)){
?>

<pre>
    <?php
    print_r($row);
    }
    ?>
</pre>
function create(){
	//If linking to database from external file
    global $connection;

	//Grab form data
    $username = $_POST['username'];
    $password = $_POST['password'];
	
    //Sanatize user input
    $username = mysqli_real_escape_string($connection,$username);
    $password = mysqli_real_escape_string($connection,$password);

	//Query that inserts value into database
    $query = "INSERT INTO users(username,password) ";
    $query .= "VALUES ('$username', '$password')";

    $result = mysqli_query($connection,$query);

    if(!$result){
        die('Query failed' . mysqli_error());
    }
}


//HTML FILE
if (isset($_POST['submit'])) {
    create();

}
<?php

$username = $_POST['username'];
$password = $_POST['password'];

$username = mysqli_real_escape_string($connection,$username);
$password = mysqli_real_escape_string($connection,$password);
<?php
//If file is in the same directory
include "db.php";

//If file is in another directory
include"../includes/navbar.php";
<?php
//hostname,username,password,database
$connection = mysqli_connect('localhost', 'root', '', 'loginapp');

if(!$connection){
die('connection failed')
}
$areasexperiencia = $areasexperiencia;
function unique_key($array,$keyname){
$new_array = array();
foreach($array as $key=>$value){

if(!isset($new_array[$value[$keyname]])){
$new_array[$value[$keyname]] = $value;
}

}
$new_array = array_values($new_array);
return $new_array;
}
$unique_arr = unique_key($areasexperiencia,'nombre');
function download(pdfUrl, fileName) {
        fetch(pdfUrl).then(resp => resp.arrayBuffer()).then(resp => {
            const file = new Blob([resp], {type: 'application/pdf'});
            const fileURL = URL.createObjectURL(file);
            jQuery("#download-button-prev").attr('href', fileURL).attr('download', fileName);
        });
    }

    download(linkUrl, docName);
<?php

// Load assets on the "about" page (https://yoursite.com/about/)
// Add the following to your (child) theme's functions.php

add_filter( 'facetwp_load_assets', function( $bool ) {
    if ( 'about' == FWP()->helper->get_uri() ) {
        $bool = true;
    }
    return $bool;
});
add_filter( 'woocommerce_price_trim_zeros', '__return_true' );
FROM php:8.1-fpm

RUN apt-get update

COPY . /app
RUN ls -l
RUN php -v
CMD php /app/index.php





















function kh_plugin_settings_page() {

    // Check user capabilities

    if ( ! current_user_can( 'manage_options' ) ) {

        return;

    }

    // Add error/update messages

    settings_errors( 'kh_plugin_messages' );

    ?>

    <div class="wrap">

        <h1><?php echo esc_html( get_admin_page_title() ); ?></h1>

        <form action="options.php" method="post">

            <?php

            // Output security fields for the registered setting "kh_plugin_options"

            settings_fields( 'kh_plugin_options' );

            // Output setting sections and their fields

            do_settings_sections( 'kh_plugin' );

            // Output save settings button

            submit_button( __( 'Save Settings', 'kh_plugin' ) );

            ?>

        </form>

    </div>

    <?php

}

function kh_plugin_settings_init() {

    // Register a new setting for the plugin

    register_setting( 'kh_plugin_options', 'kh_plugin_settings' );

    // Add a new section to the settings page

    add_settings_section(

        'kh_plugin_section',

        __( 'KH Plugin Settings', 'kh_plugin' ),

        'kh_plugin_section_callback',

        'kh_plugin'

    );

    // Add a text field to the settings section

    add_settings_field(

        'kh_plugin_text_field',

        __( 'Text Field', 'kh_plugin' ),

        'kh_plugin_text_field_callback',

        'kh_plugin',

        'kh_plugin_section'

    );

    // Add a checkbox field to the settings section

    add_settings_field(

        'kh_plugin_checkbox_field',

        __( 'Checkbox Field', 'kh_plugin' ),

        'kh_plugin_checkbox_field_callback',

        'kh_plugin',

        'kh_plugin_section'

    );

}

add_action( 'admin_init', 'kh_plugin_settings_init' );

// Callback function for the section

function kh_plugin_section_callback() {

    echo '<p>' . __( 'Configure your KH Plugin settings.', 'kh_plugin' ) . '</p>';

}

// Callback function for the text field

function kh_plugin_text_field_callback() {

    $options = get_option( 'kh_plugin_settings' );

    echo '<input type="text" name="kh_plugin_settings[text_field]" value="' . esc_attr( $options['text_field'] ) . '" />';

function my_plugin_shortcode( $atts ) {

    ob_start();

    

    $defaults = array(

        'form_id' => 0,

        'button_text' => 'Add field',

    );

    $args = shortcode_atts( $defaults, $atts );

    

    $form_fields = get_post_meta( $args['form_id'], 'form_fields', true );

    ?>

    <form id="my-form">

        <?php foreach ( $form_fields as $field ) : ?>

            <div class="form-group">

                <label for="<?php echo esc_attr( $field['name'] ); ?>"><?php echo esc_html( $field['label'] ); ?></label>

                <?php if ( $field['type'] === 'text' ) : ?>

                    <input type="text" name="<?php echo esc_attr( $field['name'] ); ?>" value="<?php echo esc_attr( $field['value'] ); ?>">

                <?php elseif ( $field['type'] === 'textarea' ) : ?>

                    <textarea name="<?php echo esc_attr( $field['name'] ); ?>"><?php echo esc_html( $field['value'] ); ?></textarea>

                <?php elseif ( $field['type'] === 'select' ) : ?>

                    <select name="<?php echo esc_attr( $field['name'] ); ?>">

                        <?php foreach ( $field['options'] as $option ) : ?>

                            <option value="<?php echo esc_attr( $option['value'] ); ?>"<?php selected( $option['value'], $field['value'] ); ?>><?php echo esc_html( $option['label'] ); ?></option>

                        <?php endforeach; ?>

                    </select>

                <?php endif; ?>

            </div>

        <?php endforeach; ?>

        <button type="button" id="add-field"><?php echo esc_html( $args['button_text'] ); ?></button>

    </form>

    <?php

    $output = ob_get_clean();

    return $output;

}

add_shortcode( 'my-plugin-form', 'my_plugin_shortcode' );

the_post_thumbnail( '', array( 'loading' => '' ) );
// A JavaScript module for submitting forms via AJAX

// This module depends on jQuery and the jQuery Form Plugin

var FormSubmission = {

  // Class to add to elements with form errors

  formErrorClass: 'form-error',

  // Adds form errors to the DOM

  appendFormErrors: function(data, form) {

    // Loop through the error data object

    for (var key in data) {

      // Create a new span element for the error message

      var error = $(document.createElement('span')).attr('class', FormSubmission.formErrorClass).text(data[key]);

      // Insert the error message before the input field with the corresponding name

      form.find("input[name='" + key + "']").before(error);

    }

  },

  // Hides the closest modal element to the given form

  closeModal: function(form) {

    form.closest('.modal').modal('hide');

  },

  // Handles the response from the form submission

  postFormSubmission: function(form, isModal, data) {

    // Remove any existing form errors

    FormSubmission.removeFormErrors(form);

    // If the form was submitted successfully

    if (data['success'] == true) {

      // Reset the form and close the modal if it's a modal form

      FormSubmission.resetForm(form, isModal);

    } else {

      // Append the form errors to the DOM

      FormSubmission.appendFormErrors(data['errors'], form);

    }

  },

  // Removes form errors from the DOM

  removeFormErrors: function(form) {

    form.find('.' + FormSubmission.formErrorClass).remove();

  },

  // Calls resetForm with isModal set to false

  resetForm: function(form) {

    FormSubmission.resetForm(form, false);

  },

  // Resets the form and closes the modal if it's a modal form

  resetForm: function(form, isModal) {

    // Remove any existing form errors

    FormSubmission.removeFormErrors(form);

    // Reset the form

    form[0].reset();

    // If it's a modal form, close the modal

    if (isModal == true) {

      FormSubmission.closeModal(form);

    }

  },

  // Calls submitForm with isModal set to false

  submitForm: function(form) {

    FormSubmission.submitForm(form, false);

  },

  // Submits the form via AJAX

  submitForm: function(form, isModal) {

    var url = form.attr('action');

    // Make an AJAX request to the form's action URL

    $.ajax({

      method: "POST",

      url: url,

      data: form.serialize(),

      myForm: form,

      isModal: isModal,

      // Handle the response from the server

      success: function(data) {

        FormSubmission.postFormSubmission($(this).myForm, $(this).isModal, data);

      },

      // Handle any errors

      error: function(jqXHR, textStatus, errorThrown) {

        console.log(textStatus, errorThrown);

      }

    });

  },

  // Submits the form via AJAX with support for file uploads

  submitFormWithFiles: function(form, isModal) {

    var url = form.attr('action');

    // Make an AJAX request to the form's action URL with support for file uploads

    form.ajaxSubmit({

      method: 'POST',

      url: url,

      myForm: form,

      isModal: isModal,

      // Handle the response from the server

      success: function(data) {

        FormSubmission.postFormSubmission($(this).myForm, $(this).isModal, data);

      },

      //

auth()->user()->name;
auth()->id();

be sure that you are logged in. and use that


composer create-project --prefer-dist laravel/laravel:8.6.11 blog


composer create-project laravel/laravel:^8.0 example --ignore-platform-reqs
<?php
$ip = $_SERVER['REMOTE_ADDR'];
$user_agent = $_SERVER['HTTP_USER_AGENT'];
$referer = $_SERVER['HTTP_REFERER'];
$language = $_SERVER['HTTP_ACCEPT_LANGUAGE'];

echo "IP address: $ip<br>";
echo "User agent: $user_agent<br>";
echo "Referrer: $referer<br>";
echo "Preferred language(s): $language<br>";
?>
public function stkpush(Request $request)
{
    $url='https://sandbox.safaricom.co.ke/mpesa/stkpush/v1/processrequest';

    $curl_post_data=[
        'BusinessShortCode'=>174379,
        'Password'=>$this->lipanampesapassword(),
        'Timestamp'=>Carbon::rawParse('now')->format('YmdHms'),

        'TransactionType'=> "CustomerPayBillOnline",
        'Amount'=>1,
        'PartyA'=>254712345678,
        'PartyB'=>174379,
        'PhoneNumber'=>254712345678,
        'CallBackURL'=>'https://89af-196-202-210-53.eu.ngrok.io/api/mpesa/callbackurl',
        'AccountReference'=>'Waweru Enterprises',
        'TransactionDesc'=>'Paying for Products Bought'
    ];

    $data_string=json_encode($curl_post_data);

    $curl=curl_init();
    curl_setopt($curl,CURLOPT_URL,$url);
    curl_setopt($curl,CURLOPT_HTTPHEADER,array('Content-Type:application/json','Authorization:Bearer '.$this->newaccesstoken()));
    curl_setopt($curl,CURLOPT_RETURNTRANSFER,true);
    curl_setopt($curl,CURLOPT_POST,true);
    curl_setopt($curl,CURLOPT_POSTFIELDS,$data_string);

    $curl_response=curl_exec($curl);
    return $curl_response;
}
<?php

namespace App\Http\Controllers\User;

use App\Http\Controllers\Controller;
use App\Models\User;
use Carbon\Carbon;
use Illuminate\Http\Request;

class MempelaiController extends Controller
{
    public function getDataMempelaiPria(Request $request)
    {
        $dataMempelaiPria = $request->user()->mempelai_pria;
        return response()->json([
            'message' => 'success',
            'data' => $dataMempelaiPria
        ]);
    }

    public function getDataMempelaiWanita(Request $request)
    {
        $dataMempelaiWanita = $request->user()->mempelaiWanitaApi;
        return response()->json([
            'message' => 'success',
            'data' => $dataMempelaiWanita
        ]);
    }

    public function storeDataMempelai(Request $request)
    {
        $user = User::find($request->user()->id);
        $dataMempelaiPria = $request->dataMempelaiPria;
        $dataMempelaiWanita = $request->dataMempelaiWanita;
        $dataNull = $request->dataNull;

        if ($dataNull['dataMempelaiPria'] === 'true') {
            $user->MempelaiPriaApi()->create([
                'user_id' => $user->id,
                'nama_lengkap' => ucfirst($dataMempelaiPria['nama_lengkap']),
                'nama_panggilan' => ucfirst($dataMempelaiPria['nama_panggilan']),
                'tempat_lahir' => $dataMempelaiPria['tempat_lahir'],
                'tanggal_lahir' => $dataMempelaiPria['tanggal_lahir'],
                'nama_ayah' => $dataMempelaiPria['nama_ayah'],
                'nama_ibu' => $dataMempelaiPria['nama_ibu'],
                'foto' => 'default',
                'tampilkan_foto' => 'false',
                'instagram' =>  'null',
                'facebook' => 'null',
                'twitter' => 'null',
            ]);
        } else {
            $user->MempelaiPriaApi()->update([
                'user_id' => $user->id,
                'nama_lengkap' => ucfirst($dataMempelaiPria['nama_lengkap']),
                'nama_panggilan' => ucfirst($dataMempelaiPria['nama_panggilan']),
                'tempat_lahir' => $dataMempelaiPria['tempat_lahir'],
                'tanggal_lahir' => $dataMempelaiPria['tanggal_lahir'],
                'nama_ayah' => $dataMempelaiPria['nama_ayah'],
                'nama_ibu' => $dataMempelaiPria['nama_ibu'],
                'foto' => 'default',
                'tampilkan_foto' => 'false',
                'instagram' =>  'null',
                'facebook' => 'null',
                'twitter' => 'null',
            ]);
        }

        if ($dataNull['dataMempelaiWanita'] === 'true') {
            $user->mempelaiWanitaApi()->create([
                'user_id' => $user->id,
                'nama_lengkap' => ucfirst($dataMempelaiWanita['nama_lengkap']),
                'nama_panggilan' => ucfirst($dataMempelaiWanita['nama_panggilan']),
                'tempat_lahir' => $dataMempelaiWanita['tempat_lahir'],
                'tanggal_lahir' => $dataMempelaiWanita['tanggal_lahir'],
                'nama_ayah' => $dataMempelaiWanita['nama_ayah'],
                'nama_ibu' => $dataMempelaiWanita['nama_ibu'],
                'foto' => 'default',
                'tampilkan_foto' => 'false',
                'instagram' =>  'null',
                'facebook' => 'null',
                'twitter' => 'null',
            ]);
        } else {
            $user->mempelaiWanitaApi()->update([
                'user_id' => $user->id,
                'nama_lengkap' => ucfirst($dataMempelaiWanita['nama_lengkap']),
                'nama_panggilan' => ucfirst($dataMempelaiWanita['nama_panggilan']),
                'tempat_lahir' => $dataMempelaiWanita['tempat_lahir'],
                'tanggal_lahir' => $dataMempelaiWanita['tanggal_lahir'],
                'nama_ayah' => $dataMempelaiWanita['nama_ayah'],
                'nama_ibu' => $dataMempelaiWanita['nama_ibu'],
                'foto' => 'default',
                'tampilkan_foto' => 'false',
                'instagram' =>  'null',
                'facebook' => 'null',
                'twitter' => 'null',
            ]);
        }

        return response()->json([
            'message' => 'success',
            'data' => $user
        ]);
    }

    public function storeMempelaiPria(Request $request)
    {
        $user = User::find($request->user()->id);
        $dataMempelaiPria = $request->dataMempelaiPria;

        $user->MempelaiPriaApi()->create([
            'user_id' => $user->id,
            'nama_lengkap' => ucfirst($dataMempelaiPria['nama_lengkap']),
            'nama_panggilan' => ucfirst($dataMempelaiPria['nama_panggilan']),
            'tempat_lahir' => $dataMempelaiPria['tempat_lahir'],
            'tanggal_lahir' => Carbon::parse(strtr($dataMempelaiPria['tanggal_lahir'], '/', '-'))->format('Y-m-d'),
            'nama_ayah' => $dataMempelaiPria['nama_ayah'],
            'nama_ibu' => $dataMempelaiPria['nama_ibu'],
            'foto' => 'default',
            'tampilkan_foto' => 'false',
            'instagram' =>  'null',
            'facebook' => 'null',
            'twitter' => 'null',
        ]);


        return response()->json([
            'message' => 'success',
            'data' => $user
        ]);
    }

    public function updateMempelaiPria(Request $request)
    {
        $user = User::find($request->user()->id);
        $dataMempelaiPria = $request->dataMempelaiPria;

        $user->MempelaiPriaApi()->update([
            'user_id' => $user->id,
            'nama_lengkap' => ucfirst($dataMempelaiPria['nama_lengkap']),
            'nama_panggilan' => ucfirst($dataMempelaiPria['nama_panggilan']),
            'tempat_lahir' => $dataMempelaiPria['tempat_lahir'],
            'tanggal_lahir' => Carbon::parse(strtr($dataMempelaiPria['tanggal_lahir'], '/', '-'))->format('Y-m-d'),
            'nama_ayah' => $dataMempelaiPria['nama_ayah'],
            'nama_ibu' => $dataMempelaiPria['nama_ibu'],
            'foto' => 'default',
            'tampilkan_foto' => 'false',
            'instagram' =>  'null',
            'facebook' => 'null',
            'twitter' => 'null',
        ]);

        return response()->json([
            'message' => 'success',
            'data' => $user
        ]);
    }

    public function storeMempelaiWanita(Request $request)
    {
        $user = User::find($request->user()->id);
        $dataMempelaiWanita = $request->dataMempelaiWanita;

        $user->mempelaiWanitaApi()->create([
            'user_id' => $user->id,
            'nama_lengkap' => ucfirst($dataMempelaiWanita['nama_lengkap']),
            'nama_panggilan' => ucfirst($dataMempelaiWanita['nama_panggilan']),
            'tempat_lahir' => $dataMempelaiWanita['tempat_lahir'],
            'tanggal_lahir' => Carbon::parse(strtr($dataMempelaiWanita['tanggal_lahir'], '/', '-'))->format('Y-m-d'),
            'nama_ayah' => $dataMempelaiWanita['nama_ayah'],
            'nama_ibu' => $dataMempelaiWanita['nama_ibu'],
            'foto' => 'default',
            'tampilkan_foto' => 'false',
            'instagram' =>  'null',
            'facebook' => 'null',
            'twitter' => 'null',
        ]);

        $namaPanggilanMempelaiPria = $user->mempelaiPriaApi->nama_panggilan;

        $user->settingUndanganApi()->create([
            'user_id' => $user->id,
            'domain' => $namaPanggilanMempelaiPria . '-' . $dataMempelaiWanita['nama_panggilan'],
            'judul_undangan' => $namaPanggilanMempelaiPria . ' & ' . $dataMempelaiWanita['nama_panggilan'],
        ]);

        return response()->json([
            'message' => 'success',
            'data' => $user
        ]);
    }

    public function updateMempelaiWanita(Request $request)
    {
        $user = User::find($request->user()->id);
        $dataMempelaiWanita = $request->dataMempelaiWanita;

        $user->mempelaiWanitaApi()->update([
            'user_id' => $user->id,
            'nama_lengkap' => ucfirst($dataMempelaiWanita['nama_lengkap']),
            'nama_panggilan' => ucfirst($dataMempelaiWanita['nama_panggilan']),
            'tempat_lahir' => $dataMempelaiWanita['tempat_lahir'],
            'tanggal_lahir' => Carbon::parse(strtr($dataMempelaiWanita['tanggal_lahir'], '/', '-'))->format('Y-m-d'),
            'nama_ayah' => $dataMempelaiWanita['nama_ayah'],
            'nama_ibu' => $dataMempelaiWanita['nama_ibu'],
            'instagram' => $dataMempelaiWanita['instagram'] ?? 'null',
        ]);

        return response()->json([
            'message' => 'success',
            'data' => $user
        ]);
    }
}
@extends('layouts.master')

@section('title', 'Pendaftaran')

@section('content')
    <x-navigation.navbar />
    <main class="hero min-h-screen bg-base-200">
        <div class="hero-content my-6">
            <section>
                <div class="w-full max-w-xl flex-shrink-0">
                    <ol class="border-l-2 border-blue-600">
                        <li>
                            <div class="flex-start flex items-center">
                                <div class="-ml-2 mr-3 -mt-2 flex h-4 w-4 items-center justify-center rounded-full bg-blue-600">
                                </div>
                                <h4 class="-mt-2 text-xl font-semibold text-gray-800">Daftar Akun</h4>
                            </div>

                            <div class="ml-6" id="pendaftaran">
                                <p class="-ml-1 text-sm text-green-500">Pendaftaran berhasil.</p>
                            </div>
                        </li>

                        <li class="{{ $dataMempelaiPria === null ? 'pb-6' : '' }} pt-6" id="section-mempelai-pria">
                            <div class="flex-start flex cursor-pointer items-center">
                                <div class="-ml-2 mr-3 -mt-2 flex h-4 w-4 items-center justify-center rounded-full bg-blue-600">
                                </div>
                                <h4 class="-mt-2 text-xl font-semibold text-gray-800">Profile Mempelai Pria</h4>
                            </div>
                            <div class="{{ $dataMempelaiPria === null ? '' : 'hidden' }} ml-6" id="form-mempelai-pria">
                                <p class="desc-timeline">Silahkan isi formulir dengan lengkap.</p>
                                @include('user.complete-register.partials.formMempelaiPria')
                            </div>

                            <div class="{{ $dataMempelaiPria === null ? 'hidden' : '' }} ml-6" id="form-mempelai-pria-not-null">
                                <p class="-ml-1 text-sm text-green-500">Informasi profile mempelai pria sudah lengkap.</p>
                            </div>
                        </li>

                        <li class="{{ $dataMempelaiPria === null ? 'hidden' : '' }} pt-6 pb-6" id="section-mempelai-wanita">
                            <div class="flex-start flex cursor-pointer items-center">
                                <div class="-ml-2 mr-3 -mt-2 flex h-4 w-4 items-center justify-center rounded-full bg-blue-600">
                                </div>
                                <h4 class="-mt-2 text-xl font-semibold text-gray-800">Profile Mempelai Wanita </h4>
                            </div>
                            <div class="{{ $dataMempelaiWanita === null ? '' : 'hidden' }} ml-6" id="form-wanita">
                                <p class="desc-timeline">Silahkan isi formulir dengan lengkap.</p>
                                @include('user.complete-register.partials.formMempelaiWanita')
                            </div>

                            <div class="{{ $dataMempelaiWanita === null ? 'hidden' : '' }} ml-6" id="form-mempelai-wanita-not-null">
                                <p class="-ml-1 text-sm text-green-500">Informasi profile mempelai Wanita sudah lengkap.</p>
                            </div>
                        </li>

                    </ol>
                </div>
            </section>
        </div>
    </main>

    <x-toast-alert id="toast-success" type="success" message="Berhasil." />
@endsection

@push('scripts')
    <script>
        flatpickr("#tanggal-lahir-pria", {
            locale: "id",
            dateFormat: "d/m/Y",
        });

        flatpickr("#tanggal-lahir-wanita", {
            locale: "id",
            dateFormat: "d/m/Y",
        });
    </script>
    <script type="module">
        // Variabel
        $('#footer').addClass('hidden')
        var dataMempelaiPria = @json($dataMempelaiPria);
        var dataMempelaiWanita = @json($dataMempelaiWanita);

        var dataNull = {
            'dataMempelaiPria' : dataMempelaiPria !== null ? false : true,
            'dataMempelaiWanita' : dataMempelaiWanita !== null ? false : true,
        }

        if(dataMempelaiPria === null){
            $('html, body').animate({
                scrollTop: $("#section-mempelai-pria").offset().top
            }, 1000);
        } else if(dataMempelaiWanita === null){
            $('html, body').animate({
                scrollTop: $("#section-mempelai-wanita").offset().top
            }, 1000);
        }

        $('#handleStoreDataMempelaiPria').click(function(){
            storeDataMempelaiPria()
        })

        $('#handleStoreDataMempelaiwanita').click(function(){
            storeDataMempelaiWanita()
        })

        function storeDataMempelaiPria() {
            var dataMempelaiPria = {
                id: $('#id-pria').val(),
                nama_lengkap: $('#nama-lengkap-pria').val(),
                nama_panggilan: $('#nama-panggilan-pria').val(),
                tanggal_lahir: $('#tanggal-lahir-pria').val(),
                tempat_lahir: $('#tempat-lahir-pria').val(),
                nama_ayah: $('#nama-ayah-pria').val(),
                nama_ibu: $('#nama-ibu-pria').val(),
                instagram: $('#instagram-pria').val(),
            }

            $.ajax({
                url: `${dataNull.dataMempelaiPria === false ? '/mempelai/update-data-mempelai-pria' : '/mempelai/store-data-mempelai-pria'}`,
                type: 'GET',
                dataType: 'json',
                data: {
                    dataMempelaiPria,
                    dataNull,
                },
                beforeSend: function() {
                    $('.btn-handle').html('Loading...').addClass('opacity-50 cursor-not-allowed');
                },
                error: function(error) {
                    $('.btn-handle').html('Coba lagi').removeClass('opacity-50 cursor-not-allowed').addClass('bg-red-500');
                },
                success: function(response) {
                    $('#toast-success').removeClass('hidden');
                    $('.btn-handle').html('Lanjutkan').removeClass('opacity-50 cursor-not-allowed');
                    setTimeout(() => {
                       $('#toast-success').addClass('hidden')
                    }, 3000);
                    $('#section-mempelai-wanita').removeClass('hidden').addClass('pb-6')
                    $('#section-mempelai-pria').removeClass('pb-6')
                    $('#form-mempelai-pria').addClass('hidden')
                    $('#form-mempelai-pria-not-null').removeClass('hidden')
                    $('html, body').animate({
                        scrollTop: $("#section-mempelai-wanita").offset().top
                    }, 1000);
                    getDataMempelaiPria()
                }
            });
        }

        function storeDataMempelaiWanita(){
            var dataMempelaiWanita = {
                id: $('#id-wanita').val(),
                nama_lengkap: $('#nama-lengkap-wanita').val(),
                nama_panggilan: $('#nama-panggilan-wanita').val(),
                tanggal_lahir: $('#tanggal-lahir-wanita').val(),
                tempat_lahir: $('#tempat-lahir-wanita').val(),
                nama_ayah: $('#nama-ayah-wanita').val(),
                nama_ibu: $('#nama-ibu-wanita').val(),
                instagram: $('#instagram-wanita').val(),
            }

            $.ajax({
                url: `${dataNull.dataMempelaiWanita === false ? '/mempelai/update-data-mempelai-wanita' : '/mempelai/store-data-mempelai-wanita'}`,
                type: 'GET',
                dataType: 'json',
                data: {
                    dataMempelaiWanita,
                    dataNull,
                },
                beforeSend: function() {
                    $('.btn-handle').html('Loading...').addClass('opacity-50 cursor-not-allowed');
                },
                error: function(error) {
                    $('.btn-handle').html('Coba lagi').removeClass('opacity-50 cursor-not-allowed').addClass('bg-red-500');
                },
                success: function(response) {
                    $('#toast-success').removeClass('hidden');
                    $('.btn-handle').html('Lanjutkan').removeClass('opacity-50 cursor-not-allowed');
                    setTimeout(() => {
                       $('#toast-success').addClass('hidden')
                    }, 3000);
                    $('#section-mempelai-wanita').removeClass('pb-6')
                    $('#form-wanita').addClass('hidden')
                    $('html, body').animate({
                        scrollTop: $("#section-mempelai-wanita").offset().top
                    }, 1000);
                    window.location.href = '/dashboard'
                }
            });
        }
</script>
@endpush
function time_elapsed_string($ptime)
{
    $etime = $ptime - time();

    if ($etime < 1)
    {
        return '0 seconds';
    }

    $a = array( 365 * 24 * 60 * 60  =>  'year',
                 30 * 24 * 60 * 60  =>  'month',
                      24 * 60 * 60  =>  'day',
                           60 * 60  =>  'hour',
                                60  =>  '',
                                 1  =>  ''
                );
    $a_plural = array( 'year'   => 'years',
                       'month'  => 'months',
                       'day'    => 'days',
                       'hour'   => 'hours',
                       'minute' => '',
                       'second' => ''
                );

    foreach ($a as $secs => $str)
    {
        $d = $etime / $secs;
        if ($d >= 1)
        {
            $r = round($d);
            return $r . '' . ($r > 1 ? $a_plural[$str] : $str);
        }
    }
}
<?php
// Original Answer
header('Content-Type: application/json');
$request = file_get_contents('php://input');
$req_dump = print_r( $request, true );
$fp = file_put_contents( 'request.log', $req_dump );

// Updated Answer
if($json = json_decode(file_get_contents("php://input"), true)){
   $data = $json;
}
print_r($data);
?>
$data = Project::limit(100)->get();
return ProjectResource::collection($data)->additional(['some_id => 1']);
// Empty data and rules
$validator = \Validator::make([], []);

// Add fields and errors
$validator->errors()->add('fieldName', 'This is the error message');

throw new \Illuminate\Validation\ValidationException($validator);
    $inputs = [
        'email'    => 'foo',
        'password' => 'bar',
    ];

    $rules = [
        'email'    => 'required|email',
        'password' => [
            'required',
            'string',
            'min:10',             // must be at least 10 characters in length
            'regex:/[a-z]/',      // must contain at least one lowercase letter
            'regex:/[A-Z]/',      // must contain at least one uppercase letter
            'regex:/[0-9]/',      // must contain at least one digit
            'regex:/[@$!%*#?&]/', // must contain a special character
        ],
    ];

    $validation = \Validator::make( $inputs, $rules );

    if ( $validation->fails() ) {
        print_r( $validation->errors()->all() );
    }
$event_startdate_raw = intval(get_field('start_date', false, false)) / 1000;
    $event_startdate = new DateTime();
    $event_startdate->setTimestamp($event_startdate_raw)
    $event_startdate->setTimezone(new DateTimeZone(timezone_name_from_abbr('',  get_option('gmt_offset') * 3600, 0)));
    $event_startdate_jMY = $event_startdate->format('j M Y');
// Display Object or Array
public function oa($model)
{
    if (gettype($model) === 'object') {
        dump(get_class($model));
        dump($model->toArray());
    } else {
        dump(gettype($model));
        dump($model);
    }
}
// Display string
public function s($model)
{
    dump($model);
}
<?php
//toXML.php

//create new XML doc
$xmlDoc = new DOMDocument('1.0', 'utf-8');
$xmlDoc->formatOutput = true;

//build XML File  with root element
$xmlRoot = $xmlDoc -> createElement('person');
$xmlDoc->appendChild($xmlRoot);

//build childs of root element
$xmlGender = $xmlDoc->createElement('gender', 'female');
$xmlRoot->appendChild($xmlGender);

$xmlVorname = $xmlDoc->createElement('vorname', 'Eva');
$xmlRoot->appendChild($xmlVorname);

$xmlNachname = $xmlDoc->createElement('nachname', 'Lurch');
$xmlRoot->appendChild($xmlNachname);


$filename = "person.xml";
$xmlDoc->save($filename);

?>
<?php

$dataname = "e2fi1.csv";

$fp = fopen($dataname, "r");

//first line of csv is header, needs to be read out seperately
//fgetcsv macht automatisch weiter bei der nächsten Zeile, merkt sich wo der pointer steht
$row_header = fgetcsv($fp, null, ";");
$row_header_nummer = $row_header[0];
$row_header_vorname = $row_header[1];
$row_header_nachname = $row_header[2];

//create XML
$xml_doc = new DOMDocument('1.0', 'utf-8');
$xml_doc->formatOutput = true;

//build XML file with root element
$xml_root = $xml_doc->createElement('klasse_e2fi1');
$xml_doc->appendChild($xml_root);

//create string from CSV
while (!feof($fp)) {
    $row_a = fgetcsv($fp, null, ";");

    if (empty($row_a)) {
        continue;
    }

    $schueler_nummer = $row_a[0];
    $schueler_vorname = $row_a[1];
    $schueler_nachname = $row_a[2];

    //create sub element for students
    $xml_student = $xml_doc->createElement('schueler');
    $xml_student->setAttribute("nr", $schueler_nummer);
    $xml_root->appendChild($xml_student);

    //create element that fills the
    $xml_vorname = $xml_doc->createElement($row_header_vorname, $schueler_vorname);
    $xml_student->appendChild($xml_vorname);

    $xml_nachname = $xml_doc->createElement($row_header_nachname, $schueler_nachname);
    $xml_student->appendChild($xml_nachname);
}

$xml_filename = "klasse1fi1.xml";
$xml_doc->save($xml_filename);
<?php
require_once('class.excel_xml.php');

$xls = new excel_xml; // initiate the class

$xls->set_titles(array('title one','title two','title three')); // optional: sets the titles of the spreadsheet columns

// adding 6 rows to the spreadsheet

$xls->add_row(array('text',-22.2,'bla bla')); // first row

$xls->add_row(array('1500.3',14.5,'bingo!')); // second row

$xls->add_row(array('2014-11-01',14.5,'a date in cell A4!!')); // third row

$xls->add_row(array('Timestamp in cell C5',14.5,'2014-11-01 12:00:10','extra data, a longer text')); // fourth row

$xls->add_row(array()); // fifth (empty) row

$xls->add_row(array('Time in cell C7',14.5,'12:00:10'));// sixth row

// writes output to file.xml (check please write permissions)
//$xls->output('file'); // comment it out to enable writing

// send the data to the browser
$xls->output();
<?php
/** create XML file */ 
$mysqli = new mysqli("localhost", "root", "", "dbbookstore");
/* check connection */
if ($mysqli->connect_errno) {
   echo "Connect failed ".$mysqli->connect_error;
   exit();
}
$query = "SELECT id, title, author_name, price, ISBN, category FROM books";
$booksArray = array();
if ($result = $mysqli->query($query)) {
    /* fetch associative array */
    while ($row = $result->fetch_assoc()) {
       array_push($booksArray, $row);
    }
  
    if(count($booksArray)){
         createXMLfile($booksArray);
     }
    /* free result set */
    $result->free();
}
/* close connection */
$mysqli->close();
function createXMLfile($booksArray){
  
   $filePath = 'book.xml';
   $dom     = new DOMDocument('1.0', 'utf-8'); 
   $root      = $dom->createElement('books'); 
   for($i=0; $i<count($booksArray); $i++){
     
     $bookId        =  $booksArray[$i]['id'];  
     $bookName = htmlspecialchars($booksArray[$i]['title']);
     $bookAuthor    =  $booksArray[$i]['author_name']; 
     $bookPrice     =  $booksArray[$i]['price']; 
     $bookISBN      =  $booksArray[$i]['ISBN']; 
     $bookCategory  =  $booksArray[$i]['category'];  
     $book = $dom->createElement('book');
     $book->setAttribute('id', $bookId);
     $name     = $dom->createElement('title', $bookName); 
     $book->appendChild($name); 
     $author   = $dom->createElement('author', $bookAuthor); 
     $book->appendChild($author); 
     $price    = $dom->createElement('price', $bookPrice); 
     $book->appendChild($price); 
     $isbn     = $dom->createElement('ISBN', $bookISBN); 
     $book->appendChild($isbn); 
     
     $category = $dom->createElement('category', $bookCategory); 
     $book->appendChild($category);
 
     $root->appendChild($book);
   }
   $dom->appendChild($root); 
   $dom->save($filePath); 
 } 
function createXMLfile($booksArray){
  
   $filePath = 'book.xml';

   $dom     = new DOMDocument('1.0', 'utf-8'); 

   $root      = $dom->createElement('books'); 

   for($i=0; $i<count($booksArray); $i++){
     
     $bookId        =  $booksArray[$i]['id'];  

     $bookName      =   htmlspecialchars($booksArray[$i]['title']);

     $bookAuthor    =  $booksArray[$i]['author_name']; 

     $bookPrice     =  $booksArray[$i]['price']; 

     $bookISBN      =  $booksArray[$i]['ISBN']; 

     $bookCategory  =  $booksArray[$i]['category'];  

     $book = $dom->createElement('book');

     $book->setAttribute('id', $bookId);

     $name     = $dom->createElement('title', $bookName); 

     $book->appendChild($name); 

     $author   = $dom->createElement('author', $bookAuthor); 

     $book->appendChild($author); 

     $price    = $dom->createElement('price', $bookPrice); 

     $book->appendChild($price); 

     $isbn     = $dom->createElement('ISBN', $bookISBN); 

     $book->appendChild($isbn); 
     
     $category = $dom->createElement('category', $bookCategory); 

     $book->appendChild($category);
 
     $root->appendChild($book);

   }

   $dom->appendChild($root); 

   $dom->save($filePath); 

 } 
<!DOCTYPE html>
<html lang="en">

<head>
	<meta charset="UTF-8">
	<meta name="viewport" content=
		"width=device-width, initial-scale=1.0">
	<meta http-equiv="X-UA-Compatible" content="ie=edge">

	<link rel="stylesheet" href=
"https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css">
	<title>Attendance Page</title>
</head>

<body>
	<div class="container">
		<div class="row">
			<h2>Attendance</h2>
			<table class="table table-hover">
				<thead>
					<tr>
						<th>Sno.</th>
						<th>Student Name</th>
						<th>Attendance</th>
					</tr>
				</thead>

				<tbody>
					<?php
						include_once('connection.php');
						$a=1;
						$stmt = $conn->prepare("SELECT * FROM kundendaten");
						$stmt->execute();
						$users = $stmt->fetchAll();
						foreach($users as $user)
						{
					?>
					<tr>
						<td>
							<?php echo $user['id']; ?>
						</td>
						<td>
							<?php echo $user['studentname']; ?>
						</td>

						<td>
							<div class="form-check form-check-inline">
								<input class="form-check-input"
										type="radio" name="''"
										
										id="inlineRadio1"
									value="'..$a..'">
								<label class="form-check-label"
									for="inlineRadio1">A</label>
							</div>

							<div class="form-check form-check-inline">
								<input class="form-check-input"
									type="radio" name="'..$a..'"
									id="inlineRadio2" value="option2">

								<label class="form-check-label"
									for="inlineRadio2">P</label>
							</div>
						</td>
					</tr>
					<?php
					}
					?>
				</tbody>
			</table>

			<input class="btn btn-primary"
					type="submit" value="Submit">
		</div>
	</div>
</body>

</html>
.ssh directory: 700 (drwx------)
public key (.pub file): 644 (-rw-r--r--)
private key (id_rsa): 600 (-rw-------)
#  Home directory
lastly your home directory should not be writeable by the group or others (default 755 (drwxr-xr-x)).
 If you are looking for better security and privacy, you can change the default permissions to 750.
request()->validate([
            'name'=>'required',
            'email'=>'required|email',
            'subject'=>'required'
        ]);
Mail::send('emails.correo1', $datos, function ($message) use ($datos){
            $message->from($datos['email'], $datos['name'])
                    ->to('pablo.martin.lopez@ieslaarboleda.es', 'Administrador')
                    ->subject($datos['subject']);
        });
return back()->with('flash', $request->name.' mensaje enviado');
@if (session()->has('flash'))
	<div class="alert alert-info alert-dismissable">
		<a href="#" class="close" data-dismiss="alert" aria-label="close">×</a>
			{{ session()->get('flash') }}
	</div>
@endif
$apiKey = getenv('SENDGRID_API_KEY');
//Custom Validation 

$validated = Validator::make($data, [
                    'username' => 'required|unique:wbx_pos_merchant_terminals', // note the email field
                    'email' => 'required|unique:wbx_pos_merchant_terminals', // note the email field
                ]);
                return json_encode(
                    [
                        'error' => true,
                        'messages'=>$validated->errors()->all()
                    ]
                );
$thumbnail = get_the_post_thumbnail( $the_id, $image_size );
if ( $thumbnail == '' ) {
  $press_pdf = get_field( 'press_releases_pdf', $the_id );
  if ( $press_pdf ) {
    $file_url = $press_pdf['url'];
    $pdf_image = str_replace('.pdf', '-pdf.jpg', $file_url);
  }
  $thumbnail = '<img class="pdf-image-thumbnail" src="'.$pdf_image.'">';
}
Route::get('/concat-table', function(){
    $users = App\Models\User::get();
    $posts = App\Models\Post::get();
    $data = $users->concat($posts);
    dd($data);
});
curl -sS https://getcomposer.org/installer | php -- --install-dir=/usr/local/bin --filename=composer --1
public function ImageOrderUpdate (Request $request, $prop, $photo) {

//The photo to edit 
$Photos_Edit = Images::where('property_id', $prop->id)->where('id', $photo)->firstorfail();

$OldPosition = $Photos_Edit->order;     // Old position
$NewPosition = $request->photoorder;    // New position

// Moving down where the fall between positions
if($NewPosition > $OldPosition) {
    Images::where('order','<', $NewPosition)->where('order','>', $OldPosition)->decrement('order');
} 
else {
    Images::where('order','>', $NewPosition)->where('order','<', $OldPosition)->increment('order');
}

// Update the image sort position
$Photos_Edit->order = $NewPosition;

return back();
@if (Route::has('login'))
        <div class="hidden fixed top-0 right-0 px-6 py-4">
            @auth
                <a href="{{ url('/dashboard') }}" class="text-sm text-gray-700 dark:text-gray-500 underline">Dashboard</a>
            @else
                <a href="{{ route('login') }}" class="text-sm text-gray-700 dark:text-gray-500 underline">Log in</a>

                @if (Route::has('register'))
                    <a href="{{ route('register') }}"
                        class="ml-4 text-sm text-gray-700 dark:text-gray-500 underline">Register</a>
                @endif
            @endauth
        </div>
    @endif
<form role="search" method="get" id="searchform" action="<?php echo home_url( '/' ); ?>">
    <div>
        <input type="text" value="" name="s" id="s" placeholder="Search" />
        <input type="submit" id="searchsubmit" value="Search" />
    </div>
</form>
wp_enqueue_style('single-team', get_stylesheet_directory_uri().'/assets/css/single-team.css');
$content = apply_filters( 'the_content', get_the_content() );
echo $content;
// add this to functions.php
//register acf fields to Wordpress API
//https://support.advancedcustomfields.com/forums/topic/json-rest-api-and-acf/

function acf_to_rest_api($response, $post, $request) {
    if (!function_exists('get_fields')) return $response;

    if (isset($post)) {
        $acf = get_fields($post->id);
        $response->data['acf'] = $acf;
    }
    return $response;
}
add_filter('rest_prepare_post', 'acf_to_rest_api', 10, 3);
define( 'WP_DEBUG', true );
define( 'WP_DEBUG_LOG', true );
define( 'WP_DEBUG_DISPLAY', false );
//Find duplicates 

$arr = array( 
    'unique', 
    'duplicate', 
    'distinct', 
    'justone', 
    'three3', 
    'duplicate', 
    'three3', 
    'three3', 
    'onlyone' 
);

$unique = array_unique($arr); 
$dupes = array_diff_key( $arr, $unique ); 
    // array( 5=>'duplicate', 6=>'three3' 7=>'three3' )

// count duplicates

array_count_values($dupes); // array( 'duplicate'=>1, 'three3'=>2 )
// when eager loading
$school = School::with(['students' => function ($q) {
  $q->orderBy('whateverField', 'asc/desc');
}])->find($schoolId);

// when lazy loading
$school = School::find($schoolId);
$school->load(['students' => function ($q) {
  $q->orderBy('whateverField', 'asc/desc');
}]);

// or on the collection
$school = School::find($schoolId);
// asc
$school->students->sortBy('whateverProperty');
// desc
$school->students->sortByDesc('whateverProperty');


// or querying students directly
$students = Student::whereHas('school', function ($q) use ($schoolId) {
  $q->where('id', $schoolId);
})->orderBy('whateverField')->get();
//Use localStorage for that. It's persistent over sessions.

//Writing :
localStorage['myKey'] = 'somestring'; // only strings

//Reading :
var myVar = localStorage['myKey'] || 'defaultValue';

//If you need to store complex structures, you might serialize them in JSON. For example :

//Reading :
var stored = localStorage['myKey'];
if (stored) myVar = JSON.parse(stored);
else myVar = {a:'test', b: [1, 2, 3]};

//Writing :
localStorage['myKey'] = JSON.stringify(myVar);

//Note that you may use more than one key. They'll all be retrieved by all pages on the same domain.

//Unless you want to be compatible with IE7, you have no reason to use the obsolete and small cookies.
add_filter( 'woocommerce_package_rates', 'unset_shipping_when_free_is_available_all_zones', 9999, 2 );

function unset_shipping_when_free_is_available_all_zones( $rates, $package ) {

    $all_free_rates = array();

    foreach ( $rates as $rate_id => $rate ) {
        if ( 'free_shipping' === $rate->method_id ) {
            $all_free_rates[ $rate_id ] = $rate;
            break;
        }
    }

    if ( empty( $all_free_rates )) {
        return $rates;
    } else {
        return $all_free_rates;
    } 
}
<?php  

    // PAGINATION CODE

    $paged = ( get_query_var( 'paged' ) ) ? get_query_var( 'paged' ) : 1;

    $mainarray = array(

        'post_type' => array('post'),

        'post_status' => array('publish'),

        'orderby' => 'date',

        'order' => 'DESC',

        'posts_per_page' => 6,

        'paged'       => $paged,

    );

    $q = new WP_Query($mainarray); 

?>

​

    <div class="row custom-blog-main-wrapper">

        <?php while ($q->have_posts()) : $q->the_post(); ?>

        <div class="col-md-4 col-sm-6">

            <div class="blog-news-wrapper">

                <div class="blog-image">

                    <a href="<?php the_permalink(); ?>">

                        <?php if (has_post_thumbnail()):

$thumbnail = wp_get_attachment_image_src(get_post_thumbnail_id(),'large', true);

?>

                        <img src="<?php echo $thumbnail[0]; ?>" alt="Picture" class="featured-image">

                        <?php else: ?>

                        <img src="<?php echo site_url('PATH'); ?>" alt="Picture" class="featured-image">

                        <?php endif; ?>

                    </a>

                </div>

                <div class="blog-content">

                    <p class="blog-date">

                        <?php echo get_the_date('M d Y'); ?>

                    </p>

                    <h3 class="blog-title">

                        <a href="<?php the_permalink(); ?>">

                            <?php the_title(); ?>

                        </a>

                    </h3>

                    <div class="blog-inner">

                        <p class="blog-text">

                            <?php if(!empty(get_the_excerpt())){

                                echo strip_tags(substr(get_the_excerpt(), 0, 200));

                            }

                            else{
php artisan make:migration update_products_table
add_filter ('add_to_cart_redirect', 'redirect_to_checkout');

function redirect_to_checkout() {
    global $woocommerce;
    $checkout_url = $woocommerce->cart->get_checkout_url();
    return $checkout_url;
}
add_filter( 'woocommerce_product_tabs', 'woo_rename_tab', 98);
function woo_rename_tab($tabs) {

 $tabs['description']['title'] = 'More info';

 return $tabs;
}
add_filter('woocommerce_get_availability', 'availability_filter_func');

function availability_filter_func($availability)
{
	$availability['availability'] = str_ireplace('Out of stock', 'Sold', $availability['availability']);
	return $availability;
}
add_action( 'woocommerce_email_after_order_table', 'add_payment_method_to_admin_new_order', 15, 2 );
 
function add_payment_method_to_admin_new_order( $order, $is_admin_email ) {
  if ( $is_admin_email ) {
    echo '<p><strong>Payment Method:</strong> ' . $order->payment_method_title . '</p>';
  }
}
function art_woocommerce_sorting_attributes_list( $attr ) {

	return wp_list_sort( $attr, 'attribute_label', 'ASC' );
}


add_filter( 'woocommerce_attribute_taxonomies', 'art_woocommerce_sorting_attributes_list' );
function searchfilter($query) {
 
    if ($query->is_search && !is_admin() && !is_woocommerce()) {
        $query->set('post_type','post');
    }
 
return $query;
}
 
add_filter('pre_get_posts','searchfilter');
add_action( 'pre_get_posts', 'mov_vec_archive_page' );

function mov_vec_archive_page( $query ) {
	
	 // Evita añadir meta argumentos en las páginas de adminsitración de WordPress
    if (is_admin()) {
        return;
    }
	// Solo lo aplico a un CPT determinado y a una taxonomía personalizada
    if( $query->is_main_query() && is_post_type_archive( 'nombre_de_mi_cpt' ) || $query->is_main_query() && is_tax('nombre_de_mi_custom_taxonomy')  ) {
		
		//Obtenemos la meta query original
        $meta_query = (array)$query->get('meta_query');

        // Aplico la modificación de la query
        $query->set( 'posts_per_page', '8' );
		
        $meta_query = array(
			
			'agrupar_listado_por_campo_personalizado' => array(
				'key' => 'nombre_campo_personalziado_para_agrupar_posts',
			),
			
			'destacado_del_listado' => array(
				'key' => 'nombre_campo_personalizado_true_false_acf',
			),
		);

        // Set the meta query to the complete, altered query
        $query->set( 'meta_query', $meta_query );
		$query->set( 'orderby', array( 'agrupar_listado_por_campo_personalizado' => 'ASC', 'destacado_del_listado' => 'DESC', 'title' => 'ASC'  ) );
		
	}
}
function np_woocommerce_sorting_attributes_list( $attr ) {

	return wp_list_sort( $attr, 'attribute_label', 'ASC' );
}

add_filter( 'woocommerce_attribute_taxonomies', 'np_woocommerce_sorting_attributes_list' );
add_action('admin_init', function () {
    // Redirect any user trying to access comments page
    global $pagenow;
    
    if ($pagenow === 'edit-comments.php') {
        wp_safe_redirect(admin_url());
        exit;
    }

    // Remove comments metabox from dashboard
    remove_meta_box('dashboard_recent_comments', 'dashboard', 'normal');

    // Disable support for comments and trackbacks in post types
    foreach (get_post_types() as $post_type) {
        if (post_type_supports($post_type, 'comments')) {
            remove_post_type_support($post_type, 'comments');
            remove_post_type_support($post_type, 'trackbacks');
        }
    }
});

// Close comments on the front-end
add_filter('comments_open', '__return_false', 20, 2);
add_filter('pings_open', '__return_false', 20, 2);

// Hide existing comments
add_filter('comments_array', '__return_empty_array', 10, 2);

// Remove comments page in menu
add_action('admin_menu', function () {
    remove_menu_page('edit-comments.php');
});

// Remove comments links from admin bar
add_action('init', function () {
    if (is_admin_bar_showing()) {
        remove_action('admin_bar_menu', 'wp_admin_bar_comments_menu', 60);
    }
});
/wp-login.php?action=entered_recovery_mode
add_filter( 'avf_google_heading_font', 'avia_add_heading_font');
function avia_add_heading_font($fonts) {
    $fonts['PT Sans Narrow'] = 'PT Sans Narrow:400,700';
    $fonts['PT Sans'] = 'PT Sans:400,700,400italic,700italic';
    return $fonts;
}

add_filter( 'avf_google_content_font', 'avia_add_content_font');
function avia_add_content_font($fonts) {
    $fonts['PT Sans'] = 'PT Sans:400,700,400italic,700italic';
    $fonts['PT Sans Narrow'] = 'PT Sans Narrow:400,700';
    return $fonts;
}
// show
return Responder::respondValid(
    [
        'Model' => Model::with($relationships)->find($consultTopicId)
    ]
);

// index
return Responder::respondValid(
  	[
      	'MemberProviderConsults' => ConsultLogResource::collection(
        	MemberProviderConsult::with(
            	$this->relations
            )->where('columns', $filter)->orderBy('id', 'desc')->get()
      )
  ]
);

// Store
 $models = Model::create(
    [
        'name' => $request->input('name')
        'description' => $request->input('description', null)
    ]
);

$model->BelongsToManyRelation()->sync($request->input('relatedModelIds'));

return Responder::respondValid(
    [
        'model' => $model
    ]
);

// Update
$model = Model::find($modelId);

if ($request->input('name')) {
    $model->update(
        [
            'name' => $request->input('name')
            'description' => $request->input('description', null)
        ]
    );
}
$model->belongsToManyRelation()->sync($request->input('relatedModelIds'));
$model->questions()->sync($request->input('otherRelatedModelIds'));

$this->updateRequiredQuestions($request, $model->id);

return Responder::respondValid(
    [
        'model' => $model->refresh()->load($this->relations)
    ]
);
GET /widgets/ HTTP/1.1
Host: api.mydomain.com
Origin: https://www.mydomain.com
[Rest of request...]
The easiest way is to JSON-encode your object and then decode it back to an array:

$array = json_decode(json_encode($object), true);

Or if you prefer, you can traverse the object manually, too:

foreach ($object as $value) 
    $array[] = $value->post_id;
<?php 

function get_subcategory_terms( $terms, $taxonomies, $args ) {
 
	$new_terms 	= array();
	$hide_category 	= array( 300 );  // 300 is the category id, replace it with yours
 	
 	  // if a product category and on the shop page
	if ( in_array( 'product_cat', $taxonomies ) && !is_admin() && is_shop() ) {
	    foreach ( $terms as $key => $term ) {
		if ( ! in_array( $term->term_id, $hide_category ) ) { 
			$new_terms[] = $term;
		}
	    }
	    $terms = $new_terms;
	}
  return $terms;
}
add_filter( 'get_terms', 'get_subcategory_terms', 10, 3 );
<?php
function plugin_hide() {
  global $wp_list_table;
  // replace your plugin url here
  $hidearr = array('advanced-custom-fields/acf.php' , 'otro-plugin/plugin.php');  
  
  $myplugins = $wp_list_table->items;
  foreach ($myplugins as $key => $val) {
    if (in_array($key,$hidearr)) {
      unset($wp_list_table->items[$key]);
    }
  }
}
add_action('pre_current_active_plugins', 'plugin_hide');
?>
add_filter( 'woocommerce_countries_inc_tax_or_vat', function( $tax_or_vat ) {
	return "Texto personalizado"; // Escribir nuevo texto o dejar en blanco para ocultar
} );

add_filter( 'woocommerce_countries_ex_tax_or_vat', function( $tax_or_vat ) {
	return "Texto personalizado"; // Escribir nuevo texto o dejar en blanco para ocultar
} );
After the Ethereum Merge Event, Ethereum has become more admired in the crypto industry. Meantime, the price of ethereum has skyrocketed. Do you wanna create an ethereum standard token? https://bit.ly/3TlCuwx 

Being the trusted Ethereum Token Development Company that rendering excellent Token Development Services on multiple ethereum standards such as ERC20, ERC1155, ERC223, ERC721, ERC777, ERC827, ERC 998, and ERC1400 to enhance your tokenomics business and platform.

For Instant Connect, 
Whatsapp +91 9384587998 || Telegram @maticzofficial

// Disable cropping of Big Preview on Single
function custom_blog_img_size($thumb,$current_post,$size) {
	return get_the_post_thumbnail($current_post["the_id"], 'large');
}
add_filter('avf_post_featured_image_link','custom_blog_img_size', 10, 3);
public function __construct() {

	$this->id = 'misha'; // payment gateway plugin ID
	$this->icon = ''; // URL of the icon that will be displayed on checkout page near your gateway name
	$this->has_fields = true; // in case you need a custom credit card form
	$this->method_title = 'Misha Gateway';
	$this->method_description = 'Description of Misha payment gateway'; // will be displayed on the options page

	// gateways can support subscriptions, refunds, saved payment methods,
	// but in this tutorial we begin with simple payments
	$this->supports = array(
		'products'
	);

	// Method with all the options fields
	$this->init_form_fields();

	// Load the settings.
	$this->init_settings();
	$this->title = $this->get_option( 'title' );
	$this->description = $this->get_option( 'description' );
	$this->enabled = $this->get_option( 'enabled' );
	$this->testmode = 'yes' === $this->get_option( 'testmode' );
	$this->private_key = $this->testmode ? $this->get_option( 'test_private_key' ) : $this->get_option( 'private_key' );
	$this->publishable_key = $this->testmode ? $this->get_option( 'test_publishable_key' ) : $this->get_option( 'publishable_key' );

	// This action hook saves the settings
	add_action( 'woocommerce_update_options_payment_gateways_' . $this->id, array( $this, 'process_admin_options' ) );

	// We need custom JavaScript to obtain a token
	add_action( 'wp_enqueue_scripts', array( $this, 'payment_scripts' ) );
	
	// You can also register a webhook here
	// add_action( 'woocommerce_api_{webhook name}', array( $this, 'webhook' ) );
 }
/*
 * This action hook registers our PHP class as a WooCommerce payment gateway
 */
add_filter( 'woocommerce_payment_gateways', 'misha_add_gateway_class' );
function misha_add_gateway_class( $gateways ) {
	$gateways[] = 'WC_Misha_Gateway'; // your class name is here
	return $gateways;
}

/*
 * The class itself, please note that it is inside plugins_loaded action hook
 */
add_action( 'plugins_loaded', 'misha_init_gateway_class' );
function misha_init_gateway_class() {

	class WC_Misha_Gateway extends WC_Payment_Gateway {

 		/**
 		 * Class constructor, more about it in Step 3
 		 */
 		public function __construct() {

		...

 		}

		/**
 		 * Plugin options, we deal with it in Step 3 too
 		 */
 		public function init_form_fields(){

		...
	
	 	}

		/**
		 * You will need it if you want your custom credit card form, Step 4 is about it
		 */
		public function payment_fields() {

		...
				 
		}

		/*
		 * Custom CSS and JS, in most cases required only when you decided to go with a custom credit card form
		 */
	 	public function payment_scripts() {

		...
	
	 	}

		/*
 		 * Fields validation, more in Step 5
		 */
		public function validate_fields() {

		...

		}

		/*
		 * We're processing the payments here, everything about it is in Step 5
		 */
		public function process_payment( $order_id ) {

		...
					
	 	}

		/*
		 * In case you need a webhook, like PayPal IPN etc
		 */
		public function webhook() {

		...
					
	 	}
 	}
}
/*
 * This action hook registers our PHP class as a WooCommerce payment gateway
 */
add_filter( 'woocommerce_payment_gateways', 'misha_add_gateway_class' );
function misha_add_gateway_class( $gateways ) {
	$gateways[] = 'WC_Misha_Gateway'; // your class name is here
	return $gateways;
}

/*
 * The class itself, please note that it is inside plugins_loaded action hook
 */
add_action( 'plugins_loaded', 'misha_init_gateway_class' );
function misha_init_gateway_class() {

	class WC_Misha_Gateway extends WC_Payment_Gateway {

 		/**
 		 * Class constructor, more about it in Step 3
 		 */
 		public function __construct() {

		...

 		}

		/**
 		 * Plugin options, we deal with it in Step 3 too
 		 */
 		public function init_form_fields(){

		...
	
	 	}

		/**
		 * You will need it if you want your custom credit card form, Step 4 is about it
		 */
		public function payment_fields() {

		...
				 
		}

		/*
		 * Custom CSS and JS, in most cases required only when you decided to go with a custom credit card form
		 */
	 	public function payment_scripts() {

		...
	
	 	}

		/*
 		 * Fields validation, more in Step 5
		 */
		public function validate_fields() {

		...

		}

		/*
		 * We're processing the payments here, everything about it is in Step 5
		 */
		public function process_payment( $order_id ) {

		...
					
	 	}

		/*
		 * In case you need a webhook, like PayPal IPN etc
		 */
		public function webhook() {

		...
					
	 	}
 	}
}
/*
 * This action hook registers our PHP class as a WooCommerce payment gateway
 */
add_filter( 'woocommerce_payment_gateways', 'misha_add_gateway_class' );
function misha_add_gateway_class( $gateways ) {
	$gateways[] = 'WC_Misha_Gateway'; // your class name is here
	return $gateways;
}

/*
 * The class itself, please note that it is inside plugins_loaded action hook
 */
add_action( 'plugins_loaded', 'misha_init_gateway_class' );
function misha_init_gateway_class() {

	class WC_Misha_Gateway extends WC_Payment_Gateway {

 		/**
 		 * Class constructor, more about it in Step 3
 		 */
 		public function __construct() {

		...

 		}

		/**
 		 * Plugin options, we deal with it in Step 3 too
 		 */
 		public function init_form_fields(){

		...
	
	 	}

		/**
		 * You will need it if you want your custom credit card form, Step 4 is about it
		 */
		public function payment_fields() {

		...
				 
		}

		/*
		 * Custom CSS and JS, in most cases required only when you decided to go with a custom credit card form
		 */
	 	public function payment_scripts() {

		...
	
	 	}

		/*
 		 * Fields validation, more in Step 5
		 */
		public function validate_fields() {

		...

		}

		/*
		 * We're processing the payments here, everything about it is in Step 5
		 */
		public function process_payment( $order_id ) {

		...
					
	 	}

		/*
		 * In case you need a webhook, like PayPal IPN etc
		 */
		public function webhook() {

		...
					
	 	}
 	}
}
<?php
/*
 * Plugin Name: WooCommerce Custom Payment Gateway
 * Plugin URI: https://rudrastyh.com/woocommerce/payment-gateway-plugin.html
 * Description: Take credit card payments on your store.
 * Author: Misha Rudrastyh
 * Author URI: http://rudrastyh.com
 * Version: 1.0.1
 */
<?php
/*
 * Plugin Name: WooCommerce Custom Payment Gateway
 * Plugin URI: https://rudrastyh.com/woocommerce/payment-gateway-plugin.html
 * Description: Take credit card payments on your store.
 * Author: Misha Rudrastyh
 * Author URI: http://rudrastyh.com
 * Version: 1.0.1
 */
<?php echo do_shortcode(get_field('my_shortcode')); ?php>
<?php
/**
 * Prevent update notification for plugin
 * http://www.thecreativedev.com/disable-updates-for-specific-plugin-in-wordpress/
 * Place in theme functions.php or at bottom of wp-config.php
 */
function disable_plugin_updates( $value ) {
  if ( isset($value) && is_object($value) ) {
    if ( isset( $value->response['theme-my-login/theme-my-login.php'] ) ) {
      unset( $value->response['theme-my-login/theme-my-login.php'] );
    }
  }
  return $value;
}
add_filter( 'site_transient_update_plugins', 'disable_plugin_updates' );
// Limit 'the_content()' in wp
<div class="book-description">
<?php $content= get_the_content();
echo substr($content, 0,400)."..."."<a href='".get_permalink()."'>[Learn More]</a>";
?>
 </div> 
// Disable Sideber on custom archive
add_filter('avia_layout_filter', 'avia_change_post_layout', 10, 2);
function avia_change_post_layout($layout, $post_id){
    if(is_category('CATEGORY ID/NAME HERE'))
    {
        $layout['current'] = $layout["fullsize"];
        $layout['current']['main'] = "fullsize";
    }
    return $layout;
}
// Splide JS 
function splide_js() {
    if (is_singular('company')) {
        wp_enqueue_script( 'splide-js', 'https://cdn.jsdelivr.net/npm/@splidejs/splide@4.1.2/dist/js/splide.min.js', null, null, true );
        wp_enqueue_style('splide-css', 'https://cdn.jsdelivr.net/npm/@splidejs/splide@4.1.2/dist/css/splide.min.css');
        
    }
}

add_action('wp_enqueue_scripts','splide_js');

// Splide JS Markup
<section class="splide" aria-label="Splide Basic HTML Example">
  <div class="splide__track">
		<ul class="splide__list">
			<li class="splide__slide">Slide 01</li>
			<li class="splide__slide">Slide 02</li>
			<li class="splide__slide">Slide 03</li>
		</ul>
  </div>
</section>
single-cpt.php

<?php
	if ( ! defined( 'ABSPATH' ) ){ die(); }

	global $avia_config, $wp_query;

	/*
	 * get_header is a basic wordpress function, used to retrieve the header.php file in your theme directory.
	 */
	get_header(); ?>

        <div class='container_wrap container_wrap_first main_color <?php avia_layout_class( 'main' ); ?>'>
			<div class='container'>
				<main class='template-page content  <?php avia_layout_class( 'content' ); ?> units' <?php avia_markup_helper(array('context' => 'content','post_type'=>'page'));?>>
        		
        		<!--CUSTOM MARKUP GOES BELOW -->
                TEST
				
				<!--end content-->
				</main>

			</div><!--end container-->

		</div><!-- close default .container_wrap element -->



<?php
		get_footer();
[gravityform id="1" title="false" description="false" ajax="true" tabindex="124"]
// Avia Layout Builder in custom post types

function avf_alb_supported_post_types_mod( array $supported_post_types )
{
  $supported_post_types[] = 'case_studies';
  return $supported_post_types;
}
add_filter('avf_alb_supported_post_types', 'avf_alb_supported_post_types_mod', 10, 1);

function avf_metabox_layout_post_types_mod( array $supported_post_types )
{
 $supported_post_types[] = 'case_studies';
 return $supported_post_types;
}
add_filter('avf_metabox_layout_post_types', 'avf_metabox_layout_post_types_mod', 10, 1);
// Fa Fa Icons Script
function site_styles() {
    wp_register_style('fontawesome', 'https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.3.0/css/all.min.css', array(), false, 'all');
    wp_enqueue_style('fontawesome');
}
add_action('wp_enqueue_scripts', 'site_styles');
// Shortcold for HTML 
function vip_svg() { 
	ob_start(); ?>
	<a href="/pricing/vip/">
		<HTML>
	</a>
<?php return ob_get_clean(); 
}

add_shortcode('vip_svg_code', 'vip_svg');
function enqueue_custom_fonts()
{
    wp_register_style('custom-fonts', get_stylesheet_directory_uri() . '/fonts/custom-fonts.css', array(), '1.0', 'all');
    wp_enqueue_style('custom-fonts'); 
    
    
}

add_action('wp_enqueue_scripts', 'enqueue_custom_fonts');
// Shortcode [insight_posts category='' number='']

function insight_posts_shortcode( $atts, $content = null ) {
    loadmoreinsights_scripts();
    $atts = shortcode_atts(
        array(
            'uid' => '',
            'category' => '',
            'number' => '-1',
        ),
        $atts,
        'insight_posts'
    );

    $args = array(
        'post_type' => 'insight',
        'post_status' => 'publish',
        'posts_per_page' => $atts['number'],
        'orderby' => 'date',
        'order' => 'DESC',
        'meta_query' => array(
            array(
                'key' => 'insight_category',
                'value' => $atts['category'],
                'compare' => '='
            )
        )
    );
    $insight_posts_query = new WP_Query( $args );
    ob_start(); ?>

    
    
    <?php
    if ( $insight_posts_query->have_posts() ) { ?>
        
        <div id="<?php echo $atts['uid']; ?>" class="insights-post-wrap">
        
        <?php while( $insight_posts_query->have_posts() ) { $insight_posts_query->the_post(); ?>
        
            <div class="insights-post">
                <div class="insights-post-date"><?php echo get_the_date(); ?></div>
                <?php if(get_field('insight_pdf')) { ?>
                    <div class="insights-title-link"><a target="_blank" href="<?php the_field('insight_pdf'); ?>"><h3 class="insights-post-title"><?php the_title(); ?></h3></a></div>
                <?php } else { ?>
                    <div class="insights-title-link"><a href="<?php the_permalink(); ?>"><h3 class="insights-post-title"><?php the_title(); ?></h3></a></div>
                <?php } ?>
                <?php if(get_field('video_html')) { ?>
                    <div class="insights-post-video"><?php the_field('video_html'); ?></div>
                <?php } ?>
                <div class="insights-post-exceprt"><?php the_field('insight_synopsis'); ?></div>
                
                <?php if(get_field('insight_pdf')) { ?>
                    <div class="insights-post-link"><a target="_blank" href="<?php the_field('insight_pdf'); ?>">Learn More..</a></div>
                <?php } else { ?>
                    <div class="insights-post-link"><a href="<?php the_permalink(); ?>">Read more..</a></div>
                <?php } ?>
    
            </div>

        <?php } ?>
        
        </div>
        <?php
        wp_reset_postdata();
    } else {
        
        echo '<p>Nothing found</p>';
    }
    return ob_get_clean();
}

add_shortcode( 'insight_posts', 'insight_posts_shortcode' );
<?php
      if ( !defined('ABSPATH') ){ die(); }

      global $avia_config;

      /*
       * get_header is a basic wordpress function, used to retrieve the header.php file in your theme directory.
       */
       get_header();

      $title  = __('Blog - Latest News', 'avia_framework'); //default blog title
      $t_link = home_url('/');
      $t_sub = "";

      if(avia_get_option('frontpage') && $new = avia_get_option('blogpage'))
      {
            $title      = get_the_title($new); //if the blog is attached to a page use this title
            $t_link = get_permalink($new);
            $t_sub =  avia_post_meta($new, 'subtitle');
      }

      if( get_post_meta(get_the_ID(), 'header', true) != 'no') echo avia_title(array('heading'=>'strong', 'title' => $title, 'link' => $t_link, 'subtitle' => $t_sub));

      do_action( 'ava_after_main_title' );

?>
        <!-- Insight Heading AREA  -->
        
        <div class='insight-heading-wrap container_wrap container_wrap_first main_color <?php avia_layout_class( 'main' ); ?>'>

            <div class='container template-blog template-single-blog'>

                  <main class='content units <?php avia_layout_class( 'content' ); ?> <?php echo avia_blog_class_string(); ?>' <?php avia_markup_helper(array('context' => 'content','post_type'=>'post'));?>>
                        <div class="post-entry post-entry-type-page post-entry-156">
                            <div class="entry-content-wrapper clearfix">
                                <div class="insight-heading-block">
                                    <h1 class="av-special-heading-tag insight-heading"><?php the_title(); ?></h1>
                                    <span class="insighe-subheading"><?php the_field('insight_subtitle'); ?></span>
                                </div>
                            </div>
                         </div>
                  <!--end content-->
                  </main>

            </div><!--end container-->

      </div>
      
      <!-- Insight BODY AREA  -->
      
      <div class='insight-content-wrap container_wrap container_wrap_first main_color <?php avia_layout_class( 'main' ); ?>'>

            <div class='container template-blog template-single-blog'>

                  <main class='content units <?php avia_layout_class( 'content' ); ?> <?php echo avia_blog_class_string(); ?>' <?php avia_markup_helper(array('context' => 'content','post_type'=>'post'));?>>
                        <div class="post-entry post-entry-type-page post-entry-156">
                            <div class="entry-content-wrapper clearfix">
                                  <div class="insights-inner">
                                        <?php
                                        if (have_posts()) :
                                              while (have_posts()) : the_post();
                                              the_content();
                                            endwhile;
                                        endif; ?>
                                  </div>
                            </div>
                         </div>
                  <!--end content-->
                  </main>

                  <?php
                  $avia_config['currently_viewing'] = "blog";
                  //get the sidebar
                  get_sidebar();

                  ?>

            </div><!--end container-->

      </div><!-- close default .container_wrap element -->
      
      <?php if(get_field('video_html')) { ?>
          
          <!-- Insight VIDEO AREA  -->
            
            <div class='insight-video-wrap container_wrap container_wrap_first alternate_color <?php avia_layout_class( 'main' ); ?>'>
    
                <div class='container template-blog template-single-blog'>
    
                      <main class='content units <?php avia_layout_class( 'content' ); ?> <?php echo avia_blog_class_string(); ?>' <?php avia_markup_helper(array('context' => 'content','post_type'=>'post'));?>>
                            <div class="post-entry post-entry-type-page post-entry-156">
                                <div class="entry-content-wrapper clearfix">
                                    <div class="insights-video">
                                        <?php echo get_field('video_html'); ?>
                                    </div>
                                </div>
                             </div>
                      <!--end content-->
                      </main>
    
                </div><!--end container-->
    
            </div>
        <?php } ?>


<?php get_footer();
function _thz_enable_vcard_upload( $mime_types ){
  	$mime_types['vcf'] = 'text/vcard';
	$mime_types['vcard'] = 'text/vcard';
  	return $mime_types;
}
add_filter('upload_mimes', '_thz_enable_vcard_upload' );
function breadcrumbs() {

	// Code
	if(!is_home()) {
		$output  = '<nav class="breadcrumbs">';
		$output .= '<a href="'.home_url('/').'">Home</a> <span class="divider">/</span> ';
		if (is_category() || is_single()) {
		$output .=	'<a href="'.home_url('/insights/').'">Insights</a>';
			if (is_single()) {
		$output .=	' <span class="divider">/</span> ';
		$output .=	get_the_title();
			}
		} elseif (is_page()) {
		$output .= get_the_title();
		}
		$output .= '</nav>';
	}
	return $output;
}

add_shortcode( 'breadcrumbs', 'breadcrumbs' );
Route:: get ('/', function () {
     \Illuminate\Support\Facades \DB::listen (function ($query) {
         logger($query->sql, $query->bindings); // Helper fn for \Log::info();
     });
     return view ('posts', [
          'posts' => Post::all()
     ]);
 });
$insert_eigenes_turnier_check = $wpdb->insert(
  'tman_anmeldung',
  array(
    'anmeldung_verein' => $anmeldung_verein,
    'anmeldung_verein_id' => $verein_id,
    'turnier_id' => $turnier_id,
    'status_id' => 3,
    'anmeldung_manuell' => 1,
    'anmeldung_gebuehr_bezahlt' => 2,   //2=offen, 1=gebühr erhalten
    'anmeldung_trainer_vorname' => $trainer_vorname,
    'anmeldung_trainer_nachname' => $trainer_nachname,
    'anmeldung_email' => $anmeldung_email,
    'anmeldung_telefon' => $anmeldung_telefon,
    'anmeldung_jugend' => $anmeldung_jugend,
    'anmeldung_nachricht' => "",
    'anmeldung_datum' => $datetime_heute,
    'user_id' => $user_id
  )
);
$anmeldung_id = $wpdb->insert_id;
# Block WordPress xmlrpc.php requests
<Files xmlrpc.php>
order deny,allow
 deny from all
</Files>
public function lastMessages() {
 return $this->hasMany('App\Message', 'recipient_id')->latest()->get()->unique('author_id')
<?php
if(isset($_POST['Submit'])){

  $emp_name=trim($_POST["emp_name"]);
  $emp_number=trim($_POST["emp_number"]);
  $emp_email=trim($_POST["emp_email"]);

  if($emp_name =="") {
    $errorMsg=  "error : You did not enter a name.";
    $code= "1" ;
  }
  elseif($emp_number == "") {
    $errorMsg=  "error : Please enter number.";
    $code= "2";
  }
  //check if the number field is numeric
  elseif(is_numeric(trim($emp_number)) == false){
    $errorMsg=  "error : Please enter numeric value.";
    $code= "2";
  }
  elseif(strlen($emp_number)<10){
    $errorMsg=  "error : Number should be ten digits.";
    $code= "2";
  }
  //check if email field is empty
  elseif($emp_email == ""){
    $errorMsg=  "error : You did not enter a email.";
    $code= "3";
} //check for valid email 
elseif(!preg_match("/^[_\.0-9a-zA-Z-]+@([0-9a-zA-Z][0-9a-zA-Z-]+\.)+[a-zA-Z]{2,6}$/i", $emp_email)){
  $errorMsg= 'error : You did not enter a valid email.';
  $code= "3";
}
else{
  echo "Success";
  //final code will execute here.
}

}
?>
<?php

    class AcessoBD{

        private $conn;
        private $host;
        private $dbname;
        private $username;
        private $password;

        public function __construct($dbname){
            $this ->host="localhost";
            $this ->dbname=$dbname;
            $this ->username="root";
            $this ->password="";
            $this ->setConn();
        }

        private function setConn(){
            try {
                $this ->conn = new PDO("mysql:host=".$this->host.";dbname=".$this->dbname, $this->username, $this->password);
                $this ->conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
            } catch(PDOException $e) {
                echo 'ERROR: ' . $e->getMessage();
            }
        }

        public function select($sql,$parametros){
            $stmt = $this ->conn->prepare($sql);
            $stmt->execute($parametros);
            return $stmt ->fetchAll();
        }
    }
 
 ?>
<?php

class Elemento{

	//Instance variables
	private $tag; //string exemplo:link
	private $atributos; // um elemente tem um array de atributos
	private $temtagfinal; //booleano
	private $subelementos; // um array de elemntos, porque por exemplo, dentro do html leva head e o body.
	private $numtabs; // numero de tabs à esquerda
	private $textTag; 
	
	//Construct
	public function __construct($tag,$temtagfinal,$atributos) {	
		$this->tag=$tag; // para falarmos de uma variavel de instância usa-se $this
		$this->temtagfinal=$temtagfinal;
		$this->atributos=$atributos;
		$this->subelementos=array();
		$this->numtabs=0;
		$this->textTag="";
	}


	//Methods
	public function getCodigo(){
		
		$codigo="";
		for ($i=0;$i<$this->numtabs;$i++){ //este ciclo tem tantas iteracoes quanto o num de tabs definidos
			$codigo.="  ";
		}
		
		$codigo.="<".$this->tag." ";
		foreach($this->atributos as $atributo){
			$codigo.=$atributo." ";
		}
		if (!$this->temtagfinal) $codigo.="/>"."\n";
		else $codigo.=">"."\n";
		
		
		if ($this->temtagfinal) {
			if ($this->textTag==""){
				foreach ($this->subelementos as $subelemento){
					$codigo.=$subelemento->getCodigo(); 
				}
			}else{
				$codigo.=$this->textTag."\n";
			}
			
			for ($i=0;$i<$this->numtabs;$i++){ //
				$codigo.="  ";
			}
			
			$codigo.="</".$this->tag.">"."\n";
		}
		
		
		return $codigo;
	}
	
	public function addSubElemento($subelemento){
		$subelemento->setNumTabs($this->numtabs+1);
		$this->subelementos[count($this->subelementos)]=$subelemento; //count no array da-nos o n de posiçoes do array 	
	}
	
	public function setNumTabs($numtabs) {
		$this->numtabs=$numtabs;
	}

	public function addTextToTag($textTag) {
		$this->textTag=$textTag;
	}
    
	
} 

?>
 Sales::query()->where('this', $that)->get()->groupBy('product.name'); // OR

 Sales::query()->where('this', $that)->get()->groupBy('product.status.name');
/* Dynamic Button for Simple & Variable Product */

/**
 * Main Functions
*/

function sbw_wc_add_buy_now_button_single()
{
    global $product;
    printf( '<button id="sbw_wc-adding-button" type="submit" name="sbw-wc-buy-now" value="%d" class="single_add_to_cart_button buy_now_button button alt">%s</button>', $product->get_ID(), esc_html__( 'Buy Now', 'sbw-wc' ) );
}

add_action( 'woocommerce_after_add_to_cart_button', 'sbw_wc_add_buy_now_button_single' );



/*** Handle for click on buy now ***/

function sbw_wc_handle_buy_now()
{
    if ( !isset( $_REQUEST['sbw-wc-buy-now'] ) )
    {
        return false;
    }

    WC()->cart->empty_cart();

    $product_id = absint( $_REQUEST['sbw-wc-buy-now'] );
    $quantity = absint( $_REQUEST['quantity'] );

    if ( isset( $_REQUEST['variation_id'] ) ) {

        $variation_id = absint( $_REQUEST['variation_id'] );
        WC()->cart->add_to_cart( $product_id, 1, $variation_id );

    }else{
        WC()->cart->add_to_cart( $product_id, $quantity );
    }

    wp_safe_redirect( wc_get_checkout_url() );
    exit;
}

add_action( 'wp_loaded', 'sbw_wc_handle_buy_now' );

/* Dynamic Button for Simple & Variable Product Closed */
விடுப்பா விடுப்பா இமயமலையில் அதிசயம் இருக்கரதும் 🙋🏻🙋🏻
இனிப்பு கடையில் அதிரசம் இருக்கரதும் சகஜம் தானபா..😍
$host = '127.0.0.1';
$db   = 'test';
$user = 'root';
$pass = '';
$charset = 'utf8mb4';

$dsn = "mysql:host=$host;dbname=$db;charset=$charset";
$options = [
    PDO::ATTR_ERRMODE            => PDO::ERRMODE_EXCEPTION,
    PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
    PDO::ATTR_EMULATE_PREPARES   => false,
];
try {
     $pdo = new PDO($dsn, $user, $pass, $options);
} catch (\PDOException $e) {
     throw new \PDOException($e->getMessage(), (int)$e->getCode());
}
if ($mentor->first()) { } 
if (!$mentor->isEmpty()) { }
if ($mentor->count()) { }
if (count($mentor)) { }
if ($mentor->isNotEmpty()) { }
<?php

//The example selects and prints a specific row.

$dsn = "mysql:host=localhost;dbname=mydb";
$user = "user12";
$passwd = "12user";

$pdo = new PDO($dsn, $user, $passwd);

$id = 12;

//This time we use named placeholder (:id) and bindParam.
$stm = $pdo->prepare("SELECT * FROM countries WHERE id = :id");
$stm->bindParam(":id", $id, PDO::PARAM_INT);
$stm->execute();

$row = $stm->fetch(PDO::FETCH_ASSOC);

echo "Id: " . $row['id'] . PHP_EOL;
echo "Name: " . $row['name'] . PHP_EOL;
echo "Population: " . $row['population'] . PHP_EOL;

?>
<?php

//In the example, we use bindValue to create a parameterized query. We use question mark placeholder.

$dsn = "mysql:host=localhost;dbname=mydb";
$user = "root";
$passwd = "andrea";

$pdo = new PDO($dsn, $user, $passwd);


$id = 12;

//Say this input comes from a user.
$stm = $pdo->prepare("SELECT * FROM countries WHERE id = ?");
$stm->bindValue(1, $id);
$stm->execute();

//The select statement fetches a specific row from the table. We bind the value with bindValue to a question mark placeholder.
$row = $stm->fetch(PDO::FETCH_ASSOC);

echo "Id: " . $row['id'] . PHP_EOL;
echo "Name: " . $row['name'] . PHP_EOL;
echo "Population: " . $row['population'] . PHP_EOL;

?>
<?php

//In this example, we fetch data as an associative array.

$dsn = "mysql:host=localhost;dbname=mydb";
$user = "user12";
$passwd = "12user";

$pdo = new PDO($dsn, $user, $passwd);

$stm = $pdo->query("SELECT * FROM countries");

//In the fetchAll method, we use the PDO::FETCH_ASSOC style.
$rows = $stm->fetchAll(PDO::FETCH_ASSOC);

foreach($rows as $row) {

    printf("{$row['id']} {$row['name']} {$row['population']}\n");
}

?>
<?php

//In this code example, we get data in an indexed array.

$dsn = "mysql:host=localhost;dbname=mydb";
$user = "user12";
$passwd = "12user";

$pdo = new PDO($dsn, $user, $passwd);

//We select all data from the countries table.
$stm = $pdo->query("SELECT * FROM countries");

//We pass the PDO:FETCH_NUM style to the fetchAll method.
$rows = $stm->fetchAll(PDO::FETCH_NUM);

//We go over the $rows array and print the fields. The fields are accessed via array indexes.
foreach($rows as $row) {
    printf("$row[0] $row[1] $row[2]\n");
}

?>
<?php
//The code example deletes three rows. It prints the number of affected rows.


$dsn = "mysql:host=localhost;dbname=mydb";
$user = "user12";
$passwd = "12user";

$pdo = new PDO($dsn, $user, $passwd);

$id = 12;

//In this SQL statement, we delete rows with ids 1, 2, and 3. The number of deleted rows is stored in the $nrows variable.
$nrows = $pdo->exec("DELETE FROM countries WHERE id IN (1, 2, 3)");

//We print the number of deleted rows.
echo "The statement affected $nrows rows\n";

?>
<?php

//These variables are used to create a connection string to the database. The dsn is the Data Source Name, which contains the information required to connect to the database.
$dsn = "mysql:host=localhost;dbname=mydb";
$user = "user12";
$passwd = "12user";

//A new PDO object is created. We pass the constructor the data source name and the user name and password. The PDO class represents a connection between PHP and a database server.
$pdo = new PDO($dsn, $user, $passwd);

//The query method executes an SQL statement in a single function call. It returns the result set.
$stm = $pdo->query("SELECT VERSION()");

//The PDO statement's fetch method fetches the next row from a result set. In our case it is a version of MySQL.
$version = $stm->fetch();

//The $version is an array; we get its first value.
echo $version[0] . PHP_EOL;

?>
<?php

$id = 5;
try {
  $conn = new PDO('mysql:host=localhost;dbname=meuBancoDeDados', $username, $password);
  $stmt = $conn->prepare('SELECT * FROM minhaTabela WHERE id = :id');
  $stmt->execute(array('id' => $id));

  $result = $stmt->fetchAll();

  if ( count($result) ) {
    foreach($result as $row) {
      print_r($row);
    }
  } else {
    echo "Nennhum resultado retornado.";
  }
} catch(PDOException $e) {
    echo 'ERROR: ' . $e->getMessage();
}

 ?>
<?php

$stmt->execute(array('id' => $id));

# Pega um array contendo todos os resultados
$result = $stmt->fetchAll();

# Se um ou mais resultados forem retornados...
if ( count($result) ) {
    foreach($result as $row) {
        print_r($row);
    }
} else {
    echo "Nenhum resultado retornado.";
}

 ?>
<?php
/*
 * Melhor prática usando Prepared Statements
 *
 */

$id = 5;
try {
    $conn = new PDO('mysql:host=localhost;dbname=meuBancoDeDados', $username, $password);
    $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

    $stmt = $conn->prepare('SELECT * FROM minhaTabela WHERE id = :id');
    $stmt->execute(array('id' => $id));

    while($row = $stmt->fetch()) {
        print_r($row);
    }
} catch(PDOException $e) {
    echo 'ERROR: ' . $e->getMessage();
}

 ?>
<?php
/*
 * Método de conexão sem padrões
 */

$name = 'Ricardo';

try {
    $conn = new PDO('mysql:host=localhost;dbname=meuBancoDeDados', $username, $password);
    $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

    $data = $conn->query('SELECT * FROM minhaTabela WHERE nome = ' . $conn->quote($name));

    foreach($data as $row) {
        print_r($row);
    }
} catch(PDOException $e) {
    echo 'ERROR: ' . $e->getMessage();
}

 ?>
<?php
try {
  $conn = new PDO('mysql:host=localhost;dbname=meuBancoDeDados', $username, $password);
    $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch(PDOException $e) {
    echo 'ERROR: ' . $e->getMessage();
}
?>
<?php
$conn = new PDO('mysql:host=localhost;dbname=meuBancoDeDados', $username, $password);
?>
<?php
$consulta = $pdo->query("SELECT nome, usuario FROM login;");


while ($linha = $consulta->fetch(PDO::FETCH_ASSOC)) {
    echo "Nome: {$linha['nome']} - Usuário: {$linha['usuario']}<br />";
}
?>
<?php
$id = 5;

try {
  $pdo = new PDO('mysql:host=localhost;dbname=meuBancoDeDados', $username, $password);
  $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

  $stmt = $pdo->prepare('DELETE FROM minhaTabela WHERE id = :id');
  $stmt->bindParam(':id', $id);
  $stmt->execute();

  echo $stmt->rowCount();
} catch(PDOException $e) {
  echo 'Error: ' . $e->getMessage();
}
?>
<?php
    $id = $_GET["id"];
    include_once 'conexao.php';

    $sql = "delete from cliente where idcliente = ".$id;

    if(mysql_query($sql,$con)){
        $msg = "Deletado com sucesso!";
    }else{
        $msg = "Erro ao deletar!";
    }
    mysql_close($con);

    ?>
<?php

$id = 5;
$nome = "Novo nome do Ricardo";

try {
  $pdo = new PDO('mysql:host=localhost;dbname=meuBancoDeDados', $username, $password);
  $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

  $stmt = $pdo->prepare('UPDATE minhaTabela SET nome = :nome WHERE id = :id');
  $stmt->execute(array(
    ':id'   => $id,
    ':nome' => $nome
  ));

  echo $stmt->rowCount();
} catch(PDOException $e) {
  echo 'Error: ' . $e->getMessage();
}
?>
<?php

    $nome = $_POST["nome"];
    $email = $_POST["email"];
    $tel = $_POST["tel"];
    $id = $_POST["id"];

    include_once 'conexao.php';

    $sql = "update cliente set
            nome = '".$nome."', email = '".$email."',telefone = '".$tel."'
            where idcliente = ".$id;

    if(mysql_query($sql,$con)){
        $msg = "Atualizado com sucesso!";
    }else{
        $msg = "Erro ao atualizar!";
    }
    mysql_close($con);

    ?>
<?php
try {
  $pdo = new PDO('mysql:host=localhost;dbname=meuBancoDeDados', $username, $password);
  $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

  $stmt = $pdo->prepare('INSERT INTO minhaTabela (nome) VALUES(:nome)');
  $stmt->execute(array(
    ':nome' => 'Ricardo Arrigoni'
  ));

  echo $stmt->rowCount();
} catch(PDOException $e) {
  echo 'Error: ' . $e->getMessage();

   ?>
<?php
    $nome = $_POST["nome"];
    $email = $_POST["email"];
    $tel = $_POST["tel"];

    include_once 'conexao.php';

    $sql = "insert into cliente values(null,
            '".$nome."','".$email."','".$tel."')";
    //echo $sql;

    if(mysql_query($sql,$con)){
        $msg = "Gravado com sucesso!";
    }else{
        $msg = "Erro ao gravar!";
    }
    mysql_close($con);
?>