Insert content after x img tag - wordpress

My code counts p tags, then insert ads code after x-th p tag.
If I want to count img tags, then insert ads code after x-th img tag how should I do it?
add_filter( 'the_content', 'prefix_insert_post_ads2' );
function prefix_insert_post_ads2( $content ) {
$imgs = preg_match_all("#<img.+>#U", $content, $matches);
$ad_codea = "ads code";
if ( is_single() && ! is_admin() && $imgs >= 4) {
return prefix_insert_after_paragraph2( $ad_codea, 3, $content );
}
return $content;
}
function prefix_insert_after_paragraph2( $insertion, $paragraph_id, $content ) {
$closing_p = '></p>';
$paragraphs = explode( $closing_p, $content );
foreach ($paragraphs as $index => $paragraph) {
if ( trim( $paragraph ) ) {
$paragraphs[$index] .= $closing_p;
}
if ( $paragraph_id == $index + 1 ) {
$paragraphs[$index] .= $insertion;
}
}
return implode( '', $paragraphs );
}

I have solved by myself.
add_filter( 'the_content', 'prefix_insert_post_ads2' );
function prefix_insert_post_ads2( $content ) {
$imgs = preg_match_all("#<img.+>#U", $content, $matches);
preg_match_all('/<img[^>]+>/i',$content, $result);
$ad_codea = '123';
if ($imgs < 4 ) {$result[0][1]='';}
if ( is_single() && ! is_admin()) {
return str_replace($result[0][1], $result[0][1].$ad_codea, $content);
}
}

Related

Place ads after second paragraph of the posts in a specific category

I want to place ads after second paragraph of the posts located under a specific category. For this I am trying to run the following piece of codes but it is not working. Kindly help me out.
//Insert ads after second paragraph of single post content.
$catarray = get_the_category( $post->ID );
foreach ($catarray as $cat) {
$catid = $cat->term_id;
if ($catid == 124);
add_filter( 'the_content', 'prefix_insert_post_ads' );
function prefix_insert_post_ads( $content ) {
$ad_code = '<div>Insert Ad code here</div>';
if ( is_single() && ! is_admin() ) {
return prefix_insert_after_paragraph( $ad_code, 2, $content );
}
}
return $content;
}
// Parent Function that makes the magic happen
function prefix_insert_after_paragraph( $insertion, $paragraph_id, $content ) {
$closing_p = '</p>';
$paragraphs = explode( $closing_p, $content );
foreach ($paragraphs as $index => $paragraph) {
if ( trim( $paragraph ) ) {
$paragraphs[$index] .= $closing_p;
}
if ( $paragraph_id == $index + 1 ) {
$paragraphs[$index] .= $insertion;
}
}
return implode( '', $paragraphs );
}
you can use this code for it
add_filter('the_content', 'ak_the_content_filter', 10, 1);
function ak_the_content_filter($content)
{
$catarray = get_the_category( $post->ID );
foreach ($catarray as $cat) {
$catid = $cat->term_id;
if ($catid != 124) { return $content; }
else{
$parags = explode('</p>', $content);
$parags[1] .= '<br>'.do_shortcode('[SHORTCODE HERE]');// add whatever you want after first paragraph
$content_new = '';
foreach ($parags as $parag) {
$content_new .= $parag;
}
return $content_new;
}
}
}

Add message below shipping methods based on taxonomy terms in WooCommerce

