Showing posts with label Wordpress. Show all posts
Showing posts with label Wordpress. Show all posts

Get contact form 7 submmitted data

function contactform7_before_send_mail( $submission ) {

    $submission = WPCF7_Submission::get_instance();
    if ( $submission ) {
        $formData = $submission->get_posted_data();
$uploaded_files = $submission->uploaded_files();     
    }
}

remove_all_filters ('wpcf7_before_send_mail');
add_action( 'wpcf7_before_send_mail', 'contactform7_before_send_mail' );

Get wordpress featured image

<?php
if (has_post_thumbnail( $post->ID ) ){
$image = wp_get_attachment_image_src( get_post_thumbnail_id( $post->ID ), 'full' );
?>
<img src="<?php echo $image[0]; ?>" alt="<?php echo $post->post_title; ?>" />
<?php
}else{
?>
<img src="<?php echo get_template_directory_uri(); ?>/images/banner/default-banner.jpg" alt="" />
<?php
}
?>


get featured image
 
if (has_post_thumbnail( $post->ID ) ){
   echo wp_get_attachment_image( get_post_thumbnail_id(), 'full');
}

Wordpress Spam Protection

6 ways to stop Contact Form 7 spam on WordPress websites
https://barn2.co.uk/stop-contact-form-7-spam/

Wordpress .htaccess

# BEGIN WordPress
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /wordpress/
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /wordpress/index.php [L]
</IfModule>

# END WordPress

# Block the include-only files.
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteRule ^wp-admin/includes/ - [F,L]
RewriteRule !^wp-includes/ - [S=3]
RewriteRule ^wp-includes/[^/]+\.php$ - [F,L]
RewriteRule ^wp-includes/js/tinymce/langs/.+\.php - [F,L]
RewriteRule ^wp-includes/theme-compat/ - [F,L]
</IfModule>

# STRONG HTACCESS PROTECTION</code>
<Files ~ "^.*\.([Hh][Tt][Aa])">
order allow,deny
deny from all
satisfy all
</Files>

# disable directory browsing
Options All -Indexes

# protect wp-config.php
<files wp-config.php>
Order deny,allow
Deny from all
</files>

# TN START ENABLE KEEP ALIVE
<ifModule mod_headers.c>
Header set Connection keep-alive
</ifModule>
# TN END ENABLE KEEP ALIVE

