questions

Get page content by slug or title WP

Rate this post

I am creating a blog and I have difficulty with pages in wordpress, in my case I would like to insert content (raw content) from two pages randomly in modal system while people browse the blog.

Example: Current Page> Modal Box> Page01 content or Page02 Content

I know it’s possible by the page id. but I would like to make it more dynamic by getting the contents of the pages by slugs or by title.

here’s the code

<?php

  $term = get_taxonomy( $slug );

  $args = array( 
    'post_type' => 'page', 
    'posts_per_page' => 1, 
    'orderby' => 'RAND',
    'tax_query' => array( array(
        'taxonomy' => $term,
        'field' => 'slug',
        'terms' => array('page-01', 'page-02'),
    ) )
  );

  $rand = new WP_Query($args);

  if ($rand->have_posts()) {
    while ($rand->have_posts()) {
      $rand->the_post();
      the_content();
    }
  }
?>

I know that removing taxonomy from query gets the contents of publish pages but, in my case, I need to get content from two specific pages

 

✔️Solution:

You can use post_name__in to filter by multiple slugs, eg:

  $args = array( 
    'post_name__in' => array('page-slug-1', 'page-slug-2'),
    'post_type' => 'page', 
    'posts_per_page' => 1, 
    'orderby' => 'RAND',
  );

You can find more details on the WP_Query documentation page.

Leave a Reply

Your email address will not be published.

Back to top button