Skip to content

Instantly share code, notes, and snippets.

@lizzies
Forked from josanua/wp-code-utils.php
Created February 20, 2022 16:47
Show Gist options
  • Save lizzies/0692e8d1e02e6bdd91228e5cbc5f1d11 to your computer and use it in GitHub Desktop.
Save lizzies/0692e8d1e02e6bdd91228e5cbc5f1d11 to your computer and use it in GitHub Desktop.
wp code utils
<?php
************ Debug, Debuging ************
//Activate log files in wp-config.php
define( 'WP_DEBUG', true ); // Enabling WP_DEBUG will cause all PHP errors, notices and warnings to be displayed.
define( 'WP_DEBUG_LOG', true ); // Enable Debug logging to the /wp-content/debug.log file
define( 'WP_DEBUG_DISPLAY', true ); // Controls whether debug messages are shown inside the HTML of pages or not.
// use this
define( 'WP_DEBUG', true );
define( 'WP_DEBUG_LOG', true );
define( 'WP_DEBUG_DISPLAY', false );
define( 'SMTP_DEBUG', 0 );
// Disable Cron
define('DISABLE_WP_CRON', true);
//Return a comma-separated string of functions that have been called to get to the current point in code.
var_dump( wp_debug_backtrace_summary());
// Increase memory limit
define('WP_MEMORY_LIMIT', '128M');
// Increase Maximum Upload File Size in WordPress
https://help.servmask.com/2018/10/27/how-to-increase-maximum-upload-file-size-in-wordpress/
// 1. Update .htaccess file
php_value upload_max_filesize 128
php_value post_max_size 128
php_value memory_limit 256
php_value max_execution_time 300
php_value max_input_time 300
// 2. Update wp-config.php file
@ini_set( 'upload_max_filesize' , '128M' );
@ini_set( 'post_max_size', '128M');
@ini_set( 'memory_limit', '256M' );
@ini_set( 'max_execution_time', '300' );
@ini_set( 'max_input_time', '300' );
Connect external file to WP
//Include the wp-load.php file
include('wp-load.php');
// Example to find path in external file
$parse_uri = explode( 'wp-content', $_SERVER['SCRIPT_FILENAME'] );
require_once( $parse_uri[0] . 'wp-load.php' );
// example
define("WP_ROOT", __DIR__);
define("DS", DIRECTORY_SEPARATOR);
echo WP_ROOT;
// Optional, adding the WP blog header which will include the wordpress head in the file
require('wp-blog-header.php');
// check if file connected, wp version
echo $wp_version;
WordPress Error class. - https://developer.wordpress.org/reference/classes/wp_error/
get_error_message();
get_error_code();
Cod pentru dezactivarea formatarii automate a codului html in redactor text.
// functions.php;
// De inclus la final de cod
remove_filter('the_content' , 'wpauto');
remove_filter('the_excerpt' , 'wpauto');
remove_filter('comment_text', 'wpauto');
Hook pentru a citi variabilele din admin
function dwwp(){
global $wp_admin_bar;
echo "<pre>";
// var_dump($wp_admin_bar);
print_r($wp_admin_bar);
echo "</pre>";
}
add_action('wp_before_admin_bar_render', 'dwwp');
//-------------- debug --------------//
// will load jQuery Migrate in debug mode, and output stack traces in your JavaScript developer console.
define( 'SCRIPT_DEBUG', true );
https://developer.wordpress.org/reference/functions/wp_mail/
// Function for send mails
wp_mail( string|array $to, string $subject, string $message, string|array $headers = '', string|array $attachments = array() )
add_action('phpmailer_init','send_smtp_email');
function send_smtp_email( $mail ) {
// Define that we are sending with SMTP
$mail->IsSMTP();
$mail->CharSet = 'UTF-8';
$mail->Host = 'mail.servername.com';
$mail->Port = '587';//'465';
$mail->SMTPAuth = true;//true;
$mail->Username = "";
$mail->Password = "";
$mail->SMTPSecure = "tls";
$mail->IsHTML(true);
}
// Send HTML Content
function claim_location_send_mail(){
global $post;
function wpdocs_set_html_mail_content_type() {
return 'text/html';
}
add_filter( 'wp_mail_content_type', 'wpdocs_set_html_mail_content_type' );
$to = get_option('admin_email');
$subject = 'Claim location notification';
$body = 'User Claim Location Event: <a href=' . get_permalink( $post->ID ) . '>' . $post->post_title . '</a>';
wp_mail( $to, $subject, $body );
// Reset content-type to avoid conflicts -- https://core.trac.wordpress.org/ticket/23578
remove_filter( 'wp_mail_content_type', 'wpdocs_set_html_mail_content_type' );
}
// Setup SMTP
add_action('phpmailer_init','send_smtp_email');
function send_smtp_email( $phpmailer )
{
// Define that we are sending with SMTP
$phpmailer->isSMTP();
// The hostname of the mail server
$phpmailer->Host = "your server smtp address";
// Use SMTP authentication (true|false)
$phpmailer->SMTPAuth = true;
// SMTP port number - likely to be 25, 465 or 587
$phpmailer->Port = "587";
// Username to use for SMTP authentication
$phpmailer->Username = "user name";
// Password to use for SMTP authentication
$phpmailer->Password = "password";
// The encryption system to use - ssl (deprecated) or tls
$phpmailer->SMTPSecure = "tls";
$phpmailer->From = "Mail account";
$phpmailer->FromName = "Name account";
}
// example of a basic error logging:
add_action('wp_mail_failed', 'log_mailer_errors', 10, 1);
function log_mailer_errors( $wp_error ){
$fn = $_SERVER['DOCUMENT_ROOT'] . '/mail.log'; // say you've got a mail.log file in your server root
$fp = fopen($fn, 'a');
fputs($fp, "Mailer Error: " . $wp_error->get_error_message() ."\n");
fclose($fp);
}
// put this in functions.php
// define the wp_mail_failed callback
function action_wp_mail_failed($wp_error)
{
return error_log(print_r($wp_error, true));
}
// add the action
add_action('wp_mail_failed', 'action_wp_mail_failed', 10, 1);
// send HTML mail, change mail headers
https://wordpress.stackexchange.com/questions/27856/is-there-a-way-to-send-html-formatted-emails-with-wordpress-wp-mail-function
$headers = array('Content-Type: text/html; charset=UTF-8');
wp_mail( $to, $subject, $body, $headers );
//-------------- Header Social OG setup --------------//
// Codes and plugin
https://premium.wpmudev.org/blog/wordpress-open-graph/
// Description
https://www.addthis.com/academy/open-graph-tags-in-wordpress/
//-------------- Comments --------------//
// Dissable comments feature
// First, this will disable support for comments and trackbacks in post types
function df_disable_comments_post_types_support() {
$post_types = get_post_types();
foreach ($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');
}
}
}
add_action('admin_init', 'df_disable_comments_post_types_support');
// Then close any comments open comments on the front-end just in case
function df_disable_comments_status() {
return false;
}
add_filter('comments_open', 'df_disable_comments_status', 20, 2);
add_filter('pings_open', 'df_disable_comments_status', 20, 2);
// Finally, hide any existing comments that are on the site.
function df_disable_comments_hide_existing_comments($comments) {
$comments = array();
return $comments;
}
add_filter('comments_array', 'df_disable_comments_hide_existing_comments', 10, 2);
//-------------- AJAX --------------//
https://wp-kama.ru/id_2018/ajax-v-wordpress.html
https://codex.wordpress.org/AJAX
// Needed hooks
add_action('wp_ajax_(action)', 'my_action_callback');
add_action('wp_ajax_nopriv_(action)', 'my_action_callback'); // for unregistered users
// Recommended way
if( wp_doing_ajax() ){
add_action('wp_ajax_(action)', 'my_action_callback');
add_action('wp_ajax_nopriv_(action)', 'my_action_callback'); // for unregistered users
}
// For include JS script with defined variable AJAX Path
wp_localize_script( $handle, $object_name, $l10n );
https://wp-kama.ru/id_2018/ajax-v-wordpress.html
add_action( 'wp_enqueue_scripts', 'myajax_data', 99 );
function myajax_data(){
// Первый параметр 'twentyfifteen-script' означает, что код будет прикреплен к скрипту с ID 'twentyfifteen-script'
// 'twentyfifteen-script' должен быть добавлен в очередь на вывод, иначе WP не поймет куда вставлять код локализации
// Заметка: обычно этот код нужно добавлять в functions.php в том месте где подключаются скрипты, после указанного скрипта
wp_localize_script( 'twentyfifteen-script', 'myajax',
array(
'url' => admin_url('admin-ajax.php')
)
);
}
// example
// --- Front Part --- //
add_action('wp_ajax_front', 'front_action_call');
add_action('wp_ajax_nopriv_front', 'front_action_call'); // for unregistered users
function front_action_call(){
echo 'S-a primit';
wp_die();
}
add_action( 'wp_enqueue_scripts', 'myajax_data', 99 );
function myajax_data(){
wp_localize_script( 'jquery', 'myajax',
array(
'url' => admin_url('admin-ajax.php')
)
);
}
add_action('wp_footer', 'front_action_javascript', 99);
function front_action_javascript() {
?>
<script>
jQuery(document).ready(function($) {
var data = {
action: 'front'
// whatever: 1234
};
jQuery.post( myajax, data, function(response) {
console.log('Server Response from Front Page: ' + response)
});
});
</script>
<?php }
// AJAX debug, ajax security
// Connect function to view AJAX errors,
if( WP_DEBUG && WP_DEBUG_DISPLAY && (defined('DOING_AJAX') && DOING_AJAX) ){
@ ini_set( 'display_errors', 1 );
}
// Error log file
error_log( print_r($myvar, true) );
//-------------- Widget --------------//
//Widget, display post by ID
class Show_Contacts extends WP_Widget{
//setup the widget name, description, etc...
public function __construct(){
$widget_ops = array(
'classname' => 'show_contacts_widget',
'description' => 'Show Contacts Widget',
);
parent::__construct( 'show_contacts', 'Show Contacts', $widget_ops );
}
function widget( $args, $instance ) {
// Widget output
// echo "Widget plugin";
$post = get_post(372);
print_r($post);
// echo $post[post_title];
echo $post->post_title;
echo $post->post_type;
echo $post->post_content;
}
}
add_action( 'widgets_init', function(){
register_widget( 'Show_Contacts' );
});
//-------------- Add setting option in "Settings General" panel --------------//
//******* Plugins *******//
//CF7, contact form 7
// [contact-form-7 id="1135" title="Contact form 1" html_class="form-inline"] add class name (html_class="form-inline")
// Disable Auto <p> tag and others https://contactform7.com/controlling-behavior-by-setting-constants/
// add_filter( 'wpcf7_autop_or_not', '__return_false' ); also disable tag p
// .wpcf7 general class tu apply for custom elements
// CF 7 Settigns
define('WPCF7_AUTOP', false);
// If CF7 shortoce dosn't work in widgets
add_filter( 'widget_text', 'wpcf7_widget_text_filter', 9 );
function wpcf7_widget_text_filter( $content ) {
$pattern = '/\[[\r\n\t ]*contact-form(-7)?[\r\n\t ].*?\]/';
if ( ! preg_match( $pattern, $content ) ) {
return $content;
}
$content = do_shortcode( $content );
return $content;
}
// stop spam filtering
add_filter('wpcf7_spam', function() { return false; });
// get form ID
// this solution
$wpcf7 = WPCF7_ContactForm::get_current();
$form_id = $wpcf7->id;
// or this, works both
$form_id = $_POST['_wpcf7'];
// Problem with pipes
https://wordpress.org/support/topic/contact-form-7-pipes-not-working-3/
<script>
$(document).ready(function()
{
//Change form with pipes class text & values
$('.wpcf7-pipes .wpcf7-form .wpcf7-select option').each(function(index,element) {
//split element text by "|" divider
var data = element.text.split('|');
//replace text and value of option
$(this).val(data[0]);
$(this).text(data[1]);
});
});
</script>
// CF7 DOM events
https://contactform7.com/dom-events/
document.addEventListener( 'wpcf7submit', function( event ) {
console.log(event.detail.contactFormId);
}, false );
// CF7 check for existing emails, check existing emails
add_filter('wpcf7_validate', 'email_already_in_db', 10, 2);
function email_already_in_db($result, $tags)
{
// retrieve the posted email
$form = WPCF7_Submission::get_instance();
$email = $form->get_posted_data('your-email');
global $wpdb;
$table_name = $wpdb->prefix . 'contactic_submits';
$result_search_query = $wpdb->query(" SELECT * FROM " . $table_name . " WHERE field_value LIKE '{$email}'");
if ($result_search_query != 0) {
$result->invalidate('your-email', __('Your email exists in our database', 'starcard'));
}
return $result;
}
// cf7 popup
// https://stackoverflow.com/questions/50406269/how-to-open-a-popup-after-the-contact-form-7-succesfully-submitted
add_action('wpcf7_mail_sent', function () {
// Run code after the email has been sent
$wpcf = WPCF7_ContactForm::get_current();
$wpccfid=$wpcf->id;
// if you wanna check the ID of the Form $wpcf->id
if ( '34' == $wpccfid ) { // Change 123 to the ID of the form
echo '
<div class="modal fade in formids" id="myModal2" role="dialog" style="display:block;" tabindex="-1">
<div class="modal-dialog">
<!-- Modal content-->
<div class="modal-content no_pad text-center">
<button type="button" class="close" data-dismiss="modal">&times;</button>
<div class="modal-header heading">
<h3 class="modal-title">Message Sent!</b></h3>
</div>
<div class="modal-body">
<div class="thanku_outer define_float text-center">
<h3>Thank you for getting in touch!</h3>
</div>
</div>
<div class="modal-footer">
</div>
</div>
</div>
</div>
';
}
});
// debug cf7
https://stackoverflow.com/questions/60361457/trying-to-get-contact-form-7-post-data-to-debug-to-screen
// save data in log file
add_action( 'wpcf7_before_send_mail', 'my_process_cf7_form_data' );
function my_process_cf7_form_data() {
$submission = WPCF7_Submission::get_instance();
if ( $submission ) {
$posted_data = $submission->get_posted_data();
}
ob_start();
var_dump($posted_data);
error_log(ob_get_clean());
}
// Additional Settings
// https://contactform7.com/additional-settings/
skip_mail: on
demo_mode: on
// Js code for popup messages
// CF7 custom code
document.addEventListener( 'wpcf7mailsent', function( event ) {
// console.log(event.detail.contactFormId);
// let fstatus = event.detail.apiResponse.status;
let fmessage = event.detail.apiResponse.message;
$('#cf7_Message_Modal').modal(focus);
$('#cf7_Message_Modal_text').text(fmessage);
})
// take cf7 text response, contact form 7 text response, validation statuses
document.addEventListener( 'wpcf7submit', function( event ) {
// console.log(event.detail.contactFormId);
// console.log(event.detail.apiResponse.status);
// console.log(event.detail.apiResponse.message);
let fstatus = event.detail.apiResponse.status;
let fmessage = event.detail.apiResponse.message;
// error type messages
if ((fstatus === 'validation_failed' || fstatus === 'acceptance_missing' ||
fstatus === 'spam' || fstatus === 'aborted' || fstatus === 'mail_failed')) {
// console.log(fstatus);
// console.log(fmessage);
$('#cf7_Message_Modal').modal(focus);
$('#cf7_Message_Modal_text').text(fmessage);
}
})
// disable configuration validator:
define( 'WPCF7_VALIDATE_CONFIGURATION', false );
add_filter( 'wpcf7_validate_configuration', '__return_false' );
// disable spam filter
add_filter('wpcf7_spam', function() { return false; });
// disable some CF7 filters
// http://hookr.io/plugins/contact-form-7/4.7/hooks/#index=l
remove_filter( 'wpcf7_validate', 'filter_wpcf7_validate', 10, 2 );
remove_filter( 'wpcf7_validate_configuration', 'filter_wpcf7_validate_configuration', 10, 1 );
remove_filter( 'wpcf7_spam', 'filter_wpcf7_spam', 10, 1 );
//*** ACF ***//
// get field values quantity
count(get_field('field_name'));
// ACF Maps problem in Dasboard
https://support.advancedcustomfields.com/forums/topic/google-map-not-displaying-on-wp-backend/
//-------------- Localization --------------//
//qTranslate
//Detect page language
//https://qtranslatexteam.wordpress.com/interface/
qtranxf_getLanguage();
qtranxf_getLanguageName();
/* Disable Theme Editor */
function remove_editor_menu() {
remove_action('admin_menu', '_add_themes_utility_last', 101);
}
add_action('_admin_menu', 'remove_editor_menu', 1);
// My Codes
// Filter wordpress query by checkboxes, select post type by checkbox
if($checkboxone == '1') {
$types = array( 'typeone' )
}
if($checkboxtwo == '1') {
$types = array( 'typetwo' )
}
if($checkboxtwo == '1' && $checkboxone == '1'){
$types = array( 'typeone', 'typetwo' )
}
// The Query
$the_query = new WP_Query( array( 'post_type' => $types );
// The Loop
while ( $the_query->have_posts() ) : $the_query->the_post();
//DO STUFF
endwhile;
// Reset Post Data
wp_reset_postdata();
/**
* Display the Most Recent Post in Each Category
**
//https://code.tutsplus.com/tutorials/display-the-most-recent-post-in-each-category--cms-22677
// Trebuie de scris codul de la garantie.md
//How to Display Random Posts from Different Categories using WP_Query
?>
/**
* Show Thumbnails
**
<?php if( has_post_thumbnail()) : ?>
<a href="<?php the_permalink(); ?>"><?php the_post_thumbnail('thumbnail', array( 'class' => 'img-responsive'));?></a>
<?php endif; ?>
?>
/*
* Contact Form 7 Custom Form Tag for get current URL
*/
site https://contactform7.com/2015/01/10/adding-a-custom-form-tag/
site https://wordpress.stackexchange.com/questions/291855/how-to-get-current-url-in-contact-form-7
wpcf7_add_form_tag('pageurl', 'wpcf7_sourceurl_shortcode_handler', true);
function wpcf7_sourceurl_shortcode_handler($tag) {
if (!is_object($tag)) return '';
$name = $tag->name;
if (empty($name)) return '';
$html = '<input type="hidden" name="' . $name . '" value="http://' . $_SERVER["SERVER_NAME"].$_SERVER["REQUEST_URI"] . '" />';
return $html;
}
// put this [pageurl url] in CF7 form editor
// Java script CF7 form, select page after submit
<script>
jQuery(document).ready(function() {
document.addEventListener( 'wpcf7submit', function( event ) {
inputs = event.detail.inputs;
inputs.forEach( function(el) {
if ( el.name == 'tip-persoana' ) {
if ( el.value == 'Persoană Fizică' || el.value == 'Физическое лицо' || el.value == 'Individual' ) {
location.href = '<?= home_url() ?>/thank-you-fizica/';
} else if ( el.value == 'Persoană Juridică' || el.value == 'Юридическое лицо' || el.value == 'Entity' ) {
location.href = '<?= home_url() ?>/thank-you-juridica/';
}
}
});
}, false );
});
</script>
// CF7 detect if page sxcripts are loaded and read values
<script type="text/javascript">
window.addEventListener("load", function(event) {
$j(".wpcf7-submit").click(function(){
var post_title_cf7 = $j(".entry-title").text();
$j("#hidden-post-name-input").val(post_title_cf7);
});
});
</script>
// Excerpt from Advanced Custom Field, ACF
//Add this code in your functions.php
function advanced_custom_field_excerpt() {
global $post;
$text = get_field('your_field_name');
if ( '' != $text ) {
$text = strip_shortcodes( $text );
$text = apply_filters('the_content', $text);
$text = str_replace(']]>', ']]>', $text);
$excerpt_length =30; // 30 words
$excerpt_more = apply_filters('excerpt_more', ' ' . '[...]');
$text = wp_trim_words( $text, $excerpt_length, $excerpt_more );
}
return apply_filters('the_excerpt', $text);
}
//Add this line in your template
<?php echo advanced_custom_field_excerpt(); ?>
<?php
/*
* WordPress Code Tweaks
*/
/****** Theme Utils Dashboard ******/
https://codeable.io/wordpress-hacks-without-plugins/
//Change the login logo with yours
function my_custom_login_logo() {
echo '<style type="text/css">
h1 a { background-image:url('.get_bloginfo('template_directory').'/images/custom-login-logo.gif) !important; }
</style>';
}
add_action('login_head', 'my_custom_login_logo');
// Change the admin logo
function custom_admin_logo() {
echo '<style type="text/css">
#header-logo { background-image: url('.get_bloginfo('template_directory').'/images/admin_logo.png) !important; }
</style>';
}
add_action('admin_head', 'custom_admin_logo');
// Disable WordPress Login Hints
function no_wordpress_errors(){
return 'GET OFF MY LAWN !! RIGHT NOW !!';
}
add_filter( 'login_errors', 'no_wordpress_errors' );
// Keep logged in WordPress for a longer period
add_filter( 'auth_cookie_expiration', 'stay_logged_in_for_1_year' );
function stay_logged_in_for_1_year( $expire ) {
return 31556926; // 1 year in seconds
}
// Replace "Howdy" with "Logged in as" in WordPress bar
function replace_howdy( $wp_admin_bar ) {
$my_account=$wp_admin_bar->get_node('my-account');
$newtitle = str_replace( 'Howdy,', 'Logged in as', $my_account->title );
$wp_admin_bar->add_node( array(
'id' => 'my-account',
'title' => $newtitle,
) );
}
add_filter( 'admin_bar_menu', 'replace_howdy', 25 );
// Change the footer text on WordPress dashboard
function remove_footer_admin () {
echo "Your own text";
}
add_filter('admin_footer_text', 'remove_footer_admin');
/**
* WordPress function for redirecting users on login based on user role, redirect login,
*/
https://wpscholar.com/blog/wordpress-user-login-redirect/
function my_login_redirect( $url, $request, $user ){
if( $user && is_object( $user ) && is_a( $user, 'WP_User' ) ) {
if( $user->has_cap( 'administrator' ) ) {
$url = admin_url();
} else {
$url = home_url('/members-only/');
}
}
return $url;
}
add_filter('login_redirect', 'my_login_redirect', 10, 3 );
/****** Posts and Pages ******/
// Require a featured image before you can publish posts
add_action('save_post', 'wpds_check_thumbnail');
add_action('admin_notices', 'wpds_thumbnail_error');
function wpds_check_thumbnail( $post_id ) {
// change to any custom post type
if( get_post_type($post_id) != 'post' )
return;
if ( ! has_post_thumbnail( $post_id ) ) {
// set a transient to show the users an admin message
set_transient( "has_post_thumbnail", "no" );
// unhook this function so it doesn't loop infinitely
remove_action('save_post', 'wpds_check_thumbnail');
// update the post set it to draft
wp_update_post(array('ID' => $post_id, 'post_status' => 'draft'));
add_action('save_post', 'wpds_check_thumbnail');
} else {
delete_transient( "has_post_thumbnail" );
}
}
function wpds_thumbnail_error() {
// check if the transient is set, and display the error message
if ( get_transient( "has_post_thumbnail" ) == "no" ) {
echo "<div id='message' class='error'><p><strong>You must add a Featured Image before publishing this. Don't panic, your post is saved.</strong></p></div>";
delete_transient( "has_post_thumbnail" );
}
}
// Reduce Post Revisions
define( 'WP_POST_REVISIONS', 3 );
// Delay posting to my RSS feeds for 60 minutes
function Delay_RSS_After_Publish($where) {
global $wpdb;
if (is_feed()) {
$now = gmdate('Y-m-d H:i:s');
$wait = '60';
$device = 'MINUTE';
$where.=" AND TIMESTAMPDIFF($device, $wpdb->posts.post_date_gmt, '$now') > $wait ";
}
return $where;
}
add_filter('posts_where', 'Delay_RSS_After_Publish');
// Change the length of excerpts
function custom_excerpt_length( $length ) {
return 20;
}
add_filter( 'excerpt_length', 'custom_excerpt_length', 999 );
// Change the post auto-save interval
define( 'AUTOSAVE_INTERVAL', 45 );
/****** Widgets ******/
// Add a shortcode to widget
add_filter('widget_text', 'do_shortcode');
/****** Search ******/
//Show the number of results found
<h2 class="pagetitle">Search Result for <?php /* Search Count */ $allsearch = &new WP_Query("s=$s&showposts=-1"); $key = wp_specialchars($s, 1); $count = $allsearch->post_count; _e(''); _e('<span class="search-terms">'); echo $key; _e('</span>'); _e(' — '); echo $count . ' '; _e('articles'); wp_reset_query(); ?></h2>
// Exclude categories from search
function SearchFilter($query) {
if ( $query->is_search && ! is_admin() ) {
$query->set('cat','8,15');
}
return $query;
}
add_filter('pre_get_posts','SearchFilter');
// Exclude pages from search
function modify_search_filter($query) {
if ($query->is_search) {
$query->set('post_type', 'post');
}
return $query;
}
add_filter('pre_get_posts','modify_search_filter');
// SMTP
add_action( 'phpmailer_init', 'send_smtp_email' );
function send_smtp_email( $phpmailer ) {
$phpmailer->isSMTP();
$phpmailer->Host = SMTP_HOST;
$phpmailer->SMTPAuth = SMTP_AUTH;
$phpmailer->Port = SMTP_PORT;
$phpmailer->Username = SMTP_USER;
$phpmailer->Password = SMTP_PASS;
$phpmailer->SMTPSecure = SMTP_SECURE;
$phpmailer->From = SMTP_FROM;
$phpmailer->FromName = SMTP_NAME;
}
// Define in wp-config
define('SMTP_USER','mail@example.com'); // Username to use for SMTP authentication
define('SMTP_PASS', '############'); // Password to use for SMTP authentication
define('SMTP_HOST', 'mail.host.com'); // The hostname of the mail server
define('SMTP_FROM', 'mail@example.com'); // SMTP From email address
define('SMTP_NAME', 'Example'); // SMTP From name
define('SMTP_PORT', '587'); // SMTP port number - likely to be 25, 465 or 587
define('SMTP_SECURE', 'tls'); // Encryption system to use - ssl or tls
define('SMTP_AUTH', true); // Use SMTP authentication (true|false)
define('SMTP_DEBUG', 0); // for debugging purposes only set to 1 or 2
/**
* Solved problems
*/
/**
* Reset posts counts only for current users, reset counts
*/
if( 'edit.php' == $pagenow || $query->is_admin ) {
$user_role_name = wp_get_current_user()->roles[0];
if ( $user_role_name == "free" || $user_role_name == "featured"
|| $user_role_name == "social" || $user_role_name == "marketing" || $user_role_name == "paid" ){
$count_publish = $count_pending = $count_draft = $count_trash = 0;
$user_id = get_current_user_id();
$loop_publish = new WP_Query( array( 'post_type' => 'laundries', 'author' => $user_id, 'post_status' => 'publish' ) );
$loop_pending = new WP_Query( array( 'post_type' => 'laundries', 'author' => $user_id, 'post_status' => 'pending' ) );
$loop_draft = new WP_Query( array( 'post_type' => 'laundries', 'author' => $user_id, 'post_status' => 'draft' ) );
$loop_trash = new WP_Query( array( 'post_type' => 'laundries', 'author' => $user_id, 'post_status' => 'trash' ) );
while ( $loop_publish->have_posts() ) : $loop_publish->the_post();
$count_publish++;
endwhile;
while ( $loop_pending->have_posts() ) : $loop_pending->the_post();
$count_pending++;
endwhile;
while ( $loop_draft->have_posts() ) : $loop_draft->the_post();
$count_draft++;
endwhile;
while ( $loop_trash->have_posts() ) : $loop_trash->the_post();
$count_trash++;
endwhile;
add_action('admin_print_scripts', 'la_hook_javascript', 99);
function la_hook_javascript(){
global $count_publish, $count_draft, $count_pending, $count_trash;
?>
<script>
jQuery(document).ready(function($){
$(".publish .count").text("<?php echo "(" . $count_publish . ")" ; ?>");
$(".draft .count").text("<?php echo "(" . $count_draft. ")" ; ?>");
$(".pending .count").text("<?php echo "(" . $count_pending . ")" ; ?>");
$(".trash .count").text("<?php echo "(" . $count_trash . ")" ; ?>");
});
</script>
<?php }
}
}
/****** woocommerce ******/
// Delete all data then uninstall wc, remove data
define( 'WC_REMOVE_ALL_DATA', true);
// checkout page
// creating a Redirect to thank you page
https://www.tychesoftwares.com/how-to-customize-the-woocommerce-thank-you-page/
add_action( 'template_redirect', 'woo_custom_redirect_after_purchase' );
function woo_custom_redirect_after_purchase() {
global $wp;
if ( is_checkout() && !empty( $wp->query_vars['order-received'] ) ) {
wp_redirect( 'http://localhost:8888/woocommerce/custom-thank-you/' );
exit;
}
}
// Changing the text before order information
add_filter('woocommerce_thankyou_order_received_text', 'woo_change_order_received_text', 10, 2 );
function woo_change_order_received_text( $str, $order ) {
$new_str = $str . ' We have emailed the purchase receipt to you.';
return $new_str;
}
// Cart shop select product quantity
add_filter( 'woocommerce_quantity_input_args', 'bloomer_woocommerce_quantity_changes', 10, 2 );
function bloomer_woocommerce_quantity_changes( $args, $product ) {
if ( ! is_cart() ) {
$args['input_value'] = 1; // Start from this value (default = 1)
$args['max_value'] = 10; // Max quantity (default = -1)
$args['min_value'] = 1; // Min quantity (default = 0)
$args['step'] = 1; // Increment/decrement by this value (default = 1)
} else {
// Cart's "min_value" is already 0 and we don't need "input_value"
$args['max_value'] = 10; // Max quantity (default = -1)
$args['step'] = 1; // Increment/decrement by this value (default = 0)
// ONLY ADD FOLLOWING IF STEP < MIN_VALUE
$args['min_value'] = 1; // Min quantity (default = 0)
}
return $args;
}
/**
* dissallow comments
*/
https://gist.github.com/mattclements/eab5ef656b2f946c4bfb
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);
}
});
//Remove emoji
remove_action( 'wp_head', 'print_emoji_detection_script', 7 );
remove_action( 'wp_print_styles', 'print_emoji_styles' );
/**
* Multilanguage, i18n
*/
// get current language from wpml
https://wpml.org/forums/topic/get-current-language-2/
echo ICL_LANGUAGE_CODE;
<?php if (ICL_LANGUAGE_CODE == 'ro') : ?>
<p>Stoc epuizat!<br/>lasă-ne datele tale de contact, iar noi vom lua legătura cu tine pentru o alta ofertă</p>
<?php else: ?>
<p>Все продано!<br/>Оставь нам свои данные, и мы предложим тебе новую оферту.</p>
<?php endif; ?>
// Display WPML's drop-down language switcher
https://wpml.org/wpml-hook/wpml_add_language_selector/
<?php do_action('wpml_add_language_selector'); ?>
// WPML Language Switcher Custom Menu
add_action('dp_wpml_language_selector', 'my_custom_language_switcher');
function my_custom_language_switcher()
{
$languages = apply_filters('wpml_active_languages', NULL, array('skip_missing' => 0));
if (!empty($languages)) {
foreach ($languages as $language) {
$native_name = strtoupper( mb_substr($language['native_name'], 0, 2, 'UTF-8'));
// $native_name = $language['language_code'];
$active_class = $language['active'] ? $active_class = " active" : $active_class = '';
echo '<a class="header_lang_item js-change-lang'. $active_class .'" href="'. $language['url'] .'">'. $native_name .'</a>';
}
}
}
/****** optimization ******/
//Remove emoji
remove_action( 'wp_head', 'print_emoji_detection_script', 7 );
remove_action( 'wp_print_styles', 'print_emoji_styles' );
//-------------- Text editing, functions php, utils --------------//
// Function to activate Paste As Text By Default, paste text, paste clear formatting text
https://anythinggraphic.net/paste-as-text-by-default-in-wordpress/
add_filter('tiny_mce_before_init', 'ag_tinymce_paste_as_text');
function ag_tinymce_paste_as_text( $init ) {
$init['paste_as_text'] = true;
return $init;
}
// Get users published posts numbers
function getNbrPostsByUser($current_user_id){
global $wpdb;
$nbrPost = $wpdb->get_var( $wpdb->prepare(
"
SELECT COUNT(*)
FROM $wpdb->posts
WHERE post_type = %s AND post_author = %d AND post_status = 'publish'
",
'laundries',
$current_user_id
));
return $nbrPost;
}
//-------------- $post, post object, wp_post --------------//
https://codex.wordpress.org/Class_Reference/WP_Post
ID int The ID of the post
post_author string The post author's user ID (numeric string)
post_name string The post's slug
post_type s tring See Post Types
post_title string The title of the post
post_date string Format: 0000-00-00 00:00:00
post_date_gmt string Format: 0000-00-00 00:00:00
post_content string The full content of the post
post_excerpt string User-defined post excerpt
post_status string See get_post_status for values
comment_status string Returns: { open, closed }
ping_status string Returns: { open, closed }
post_password string Returns empty string if no password
post_parent int Parent Post ID (default 0)
post_modified string Format: 0000-00-00 00:00:00
post_modified_gmt string Format: 0000-00-00 00:00:00
comment_count string Number of comments on post (numeric string)
menu_order string Order value as set through page-attribute when enabled (numeric string. Defaults to 0)
// Filter content, add rel="lightbox" to link, add tag properties.
add_filter('the_content', 'my_addlightboxrel');
function my_addlightboxrel($content) {
global $post;
$pattern ="/<a(.*?)href=('|\")(.*?).(bmp|gif|jpeg|jpg|png)('|\")(.*?)>/i";
$replacement = '<a$1href=$2$3.$4$5 rel="lightbox" title="'.$post->post_title.'"$6>';
$content = preg_replace($pattern, $replacement, $content);
return $content;
}
/****** Connect SSL, Enable SSL ******/
https://www.wpbeginner.com/wp-tutorials/how-to-add-ssl-and-https-in-wordpress/
define('FORCE_SSL_ADMIN', true);
//-------------- post counter, show post counter, post views --------------//
https://www.isitwp.com/track-post-views-without-a-plugin-using-post-meta/
function getPostViews($postID){
$count_key = 'post_views_count';
$count = get_post_meta($postID, $count_key, true);
if($count==''){
delete_post_meta($postID, $count_key);
add_post_meta($postID, $count_key, '0');
return "0 View";
}
return $count.' Views';
}
function setPostViews($postID) {
$count_key = 'post_views_count';
$count = get_post_meta($postID, $count_key, true);
if($count==''){
$count = 0;
delete_post_meta($postID, $count_key);
add_post_meta($postID, $count_key, '0');
}else{
$count++;
update_post_meta($postID, $count_key, $count);
}
}
// Remove issues with prefetching adding extra views
remove_action( 'wp_head', 'adjacent_posts_rel_link_wp_head', 10, 0);
// This part of the tracking views code will set the post views.
setPostViews(get_the_ID());
// Use this code if you would like to display the number of views
echo getPostViews(get_the_ID());
// Add to a column in WP-Admin
add_filter('manage_posts_columns', 'posts_column_views');
add_action('manage_posts_custom_column', 'posts_custom_column_views',5,2);
function posts_column_views($defaults){
$defaults['post_views'] = __('Views');
return $defaults;
}
function posts_custom_column_views($column_name, $id){
if($column_name === 'post_views'){
echo getPostViews(get_the_ID());
}
}
// Custom Code featured image thumbnails in WordPress RSS Feeds, rss feed images
https://woorkup.com/show-featured-image-wordpress-rss-feed/#testing-your-rss-feed
function wplogout_post_thumbnails_in_feeds( $content ) {
global $post;
if( has_post_thumbnail( $post->ID ) ) {
$content = '<p>' . get_the_post_thumbnail( $post->ID ) . '</p>' . $content;
}
return $content;
}
add_filter( 'the_excerpt_rss', 'wplogout_post_thumbnails_in_feeds' );
add_filter( 'the_content_feed', 'wplogout_post_thumbnails_in_feeds' );
// responsive youtube issue, gutenberg editor
add_theme_support( 'responsive-embeds' );
/**
* Disable Fullscreen Gutenberg., disable gutenberg, disable guttenberg full screen
*/
add_action( 'enqueue_block_editor_assets', 'wpdd_disable_editor_fullscreen_by_default' );
function wpdd_disable_editor_fullscreen_by_default() {
$script = "window.onload = function() { const isFullscreenMode = wp.data.select( 'core/edit-post' ).isFeatureActive( 'fullscreenMode' ); if ( isFullscreenMode ) { wp.data.dispatch( 'core/edit-post' ).toggleFeature( 'fullscreenMode' ); } }";
wp_add_inline_script( 'wp-blocks', $script );
}
/**
* repair errors
*/
// error with image uploads. write in functions.php
// Maximum execution time of 29 seconds exceeded in class-wp-image-editor-imagick.php
// importing a theme demo
https://sonaar.ticksy.com/article/15432/
add_filter( 'wp_image_editors', 'change_graphic_lib' );
function change_graphic_lib($array) {
return array( 'WP_Image_Editor_GD', 'WP_Image_Editor_Imagick' );
}
/**
* Get custom posts count, custom posts count
*/
function wp_get_custompost_count($postType, $postStatus = 'publish') {
$args = array(
'post_type' => $postType,
'post_status' => $postStatus,
'posts_per_page' => -1
);
$query = new WP_Query($args);
// return (int)$query->found_posts;
return (int)$query->post_count;
}
//-------------- Check the URL of the WordPress login, login query string, login string check, login params --------------//
/*
* Check the URL of the WordPress login
* page for a specific query string
*
* assumes login string is
* http://mysite.com/wp-login.php?question=answer
*/
https://gist.github.com/williejackson/4347638
function rkv_login_stringcheck() {
// set the location a failed attempt goes to
$redirect = 'http://www.google.com/';
// missing query string all together
if (!isset ($_GET['question']) )
wp_redirect( esc_url_raw ($redirect), 302 );
// incorrect value for query string
if ($_GET['question'] !== 'answer' )
wp_redirect( esc_url_raw ($redirect), 302 );
}
add_action( 'login_init', 'rkv_login_stringcheck' );
//-------------- custom function check login page, detect login page, --------------//
isLoginPage();
function isLoginPage()
{
$is_login_page = false;
$ABSPATH_MY = str_replace(array('\\', '/'), DIRECTORY_SEPARATOR, ABSPATH);
// Was wp-login.php or wp-register.php included during this execution?
if (
in_array($ABSPATH_MY . 'wp-login.php', get_included_files()) ||
in_array($ABSPATH_MY . 'wp-register.php', get_included_files())
) {
$is_login_page = true;
}
// $GLOBALS['pagenow'] is equal to "wp-login.php"?
if (isset($GLOBALS['pagenow']) && $GLOBALS['pagenow'] === 'wp-login.php') {
$is_login_page = true;
}
// $_SERVER['PHP_SELF'] is equal to "/wp-login.php"?
if ($_SERVER['PHP_SELF'] == '/wp-login.php') {
$is_login_page = true;
}
return $is_login_page;
}
// change password by user ID
https://qodeinteractive.com/magazine/wordpress-reset-admin-password-localhost/
wp_set_password('password', 1);
//-------------- my functions --------------//
// calc number of words in content post, posts word number, words number
function srp_words_num($text = '') {
$text = wp_strip_all_tags( $text );
return str_word_count($text, 0);
}
// get value in btn, get value in input
$action = 'value';
sprintf( '<input type="submit" value="%s" class="button" onclick="jQuery(\'#action\').val(\'%s\');" />', 'Submit data', $action );
//-------------- get and select custom terms by hierarchycall levels, terms level --------------//
$all_tax_terms = get_terms([
'taxonomy' => 'job_sectors',
'hide_empty' => true,
'count' => -1,
'orderby' => 'name',
'order' => 'ASC',
// 'fields' => 'names',
'fields' => 'ids', // get id's terms list
]);
// Clear from duplicates and reset counter
// $sorted_terms = array_values(array_unique($all_tax_terms));
// get 1-st term level
function get_first_term_level($all_tax_terms)
{
$terms = $all_tax_terms;
foreach ($terms as $term_id) {
$depth = count(get_ancestors($term_id, 'job_sectors'));
if ($depth === 1) {
// get terms names
$sorted_terms[] = get_term_by('id', $term_id, 'job_sectors')->name;
}
}
return $sorted_terms;
}
$sorted_terms = get_first_term_level($all_tax_terms);
//-------------- work with users, password change, password delete, delete pass, change user --------------//
wp_set_password('password', 1); //
wp_set_auth_cookie(1); // 1 user_id
//-------------- get terms of custom tax and posts --------------//
// https://www.forumming.com/question/8107/get-terms-by-taxonomy-and-post-type
/* get terms limited to post type
@ $taxonomies - (string|array) (required) The taxonomies to retrieve terms from.
@ $args - (string|array) all Possible Arguments of get_terms http://codex.wordpress.org/Function_Reference/get_terms
@ $post_type - (string|array) of post types to limit the terms to
@ $fields - (string) What to return (default all) accepts ID,name,all,get_terms.
if you want to use get_terms arguments then $fields must be set to 'get_terms'
*/
function get_terms_by_post_type($taxonomies, $post_type, $fields = 'all')
{
$args = array(
'post_type' => $post_type,
'posts_per_page' => -1
);
$the_query = new WP_Query($args);
$terms = array();
while ($the_query->have_posts()) {
$the_query->the_post();
$curent_terms = wp_get_object_terms(get_the_ID(), $taxonomies);
foreach ($curent_terms as $t) {
//avoid duplicates
if (!in_array($t, $terms)) {
$terms[] = $c;
}
}
}
wp_reset_query();
// return array of term objects
if ($fields == "all") {
return $curent_terms;
}
// return array of term ID's
if ($fields == "ID") {
foreach ($terms as $t) {
$re[] = $t->term_id;
}
return $re;
}
// return array of term names
if ($fields == "name") {
foreach ($terms as $t) {
$re[] = $t->name;
}
return $re;
}
// get terms with get_terms arguments
if ($fields == "get_terms") {
$terms2 = get_terms($taxonomies, $args);
foreach ($terms as $t) {
if (in_array($t, $terms2)) {
$re[] = $t;
}
}
return $re;
}
}
/* get terms limited to post type, for ajax query */
function get_terms_by_post_type($taxonomies, $post_type)
{
$args = array(
'post_type' => $post_type,
'posts_per_page' => -1
);
$the_query = new WP_Query($args);
$terms = array();
while ($the_query->have_posts()) {
$the_query->the_post();
$curent_terms = wp_get_object_terms(get_the_ID(), $taxonomies);
foreach ($curent_terms as $t) {
//avoid duplicates
if (!in_array($t, $terms)) {
$terms[] = $t->name;
}
}
}
wp_reset_query();
return $terms;
}
//-------------- AJAX filter posts by year --------------//
https://wordpress.stackexchange.com/questions/326662/ajax-filter-posts-by-year
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment