admin管理员组

文章数量:1320610

Hi I want to create a single archive page where every custom post will get displayed on click of a button and after every 5th post I can add an Ad image which can be fetched as another posts type

I can get the currentpost index and able to add an ad on 5th position but I am unable to continue it further.

Here is my code

// WP_Query arguments
$args = array(
    'post_type'              => array( 'trivia' ),
    'post_status'            => array( 'publish' ),
    'order'                  => 'ASC',
    'orderby'                => 'rand',
  'posts_per_page'          => -1,
  //'offset'                 => 1,
  'post__not_in' => array($recentPosts )
);

// The Query
$query = new WP_Query( $args );
$maxPosts = $query->post_count;
$startPost;


$currentPost = $query->current_post;;
$adSpace = $currentPost+6;

// The Loop
if ( $query->have_posts() ) {
    while ( $query->have_posts() ) {


        $query->the_post();
        // do something
  //  $currentPost = $startPost+1;
    if ($currentPost < $maxPosts){
            printf ($currentPost."</br>");
            $currentPost++;

            if($currentPost == $adSpace){

                echo "Ad Space</br>";
            }
        }

Can anyone please help.

Thanks in advance

Hi I want to create a single archive page where every custom post will get displayed on click of a button and after every 5th post I can add an Ad image which can be fetched as another posts type

I can get the currentpost index and able to add an ad on 5th position but I am unable to continue it further.

Here is my code

// WP_Query arguments
$args = array(
    'post_type'              => array( 'trivia' ),
    'post_status'            => array( 'publish' ),
    'order'                  => 'ASC',
    'orderby'                => 'rand',
  'posts_per_page'          => -1,
  //'offset'                 => 1,
  'post__not_in' => array($recentPosts )
);

// The Query
$query = new WP_Query( $args );
$maxPosts = $query->post_count;
$startPost;


$currentPost = $query->current_post;;
$adSpace = $currentPost+6;

// The Loop
if ( $query->have_posts() ) {
    while ( $query->have_posts() ) {


        $query->the_post();
        // do something
  //  $currentPost = $startPost+1;
    if ($currentPost < $maxPosts){
            printf ($currentPost."</br>");
            $currentPost++;

            if($currentPost == $adSpace){

                echo "Ad Space</br>";
            }
        }

Can anyone please help.

Thanks in advance

Share Improve this question asked Oct 4, 2020 at 5:29 Pankaj KumarPankaj Kumar 12 bronze badges
Add a comment  | 

1 Answer 1

Reset to default 0

You'll want to use the % math operator.

if ( $currentPost % 5 === 0 ){
    echo "Ad Space</br>";
}

本文标签: theme developmentWordpress Insert ads after every 5th post