I'd like to add a custom message below the available shipping methods in the cart, but only if ALL products in the cart have a tag named 'express'.
Therefore I use this snippet:
add_action( 'woocommerce_after_shipping_rate', 'action_after_shipping_rate', 20, 2 );
function action_after_shipping_rate ( $method, $index ) {
if( 'flat_rate:1' === $method->id ) {
echo __("<p>Arriving on your chosen date between 9am - 1pm Perfect for business addresses & special occasions</p>");
}
if( 'flat_rate:2' === $method->id ) {
echo __("<p>Arriving on your chosen date between 9am - 7pm Perfect for residential addresses</p>");
}
}
add_filter( 'woocommerce_shipping_details', 'hide_shipping_details', 10, 2 );
function hide_shipping_details( $rates, $package ) {
$terms = array( 'express' );
$taxonomy = 'product_tag';
$found = false;
foreach( $package['contents'] as $cart_item ) {
if ( !has_term( $terms, $taxonomy, $cart_item['product_id'] ) ){
$found = true;
break;
}
}
if ( $found === false ) {
remove_action( 'woocommerce_after_shipping_rate', 'action_after_shipping_rate', 20, 2 );
}
}
But right now, the custom message remains if 1 or 2 products have the tag 'express' but not ALL products. Can someone help me solve this problem?
No need to call from one hook to another, while you can just loop through all the products in cart in the woocommerce_after_shipping_rate hook
So you get:
function action_woocommerce_after_shipping_rate( $method, $index ) {
// Settings
$terms = array( 'express', 'tag-1' );
$taxonomy = 'product_tag';
// Initialize
$flag = false;
// Loop through cart items
foreach ( WC()->cart->get_cart() as $cart_item ) {
// Checks if the current product has NOT any of given terms
if ( ! has_term( $terms, $taxonomy, $cart_item['product_id'] ) ) {
$flag = true;
break;
}
}
// When false
if ( ! $flag ) {
// Compare
if ( $method->get_id() === 'flat_rate:1' ) {
$text = 'My text 1';
} elseif ( $method->get_id() === 'flat_rate:3' ) {
$text = 'My text 2';
} elseif ( $method->get_id() === 'local_pickup:1' ) {
$text = 'My text 3';
}
// When isset
if ( isset( $text ) ) {
// Output
echo '<p>' . sprintf( __( '%s', 'woocommerce' ), $text ) . '</p>';
}
}
}
add_action( 'woocommerce_after_shipping_rate', 'action_woocommerce_after_shipping_rate', 10, 2 );

Change WooCommerce product Shop URL

Is there a way to change the shop URL
from: https://example.com/shop/productpage/
to: https://example.com/productpage/
make a new plugin with code below or add to functions.php in theme. REMEMBER update permalink
function wndev_remove_slug( $post_link, $post ) {
if ( !in_array( get_post_type($post), array( 'product' ) ) || 'publish' != $post->post_status ) {
return $post_link;
}
if('product' == $post->post_type){
$post_link = str_replace( '/shop/', '/', $post_link );
}else{
$post_link = str_replace( '/' . $post->post_type . '/', '/', $post_link );
}
return $post_link;
}
add_filter( 'post_type_link', 'wndev_remove_slug', 10, 2 );
function wndev_woo_product_rewrite_rules($flash = false) {
global $wp_post_types, $wpdb;
$siteLink = esc_url(home_url('/'));
foreach ($wp_post_types as $type=>$custom_post) {
if($type == 'product'){
if ($custom_post->_builtin == false) {
$querystr = "SELECT {$wpdb->posts}.post_name, {$wpdb->posts}.ID
FROM {$wpdb->posts}
WHERE {$wpdb->posts}.post_status = 'publish'
AND {$wpdb->posts}.post_type = '{$type}'";
$posts = $wpdb->get_results($querystr, OBJECT);
foreach ($posts as $post) {
$current_slug = get_permalink($post->ID);
$base_product = str_replace($siteLink,'',$current_slug);
add_rewrite_rule($base_product.'?$', "index.php?{$custom_post->query_var}={$post->post_name}", 'top');
add_rewrite_rule($base_product.'comment-page-([0-9]{1,})/?$', 'index.php?'.$custom_post->query_var.'='.$post->post_name.'&cpage=$matches[1]', 'top');
add_rewrite_rule($base_product.'(?:feed/)?(feed|rdf|rss|rss2|atom)/?$', 'index.php?'.$custom_post->query_var.'='.$post->post_name.'&feed=$matches[1]','top');
}
}
}
}
if ($flash == true)
flush_rewrite_rules(false);
}
add_action('init', 'wndev_woo_product_rewrite_rules');
function wndev_woo_new_product_post_save($post_id){
global $wp_post_types;
$post_type = get_post_type($post_id);
foreach ($wp_post_types as $type=>$custom_post) {
if ($custom_post->_builtin == false && $type == $post_type) {
wndev_woo_product_rewrite_rules(true);
}
}
}
add_action('wp_insert_post', 'wndev_woo_new_product_post_save');

Double filters showing on web view on Woocommerce