# protect from sql injection
Options +FollowSymLinks
RewriteEngine On
RewriteCond %{QUERY_STRING} (\<|%3C).*script.*(\>|%3E) [NC,OR]
RewriteCond %{QUERY_STRING} GLOBALS(=|\[|\%[0-9A-Z]{0,2}) [OR]
RewriteCond %{QUERY_STRING} _REQUEST(=|\[|\%[0-9A-Z]{0,2})
RewriteRule ^(.*)$ index.php [F,L]

WP-Content/Uploads

# Kill PHP Execution
<Files *.php>
deny from all
</Files>

Wordpress attachment html mail / wordpress mail

$to = get_option('career_email');
$subject = "Job Application";
$message ='<table>';
$message .= '<tr><td style="vertical-align:top;"><b>Name</b></td><td> : '.$_REQUEST['applicant_name']."</td></tr>";
$message .= '<tr><td style="vertical-align:top;"><b>Position</b></td><td> : '.$_REQUEST['apply_position']."</td></tr>";
$message .= '<tr><td style="vertical-align:top;"><b>Email</b></td><td> : '.$_REQUEST['email']."</td></tr>";
$message .= '<tr><td style="vertical-align:top;"><b>Phone</b></td><td> : '.$_REQUEST['phone']."</td></tr>";
$message .= '<tr><td style="vertical-align:top;"><b>Message</b></td><td> : '.$_REQUEST['message']."</td></tr>";       
$message .='</table>';

$headers = array('Content-Type: text/html; charset=UTF-8');
$headers[] = 'From: Bit Mascot - '.$_REQUEST['applicant_name'].' <'.$_REQUEST['email'].'>' . "\r\n";

if(isset($_REQUEST['cv']) && strlen($_REQUEST['cv'])>0) {
    $attachments = array(WP_CONTENT_DIR . '/' . $_REQUEST['cv']);
}else{
    $attachments = array();
}

wp_mail($to, $subject, $message, $headers, $attachments);

Portfolio

jQuery.noConflict();

jQuery(document).ready(function($){

    mixitupCall();
    
    function mixitupCall() {

        $('#portfolio').mixitup({
            targetSelector: '.item',
            transitionSpeed: 450,
            onMixLoad: function(state){
                changeRow(state);
            },
            onMixEnd: function(state){
                changeRow(state);
            }
        });
    }

    function changeRow(state) {
        var $per_row = 3;
        var $count = 0;
        var $row = 0;
        $(state.origOrder).each(function (key, value) {
            $current = $(this);
            $current.attr('class', $current.attr('class').replace(/row-.*/, ''));
            if($current.is(':visible')) {
                if($count % $per_row == 0){
                    $row++
                }
                $count++;
                $current.addClass('row-'+$row);
                $current.attr('rel', $row);
            }
        });
    }

    var portfolio_top = $('#header').height();

    $(".single-portfolio a").live('click', function (e) {
        e.preventDefault();

        var $single_portfolio = $(this).parent();
        var row = $single_portfolio.attr('rel');
        var post_id = $single_portfolio.attr('data-post_id');

        $(".portfolio-description").remove();

        data = {
            action:'portfolio',
            post_id: post_id        }

        $.ajax({
            method:"POST",
            url:ajax_url,
            data: data,
            success: function (response) {
                var html = '<div class="col-sm-12 portfolio-description" style="display: none">'+response+'</div>';

                $( ".row-"+row).last().after(html);
                $(".portfolio-description").slideDown("slow");

                if($(".our-work-section-portfolio .portfolio-description").length > 1){
                    $(".our-work-section-portfolio .portfolio-description").not(":last").remove();
                }

                customScrollTo(jQuery(".portfolio-description").offset().top - portfolio_top, 500)
            }
        });
    });


    $(".portfolio-close").live('click', function (e) {
        e.preventDefault();
        var post_id = $(this).attr('rel');
        customScrollTo(jQuery(".portfolio-"+post_id).offset().top - portfolio_top, 500);
        $(".portfolio-description").slideUp("slow", function () {
            $(".portfolio-description").remove();
        });
    });

    $('.portfolio-more').click(function () {
        
        var current_page = parseInt($(".current_page").val());
        current_page = current_page + 1;
        var total_page = parseInt($(".total_page").val());
        var item_per_page = $(".item_per_page").val();
        var start = (current_page - 1) * item_per_page;

        $.ajax({
            method : "POST",
            url : ajax_url,
            data : {
                action : 'more_work',
                current_page : current_page,
                limit : item_per_page,
                start : start            },
            success : function (response) {
                $("#portfolio").append(response);
                $(".current_page").val(current_page);
                mixitupCall();

                if(total_page <= current_page){
                    $('.portfolio-more').remove();
                }
            }
        })
    });
});

pre_get_posts


add_action('pre_get_posts','set_posts_argument');

function set_posts_argument( $query ) {
if ( ! is_admin() && is_post_type_archive('game')) {
$query->set('posts_per_page', 2);
}

if ( ! is_admin() && is_post_type_archive('device_game')) {

$query->set('posts_per_page', 500);

$user_agent= user_agent();

$meta_key = '';
if($user_agent=='android'){
$meta_key = 'android_link';
}elseif ($user_agent=='ios'){
$meta_key = 'ios_link';
}

if(!empty($meta_key)) {
$query->set('orderby', 'menu_order title');
$query->set('order', 'ASC');
$query->set('meta_query', array(
array(
'key' => $meta_key,
'value' => '',
'compare' => '!='
)
));
}
}
}

update wordpress loop

global $paged;global $wp_query;global $query_string;$wp_query->max_num_pages;$paged = (get_query_var('paged')) ? get_query_var('paged') : 1;query_posts($query_string.'&posts_per_page=2&orderby=menu_order title&order=ASC');

// Start the Loop.while ( have_posts() ) : the_post();

Exclude Taxonomy From WordPress Post Type

Paste Before If condition of while loop
query_posts( array(

    'post_type' =>'videos',

    'tax_query' => array(

        array(

            'taxonomy' => 'video_cats',

            'field'  => 'slug',

            'terms'  => array( 'adult' ),

            'operator' => 'NOT IN',

        ),

    )

) );

How can I remove unit tag from URL in contact form 7 plugin

add_filter('wpcf7_form_action_url', 'remove_unit_tag');

function remove_unit_tag($url){
    $remove_unit_tag = explode('#',$url);
    $new_url = $remove_unit_tag[0];
    return $new_url;
}

Remove emty p tag wordpress

function remove_empty_p( $content ) {
    $content = force_balance_tags( $content );
    $content = preg_replace( '#<p>\s*+(<br\s*/*>)?\s*</p>#i', '', $content );
    $content = preg_replace( '~\s?<p>(\s|&nbsp;)+</p>\s?~', '', $content );
    return $content;
}
add_filter('the_content', 'remove_empty_p', 20, 1);

Remove “Category:”, “Tag:”, “Author:” from the_archive_title

add_filter( 'get_the_archive_title', function ($title) {

   if (is_category()  ||  is_tax() ) {

      $title = single_cat_title( ' ', false );
   }elseif ( is_archive() ) {

      $title = single_month_title( ' ', false );
   } elseif ( is_tag() ) {

      $title = single_tag_title( ' ', false );
   } elseif ( is_author() ) {

      $title = '<span class="vcard">' . get_the_author() . '</span>' ;
   }

   return $title;
});

Additional field / custom field adding Programmatically in wordpress post

function __construct()
{
    add_action( 'add_meta_boxes', array( $this, 'add_meta_boxes' ), 30 );
    add_action('save_post', array($this, 'wpt_save_article_meta'), 1, 2); // save the custom fields
}

public function add_meta_boxes() {           
    add_meta_box( 'game-post', __('Game'), array( $this,'game_post_meta_box'), 'post', 'normal', 'low' );
}

function game_post_meta_box($post){

    $games = $this->getPostsByType('game');

    $game_id ='';
    if ( metadata_exists( 'post', $post->ID, 'game_id' ) ) {
        $game_id = get_post_meta( $post->ID, 'game_id', true );
    }

    if(!empty($games)){
        ?>
        <select name="game_id">
            <option value="">Please select game</option>
        <?php
        foreach ($games as $game){
            ?>
            <option value="<?php echo $game->ID; ?>" <?php if($game_id==$game->ID){ echo 'selected="selected"'; } ?>><?php echo $game->post_title; ?></option>
            <?php
        }
        ?>
        </select>
        <?php
    }   
}

public function wpt_save_article_meta($post_id, $post){

    // Is the user allowed to edit the post or page?
    if ( !current_user_can( 'edit_post', $post->ID ))
        return $post->ID;

    if(isset($_POST['game_id'])){
        $game_id = $_POST['game_id'];
        update_post_meta( $post_id, 'game_id', $game_id);
    }
}

Wordpress Useful Functions

get_page_by_path$page_path$output$post_type ); Click

if (has_post_thumbnail( $post->ID )){
    $image = wp_get_attachment_image_src(get_post_thumbnail_id($post->ID), 'full');
    $image_src = $image[0];
}


wp_nav_menu( array(
'theme_location' => 'primary',
'menu_class'     => 'primary-menu',

) );
Click Click

Get pagents and child page

Get immediate parent and child pages
<?php
if($post->post_parent)
    $children = wp_list_pages("title_li=&child_of=".$post->post_parent."&echo=0&sort_column=menu_order");
else
    $children = wp_list_pages("title_li=&child_of=".$post->ID."&echo=0&sort_column=menu_order");
if ($children) {
    $parent_title = get_the_title($post->post_parent);?>
    <li><a href="<?php echo get_permalink($post->post_parent) ?>"><?php echo $parent_title;?></a></li>
    <?php echo $children; ?>
<?php } ?>

Get top most parent id in worpdress
$parents = get_post_ancestors( $post->ID );
$get_top_parent_id = ($parents) ? $parents[count($parents)-1]: $post->ID;

Get all label parents or children pages

<?php
$parents = get_post_ancestors( $post->ID );
$get_top_parent_id = ($parents) ? $parents[count($parents)-1]: $post->ID;

$children = wp_list_pages("title_li=&child_of=".$get_top_parent_id."&echo=0&sort_column=menu_order");
if ($children) {
    $top_most_post = get_post($get_top_parent_id);
    $parent_selected = '';
    if($post->ID==$get_top_parent_id){
        $parent_selected = 'class="current_page_item"';
    }
    ?>
    <ul>
        <li <?php echo $parent_selected; ?>><a href="<?php echo get_permalink($top_most_post) ?>"><?php echo get_the_title($top_most_post);?></a></li>
        <?php echo $children; ?>
    </ul>
<?php } ?>

get pages by template

$pages = get_pages(array(
 'meta_key' => '_wp_page_template',
 'meta_value' => 'page-product.php'
));
foreach($pages as $page){
 echo $page->post_title.'<br />';
}
 
======================= 
$args = array(
    'post_type'  => 'page', 
    'meta_query' => array( 
        array(
            'key'   => '_wp_page_template', 
            'value' => 'my_template.php'
        )
    )
); 

Wordpress Taxonomy

Create taxonomy and custom post type

function taxonomy_init() {
    // create a new taxonomy

    register_taxonomy(
        'product_category',
        'product_post',
        array(
            'label' => __( 'Product categories' ),
            'singular_label' => 'Product Category',
            'hierarchical' => true,
            'query_var' => true,
            'rewrite' => array(
                'slug' => 'product-category'
            ),
        )
    );

    $args = array(
        'labels' => array(
            'name' => _x('Products', 'post type general name'),
            'singular_name' => _x('Product', 'post type singular name')
        ),
        'public' => true,
        'publicly_queryable' => true,
        'show_ui' => true,
        'query_var' => true,
        'capability_type' => 'post',
        'hierarchical' => false,
        'menu_position' => null,
        'supports' => array('title', 'editor', 'thumbnail', 'page-attributes'),
        'rewrite' => array(
            'slug' => 'product',
            'with_front' => false
        ),
        'has_archive' => 'products'
    );

    register_post_type('product_post', $args);
    flush_rewrite_rules();
}
add_action( 'init', 'taxonomy_init');

Custom Taxonomy Tree view
 <?php
//Walker function
function custom_taxonomy_walker($taxonomy, $parent = 0)
{
    $terms = get_terms($taxonomy, array('parent' => $parent, 'hide_empty' => false));
    //If there are terms, start displaying
    if(count($terms) > 0)
    {
        //Displaying as a list
        $out = "<ul>";
        //Cycle though the terms
        foreach ($terms as $term)
        {
            //Secret sauce.  Function calls itself to display child elements, if any
            $out .="<li>" . $term->name . custom_taxonomy_walker($taxonomy, $term->term_id) . "</li>";
        }
        $out .= "</ul>";  
        return $out;
    }
    return;
}

//Example
echo custom_taxonomy_walker('category');
?>


<?php
$args = array(
  'taxonomy'     => 'product-type',
  'hierarchical' => true,
  'title_li'     => '',
  'hide_empty'   => false
);
?>

<ul>
<?php wp_list_categories( $args ); ?>
</ul>

https://wordpress.org/plugins/advanced-custom-fields-categories/
https://wordpress.org/plugins/custom-taxonomy-order-ne/screenshots/

Wordpress Page Speed

Enable gzip compression
https://codex.wordpress.org/Output_Compression

Optimising Wordpress for Page Speed in 15 Minutes
https://www.youtube.com/watch?v=UpvuJxFc_8o

How to Remove WordPress Header Junk
https://github.com/cferdinandi/gmt-remove-header-junk
https://devcereal.com/remove-wordpress-header-junk/


leverage browser caching wordpress

# Expires Caching Start #
<IfModule mod_expires.c>
ExpiresActive On
ExpiresByType text/css "access 1 month"
ExpiresByType text/html "access 1 month"
ExpiresByType image/gif "access 1 year"
ExpiresByType image/png "access 1 year"
ExpiresByType image/jpg "access 1 year"
ExpiresByType image/jpeg "access 1 year"
ExpiresByType image/x-icon "access 1 year"
ExpiresByType application/pdf "access 1 month"
ExpiresByType application/javascript "access 1 month"
ExpiresByType text/x-javascript "access 1 month"
ExpiresByType application/x-shockwave-flash "access 1 month"
ExpiresDefault "access 1 month"
</IfModule>
# Expires Caching End #

Defer Parsing Javascript in WordPress 
// Defer Javascripts
// Defer jQuery Parsing using the HTML5 defer property
if (!(is_admin() )) {
    function defer_parsing_of_js ( $url ) {
        if ( FALSE === strpos( $url, '.js' ) ) return $url;
        if ( strpos( $url, 'jquery.js' ) ) return $url;
        // return "$url' defer ";
        return "$url' defer onload='";
    }
    add_filter( 'clean_url', 'defer_parsing_of_js', 11, 1 );
}

Wordpress plugins to increase site speed by 400%
https://www.youtube.com/watch?v=PQjGiXCs8IE&spfreload=5
https://wordpress.org/plugins/w3-total-cache/
Smush Image Compression and Optimization
https://wordpress.org/plugins/wp-smushit/
https://wordpress.org/plugins/wp-optimize/
https://wordpress.org/plugins/regenerate-thumbnails/ doc

Wordpress multisite

Create a network
http://codex.wordpress.org/Create_A_Network