-
Hello,
How can I insert Adsense ads to middle of posts by using Elements? -
Fernando
Hi K,
You’ll need to create a Portable hook.
Example:
function your_shortcode($atts, $content = null) { ob_start(); do_action('hook_name'); return ob_get_clean(); } add_shortcode('portable_hook', 'your_shortcode');Adding PHP: https://docs.generatepress.com/article/adding-php/#code-snippets
After adding this PHP, you may add the shortcode as such: https://share.getcloudapp.com/ApuJGooG
You can add this in the middle of your Content through a Shortcode Block.
Then you can now create your Element for your advertisement and hook it to
hook_name– custom hook.Example: https://share.getcloudapp.com/eDu5xKLX
Side note: To avoid CLS issues, you can place the ad code inside a div as such:
<div class="header-advert"> <!-- you ad script here --> </div>Then, add this CSS to set a minimum height to it:
.header-advert { min-height: 250px; }Replace the 250px value with the height of the ad.
-
Hi fernandoazarcon2! Thank you for replying.
I would try to add the code but my ad before h2 tag disappeared. I’ve already added a code below. It might get some issues with this code?add_shortcode(‘portable_hook’, function($atts){
ob_start();
$atts = shortcode_atts( array(
‘hook_name’ => ‘no foo’
), $atts, ‘portable_hook’ );
do_action($atts[‘hook_name’]);
return ob_get_clean();
});add_filter( ‘the_content’, ‘insert_custom_block’, 20 );
function insert_custom_block( $content ) {
global $post;
$inserted_hook = do_shortcode(‘[portable_hook hook_name=”before_first_h2″]’);
if ( is_single() && ! is_admin() ) {
return prefix_insert_before_h2( $inserted_hook, 1, $content );
}
return $content;
}
function prefix_insert_before_h2( $insertion, $paragraph_id, $content ) {$pattern = ‘/<h2/’;
$replacement = $insertion . ‘<h2’;
if( strpos($content, ‘<h2’) !== false ) {
return preg_replace( $pattern , $replacement, $content, 1);
}
return $content;
} -
Fernando
Oh. They have the same variable names. The variables are changeable.
For instance, replace the Portable hook code with this:
function ad_shortcode($atts, $content = null) { ob_start(); do_action('hook_custom_ad'); return ob_get_clean(); } add_shortcode('portable_hook_ad', 'ad_shortcode');With this, your shortcode would be:
[portable_hook_ad].And, the hook would be:
hook_custom_ad.It’s the same thing, you just need to replace the name of the hook, function and shortcode to avoid any conflict.
-
Hi,
Thank you for the details. I’ve tried but I couldn’t solve it. I’m sorry, I wouldn’t understand about technical things. I would like to insert ads to “all of posts” by using Element. -
Fernando
Can you provide admin login credentials through the Private Information field? I’ll check your current setup. Please share a link to a Post on your site as well.
- You must be logged in to reply to this topic.