I'm having a problem with my woocommerce theme, flatsome, but I think the problem is with the widget. The standard woocommerce product filter.
In the web view it shows normally, but on the mobile view the filter gets doubled;
a filter which gives you the standard mobile view-type of filter that pops on the side when clicked,
and another filter which gives an ugly dropdown.
This is the image on mobile view, the one on top has the right filter I want, the one under gives the ugly dropdown
Here's the code of the filter:
<?php
/*
Plugin Name: WooCommerce Product Filter
Plugin URI: http://www.mihajlovicnenad.com/product-filter
Description: Advanced product filter for any Wordpress template! - mihajlovicnenad.com
Author: Mihajlovic Nenad
Version: 6.3.0
Author URI: https://www.mihajlovicnenad.com
Text Domain: prdctfltr
*/
if ( ! defined( 'ABSPATH' ) ) {
exit;
}
if ( !class_exists( 'PrdctfltrInit' ) ) :
final class PrdctfltrInit {
public static $version = '6.3.0';
protected static $_instance = null;
public static function instance() {
if ( is_null( self::$_instance ) ) {
self::$_instance = new self();
}
return self::$_instance;
}
public function __construct() {
do_action( 'prdctfltr_loading' );
$this->includes();
$this->init_hooks();
do_action( 'prdctfltr_loaded' );
}
private function init_hooks() {
register_activation_hook( __FILE__, array( $this, 'activate' ) );
add_action( 'init', array( $this, 'check_version' ), 10 );
add_action( 'init', array( $this, 'init' ), 0 );
}
private function is_request( $type ) {
switch ( $type ) {
case 'admin' :
return is_admin();
case 'ajax' :
return defined( 'DOING_AJAX' );
case 'cron' :
return defined( 'DOING_CRON' );
case 'frontend' :
return ( ! is_admin() || defined( 'DOING_AJAX' ) ) && ! defined( 'DOING_CRON' );
}
}
public function includes() {
include_once( 'lib/pf-characteristics.php' );
include_once( 'lib/pf-widget.php' );
include_once( 'lib/pf-fixoptions.php' );
if ( $this->is_request( 'admin' ) ) {
add_action( 'vc_before_init', array( $this, 'composer' ) );
include_once ( 'lib/pf-settings.php' );
$purchase_code = get_option( 'wc_settings_prdctfltr_purchase_code', '' );
if ( $purchase_code ) {
require 'lib/update/plugin-update-checker.php';
$pf_check = PucFactory::buildUpdateChecker(
'http://mihajlovicnenad.com/envato/verify_json.php?k=' . $purchase_code,
__FILE__
);
}
}
if ( $this->is_request( 'frontend' ) ) {
$this->frontend_includes();
}
}
public function frontend_includes() {
include_once( 'lib/pf-frontend.php' );
include_once( 'lib/pf-shortcode.php' );
}
public function include_template_functions() {
}
public function init() {
do_action( 'before_prdctfltr_init' );
$this->load_plugin_textdomain();
do_action( 'after_prdctfltr_init' );
}
public function load_plugin_textdomain() {
$domain = 'prdctfltr';
$dir = untrailingslashit( WP_LANG_DIR );
$locale = apply_filters( 'plugin_locale', get_locale(), $domain );
if ( $loaded = load_textdomain( $domain, $dir . '/plugins/' . $domain . '-' . $locale . '.mo' ) ) {
return $loaded;
}
else {
load_plugin_textdomain( $domain, FALSE, basename( dirname( __FILE__ ) ) . '/lang/' );
}
}
public function setup_environment() {
}
public function plugin_url() {
return untrailingslashit( plugins_url( '/', __FILE__ ) );
}
public function template_path() {
return apply_filters( 'prdctfltr_template_path', '/templates/' );
}
public function plugin_path() {
return untrailingslashit( plugin_dir_path( __FILE__ ) );
}
public function plugin_basename() {
return untrailingslashit( plugin_basename( __FILE__ ) );
}
public function ajax_url() {
return admin_url( 'admin-ajax.php', 'relative' );
}
public function version() {
return self::$version;
}
public function composer() {
require_once( 'lib/pf-composer.php' );
}
function check_version() {
$version = get_option( 'wc_settings_prdctfltr_version', false );
if ( $version === false ) {
$check = get_option( 'wc_settings_prdctfltr_always_visible', false );
if ( $check === false ) {
update_option( 'wc_settings_prdctfltr_version', self::$version, 'yes' );
return '';
}
else {
$version = get_option( 'wc_settings_prdctfltr_version', '5.8.1' );
}
}
if ( version_compare( '5.8.2', $version, '>' ) ) {
add_action( 'admin_init', array( &$this, 'fix_database_582' ), 100 );
}
if ( version_compare( '6.0.6', $version, '>' ) ) {
add_action( 'init', array( &$this, 'fix_database_606' ), 100 );
}
}
function fix_database_606() {
global $wpdb;
$default = $wpdb->get_results( "SELECT `option_name`, `option_value` FROM `$wpdb->options` WHERE `option_name` LIKE CONVERT( _utf8 'wc_settings_prdctfltr_%'USING utf8mb4 ) COLLATE utf8mb4_unicode_ci LIMIT 99999" );
if ( !empty( $default ) ) {
$fix_default = array();
include_once( 'lib/pf-options-autoload.php' );
foreach( $default as $k => $v ) {
if ( in_array( $v->option_name, $forbidden_std ) ) {
$wpdb->query( "update $wpdb->options set autoload='yes' where option_name = '$v->option_name';" );
}
else if ( in_array( $v->option_name, $dont_autoload_std ) || substr( $v->option_name, 0, 41 ) == 'wc_settings_prdctfltr_term_customization_' || substr( $v->option_name, 0, 43 ) == 'wc_settings_prdctfltr_filter_customization_' ) {
$wpdb->query( "update $wpdb->options set autoload='no' where option_name = '$v->option_name';" );
}
else if ( in_array( $v->option_name, $autoload_std ) ) {
$wpdb->query( "update $wpdb->options set autoload='yes' where option_name = '$v->option_name';" );
}
else if ( strpos( $v->option_name, 'transient' ) ) {
delete_option( $v->option_name );
}
else {
$fix_default[$v->option_name] = get_option( $v->option_name );
$wpdb->query( "update $wpdb->options set autoload='no' where option_name = '$v->option_name';" );
}
}
if ( !empty( $fix_default ) ) {
$fix_default = json_encode( $fix_default );
update_option( 'prdctfltr_wc_default', $fix_default, 'no' );
}
$templates = get_option( 'prdctfltr_templates', array() );
if ( !empty( $templates ) && is_array( $templates ) ) {
update_option( 'prdctfltr_backup_templates', $templates, 'no' );
foreach( $templates as $k1 => $v1 ) {
if ( !empty( $v1 ) && substr( $v1, 0, 1 ) == '{' ) {
update_option( 'prdctfltr_wc_template_' . sanitize_title( $k1 ), $v1, 'no' );
$templates[$k1] = array();
}
}
}
update_option( 'prdctfltr_templates', $templates, 'no' );
}
update_option( 'wc_settings_prdctfltr_version', self::$version, 'yes' );
}
function fix_database_582() {
global $wpdb;
$wpdb->query( "update $wpdb->options set autoload='yes' where option_name like '%prdctfltr%';" );
$wpdb->query( "delete from $wpdb->options where option_name like '_transient_prdctfltr_%';" );
$wpdb->query( "delete from $wpdb->options where option_name like '_transient_%_prdctfltr_%';" );
$wpdb->query( "delete from $wpdb->options where option_name like 'wc_settings_prdctfltr_%_end';" );
$wpdb->query( "delete from $wpdb->options where option_name like 'wc_settings_prdctfltr_%_title' and option_value = '' ;" );
delete_option( 'wc_settings_prdctfltr_force_categories' );
delete_option( 'wc_settings_prdctfltr_force_emptyshop' );
delete_option( 'wc_settings_prdctfltr_force_search' );
delete_option( 'wc_settings_prdctfltr_caching' );
delete_option( 'wc_settings_prdctfltr_selected' );
delete_option( 'wc_settings_prdctfltr_attributes' );
update_option( 'wc_settings_prdctfltr_version', '6.0.5', 'yes' );
}
function activate() {
if ( false !== get_transient( 'prdctfltr_default' ) ) {
delete_transient( 'prdctfltr_default' );
}
$active_presets = get_option( 'prdctfltr_templates', array() );
if ( !empty( $active_presets ) && is_array( $active_presets ) ) {
foreach( $active_presets as $k => $v ) {
if ( false !== ( $transient = get_transient( 'prdctfltr_' . $k ) ) ) {
delete_transient( 'prdctfltr_' . $k );
}
}
}
}
}
function Prdctfltr() {
return PrdctfltrInit::instance();
}
PrdctfltrInit::instance();
endif;
?>
Simple CSS should be able to fix this. Use media queries to hide the filter with the ugly dropdown on small screens.
Something like:
#media (max-width: 768px) {
.filter-dropdown{
display: none;
}
}
Substitute filter-dropdown with the class name of that filter. Substitute 768px with whichever number of pixels is right for your situation.
Without you pasting code we can't be more specific than that.

Permalink structure for my custom_post_type

I have a “gallery” as custom_post_type and “albums” as taxonomry_name
How can i achieve this structure :
mydomain.com/gallery/albums/{taxonomy_term}/{post}
I've tried something like the example below but it didn't work or perhaps i haven't used it properly
add_filter('rewrite_rules_array', 'mmp_rewrite_rules');
function mmp_rewrite_rules($rules) {
$newRules = array();
$newRules['basename/(.+)/(.+)/(.+)/?$'] = 'index.php?gallery=$matches[3]'; // my custom structure will always have the post name as the 4th uri segment
$newRules['basename/(.+)/?$'] = 'index.php?albums=$matches[1]';
return array_merge($newRules, $rules);
}
function filter_post_type_link($link, $post)
{
if ($post->post_type != 'gallery')
return $link;
if ($cats = get_the_terms($post->ID, 'albums'))
{
$link = str_replace('%albums%', get_taxonomy_parents(array_pop($cats)->term_id, 'albums', false, '/', true), $link); // see custom function defined below
}
return $link;
}
add_filter('post_type_link', 'filter_post_type_link', 10, 2);
function get_taxonomy_parents($id, $taxonomy, $link = false, $separator = '/', $nicename = false, $visited = array()) {
$chain = '';
$parent = &get_term($id, $taxonomy);
if (is_wp_error($parent)) {
return $parent;
}
if ($nicename)
$name = $parent -> slug;
else
$name = $parent -> name;
if ($parent -> parent && ($parent -> parent != $parent -> term_id) && !in_array($parent -> parent, $visited)) {
$visited[] = $parent -> parent;
$chain .= get_taxonomy_parents($parent -> parent, $taxonomy, $link, $separator, $nicename, $visited);
}
if ($link) {
// nothing, can't get this working :(
} else
$chain .= $name . $separator;
return $chain;
}
I solved my problem by using the code below:
// Add our custom permastructures for custom taxonomy and post
add_action( 'wp_loaded', 'add_album_permastructure' );
function add_album_permastructure() {
global $wp_rewrite;
add_permastruct( 'albums', 'gallery/%albums%', false );
add_permastruct( 'gallery', 'gallery/%albums%/%gallery%', false );
}
// Make sure that all links on the site, include the related texonomy terms
add_filter( 'post_type_link', 'gallery_permalinks', 10, 2 );
function gallery_permalinks( $permalink, $post ) {
if ( $post->post_type !== 'gallery' )
return $permalink;
$terms = get_the_terms( $post->ID, 'albums' );
if ( ! $terms )
return str_replace( '%albums%/', '', $permalink );
$post_terms = array();
foreach ( $terms as $term )
$post_terms[] = $term->slug;
return str_replace( '%albums%', implode( ',', $post_terms ) , $permalink );
}
// Make sure that all term links include their parents in the permalinks
add_filter( 'term_link', 'add_term_parents_to_permalinks', 10, 2 );
function add_term_parents_to_permalinks( $permalink, $term ) {
$term_parents = get_term_parents( $term );
foreach ( $term_parents as $term_parent )
$permlink = str_replace( $term->slug, $term_parent->slug . ',' . $term->slug, $permalink );
return $permlink;
}
// Helper function to get all parents of a term
function get_term_parents( $term, &$parents = array() ) {
$parent = get_term( $term->parent, $term->taxonomy );
if ( is_wp_error( $parent ) )
return $parents;
$parents[] = $parent;
if ( $parent->parent )
get_term_parents( $parent, $parents );
return $parents;
}
Added this to fucntions.php and then refreshed my permalink structure from the Settings -> Permalink

Resources