So I want to apply two separate templates, to two different types of pages (not posts).
Both page types are children pages.
The template 'exhibition-template.php' is applied to all pages that are children of the 'archive' page.
This works!
I do this with a function in functions.php that tests to see if a page is a child of 'archive', then use that function in page.php to apply the template:
//////////////////////////////////////////////
function is_archivechild() {
// Set up the objects needed
$my_wp_query = new WP_Query();
$all_wp_pages = $my_wp_query->query(array('post_type' => 'page', 'posts_per_page' => '-1'));
// Get the page as an Object
$archive = get_page_by_title('archive');
// Filter through all pages and find archive's children
$archive_children = get_page_children( $archive->ID, $all_wp_pages );
if ($archive_children > 0){
return true;
}
else{
return false;
}
}
//////////////////////////////////////////////
And using it in page.php:
//////////////////////////////////////////////
elseif ( is_archivechild() ) {/*a function made up in functions.php, tests if it is a of archive*/
get_template_part( 'exhibition-template' );
get_template_part( 'normalfooter' );
}
//////////////////////////////////////////////
The problem is when I write the function a second time with new variables, and try to implement it in the exact same way except for applying 'artist-template.php' to children pages of 'artists', nothing changes, in fact it still applies 'exhibition-template.php' no matter what.
//////////////////////////////////////////////
function is_artistschild() {
// Set up the objects needed
$artist_query = new WP_Query();
$all_wp_pages = $artist_query->query(array('post_type' => 'page', 'posts_per_page' => '-1'));
// Get the page as an Object
$artists = get_page_by_title('artists');
// Filter through all pages and find artists's children
$artists_children = get_page_children( $artists->ID, $all_wp_pages );
if ($artists_children > 0){
return true;
}
else{
return false;
}
}
//////////////////////////////////////////////
elseif ( is_artistchild() ) {/*a function made up in functions.php, tests if it is a CHILD page, aka an exhibition*/
get_template_part( 'artist-template' );
get_template_part( 'normalfooter' );
}
//////////////////////////////////////////////
Whaaaaat the hell is going on?!?!?
much thanks!
You can write inside page.php the above:
<?php global $post;
$page = get_page_by_title( 'archive' ); // page title , Archive in your case . Try an alternative page name.
$page_parent_ID=$page->ID;
?>
<?php if ($post->post_parent == $page_parent_ID) {
get_template_part( 'exhibition-template' ); // you name of template you want to appear
}
?>
Related
Please Help
I want to make a search page for images stored in media gallery of wordpress. This page contains a textbox in which user will enter the number of image. The matched image should display in the different tab of browser.
I made a raw html page in wordpress where i put the which display a textbox but don't understand that where i have to write the php code to extract the images and how to show them.
Please give step by step instructions to solve the issue because i am beginner in wordpress.
You can create a custom function in functions.php for this and you can call that in your template
//In functions.php
if( ! ( function_exists( 'get_media_from_name' ) ) ) {
function get_media_from_name( $postName ) {
$args = array(
'name' => $postName,
'posts_per_page' => -1,
'post_type' => 'attachment',
);
$attachment = new WP_Query( $args );
if ( $attachment)
return $attachment;
else
return false;
}
}
//In you template where you can call that function
$get_all_matched_attachments = get_media_from_name( $postName );
if ( $get_all_matched_attachments ) {
foreach($get_all_matched_attachments as $get_all_matched_attachment){
echo '<pre>';print_r($get_all_matched_attachment);
}
}
I want edit default archive template. I created archive.php and add this code:
function mpp_body_class( $classes ) {
$classes[] = 'mpp-home';
return $classes;
}
add_filter( 'body_class', 'mpp_body_class' );
// Force content-sidebar layout setting
add_filter( 'genesis_pre_get_option_site_layout', '__genesis_return_full_width_content' );
genesis();
How to call post loop and makeup html for it?
You don't necessarily need to create a php file for customizing genesis,
you can simply build a custom loop directly on custom functions.php or any plugin
// hooking the modification on wp_head
add_action('wp_head', function() {
// check if we are on archive pages, if not just return back
if ( !is_archive() ) return;
//remove genesis default loop
remove_action( 'genesis_loop', 'genesis_do_loop' );
//add your custom loop
add_action( 'genesis_loop', 'your_custom_loop_archive' );
add_filter( 'body_class', 'mpp_body_class' );
// Force content-sidebar layout setting
add_filter( 'genesis_pre_get_option_site_layout', '__genesis_return_full_width_content' );
});
function mpp_body_class( $classes ) {
$classes[] = 'mpp-home';
return $classes;
}
function your_custom_loop_archive() {
// needed to get the queried date for date archive
global $wp_query;
// get current archive details, this return object user data for user
//returns NULL for date archive, that's why we have to also use $wp_query object for date
$obj = get_queried_object();
//build query paramter to get all the post of this archive
$args = [
'orderby' => 'menu_order', // overide default orderby
'order' => 'ASC', // overide default orderb
'posts_per_page'=> '12', // overrides default posts per
];
//add author paramater for author archive
if ( is_author() ) $args['author'] = $obj->ID;
//add year & monthnum paramater for date archive
if ( is_date() ) $args = array_merge( $args, $wp_query->query );
//add tax_query paramater for taxonomy archive, includes categories & tags
//is_tax() will return false for post category & tag
//we need to include is_category() and is_tag()
// see https://core.trac.wordpress.org/ticket/18636
if ( is_tax() || is_category() || is_tag() ) {
$args['tax_query'] = [[
'taxonomy' => $obj->taxonomy,
'field' => 'id',
'terms' => $obj->term_id,
]];
}
//build new query
$loop = new WP_Query( $args );
//duh Loop
if( $loop->have_posts() ):
while( $loop->have_posts() ): $loop->the_post(); global $post;
// build your html template here
echo '<pre>', print_r( $post, 1), '</pre>'; // spit each post object data
endwhile;
endif;
}
I'd like to add a query variable to all queries coming from a certain domain.
For example, mydomain.com and proxydomain.com both show the same WordPress site, but for users visiting via proxydomain.com, I'd like to be able to handle their queries differently.
Additionally, I'd like to apply some different CSS styles for visitors coming through proxydomain.com.
I was thinking I could check for the query_var and apply classes based on the presence of that variable.
This is the code to add to your functions.php file:
add_filter( 'body_class', 'domain_as_body_class' );
function domain_as_body_class( $classes ) {
$classes[] = sanitize_title( $_SERVER['SERVER_NAME'] );
return $classes;
}
It adds the sanitized domain of your site (i.e. mydomain-com or proxydomain-com) as class of the body tag of your pages, so you can target the relative class for custom styles.
Update
For the queries you could add a function again in functions.php like:
function is_proxydomain() {
return 'proxydomain.com' == $_SERVER['SERVER_NAME'];
}
And then use it when needed on a query:
if( is_proxydomain() ) {
$args = array(
// arguments for proxydomain.com
);
} else {
$args = array(
// arguments for mydomain.com
);
}
$query = new WP_Query( $args );
I like the answer of d79 for the first part.
For the queries, I think it would be better to extend WP_Query class ( i.e. WP_Query_Custom ) and have one copy for each domain. Then you can load the file you need based on the domain in the functions.php file, and so you don't need to change in the future your calls everywhere you use WP_Query_Custom, even if you need to add more domains and different versions of WP_Query_Custom.
//in functions.php
$mydomain = str_replace('.', '_', $_SERVER['SERVER_NAME']);
require_once("path/to/my/classes/$mydomain/WP_Query_Custom.php");
//In each path/to/my/classes/$mydomain/WP_Query_Custom.php
class WP_Query_Custom extends WP_Query {
function __construct( $args = array() ) {
// Force these args
$args = array_merge( $args, array(
'post_type' => 'my_custom_post_type',
'posts_per_page' => -1, // Turn off paging
'no_found_rows' => true // Optimize query for no paging
) );
add_filter( 'posts_where', array( $this, 'posts_where' ) );
parent::__construct( $args );
// Make sure these filters don't affect any other queries
remove_filter( 'posts_where', array( $this, 'posts_where' ) );
}
function posts_where( $sql ) {
global $wpdb;
return $sql . " AND $wpdb->term_taxonomy.taxonomy = 'my_taxonomy'";
}
}
The example class is copied from extending WP_Query
I'm new to Wordpress & PHP, so kindly excuse the naivety of the question, if any.
I'm building a plugin where I need to select values from the database and create a new HTML page with the values. I'm using a custom template file.
What I've done till now
Extracted the values from database
Load & display my own template in my plugin file
add_action( 'init', 'leb_add_endpoint' );
function leb_add_endpoint()
{
add_rewrite_endpoint( 'result', EP_PERMALINK );
}
add_action( 'template_include', 'leb_render_template' );
function leb_render_template($default_template) {
//some code removed for brevity
if ( ! is_singular() || !isset($wp_query->query_vars['result']) )
{
return $default_template;
}
$sample_result = $wpdb->get_var($wpdb->prepare($sql));
$default_template = plugin_dir_path(__FILE__) . '/my-custom-template.php';
return $default_template;
}
The content of my-custom-template.php is as follows
<?php
/* Template Name: My Template*/
echo '<h1>Testing</h1>';
?>
The page gets displayed without any problem. All I want is to insert $sample_result and other similar results pulled form database into my-custom-template.php
I need to generate dynamic pages based on values pulled from DB. So each time, the final page created might be different. E.g. if one hits www.example.com/sample-post/result, a page will be shown with values pulled from the DB. If one hits www.example.com/another-sample-post/result, a different page will be shown with different values. Both these pages will have the same design, only a few values will be different. This is what I'm trying to achieve.
How can I do that? Please help me. I'm stuck. :(
You need to define "result" in query vars.
Use EP_ROOT Endpoint Mask ( result/{var} is located in the root )
Inside template_include hook, you can find result value inside $wp_query object.
I've already tested the code
// Add a new var to query vars
function result_add_query_vars( $vars ){
$vars[] = 'result';
return $vars;
}
add_filter( 'query_vars', 'result_add_query_vars' );
// Add endpoint
function result_add_endpoint() {
add_rewrite_endpoint( 'result', EP_ROOT );
}
add_action( 'init', 'result_add_endpoint');
// change the template
function result_render_template($template)
{
global $wp_query;
if ( array_key_exists( 'result', $wp_query->query_vars ) ) {
$result = get_query_var('result');
$new_template = plugin_dir_path(__FILE__) . '/my-custom-template.php';
return $new_template;
} else {
return $template;
}
}
add_action( 'template_include', 'result_render_template' );
Now you can retrieve the query var in your custom template
/*
* Template Name: My Custom Template
*/
$result = get_query_var('result');
echo $result;
Well why don't you use $wp_query Inside your my-custom-template.php
<?php
/* Template Name: My Template*/
global $wp_query;
echo '<pre>';
print_r($wp_query); // Use this in case you want to see what else do you have with you.
echo '<pre/>';
// Now you can use $wp_query to build your dynamic query at run time.
// This will allow you to perform task at run time
?>
To Retrieve Meta
If you have saved something as a meta then
<?php
$meta_values = get_post_meta( $post_id, $key, $single );
?>
To Retrieve Child Post
If you want to retrieve child posts then
<?php
if ( have_posts() ) :
// Start the Loop.
while ( have_posts() ) : the_post();
// Do your stuff here such as below
the_title();
the_content();
endwhile;
else:
echo 'No Post Found';
endif;
?>
1) Write this function in function.php in your active template.
function leb_render_template() {
//some code removed for brevity
//$sql = 'YOUR_QUERY_CODE'
$sample_result = $wpdb->get_var($wpdb->prepare($sql));
return $my_template;
}
add_action('wp_ajax_leb_render_template', 'leb_render_template');
add_action('wp_ajax_nopriv_leb_render_template', 'leb_render_template');
2) Call function in your custom template.
<?php
/* Template Name: My Template*/
echo '<h1>Testing</h1>';
$result = leb_render_template();
print_r($result); // Print Your function output.
?>
I'm trying to make the front-end login for Wordpress redirect to the post (in a custom post type) that was automatically created when they registered.
I can get the URL I want to redirect them with a wp_query. I imagine this is not the best way to do it, but I don't know enough php to figure it out. Here's my current attempt, but it just prints the url (the right one, at least!) on a blank page with the same login url they were already at:
function my_login_redirect( $redirect_to, $request, $user ){
global $user, $post;
$args = array(
'author' => $current_user->ID,
'post_type' => 'course-providers',
'showposts' => 1,
'caller_get_posts' => 1
);
$my_query = null;
$my_query = new WP_Query($args);
if( $my_query->have_posts() ) {
while ($my_query->have_posts()) : $my_query->the_post(); ?>
<?php wp_redirect ( the_permalink () ); ?>
<?php
endwhile;
} else {
echo "This User Has no Profile";
}
}
add_filter("login_redirect", "my_login_redirect", 10, 3);
Also, I imagine I don't need the wp_redirect and that I should just be using the login_redirect filter itself, but again, I'm pretty lost right now and just taking lots of shots in the dark.
Thanks for the help, and let me know if there's additional info that would make this more helpful for others or easier to answer. Thanks!
I ended up using a template redirect to make this work. I assume there's technically a better way to do it, but it's loading extremely fast and doing exactly what I need it to.
So, now, when a user logs in it goes to a direct url- /profiles - and the template on that page is just a redirect. I used the ideas and some sample code from this smashing magazine post on random redirects to make it work.
Here's the function I used in my functions.php file for the template to make the redirect happen:
function profile_redirect() {
// This is a template redirect
// Whenever someone goes to /profile (or any page using the profile template)
// this function gets run
if ( is_user_logged_in() ) {
global $current_user, $post;
$args = array(
'author' => $current_user->ID,
'post_type' => 'profile',
'posts_per_page' => 1
);
$my_query = null;
$my_query = new WP_Query($args);
if( $my_query->have_posts() ) {
while ( $my_query->have_posts() )
$my_query->the_post();
//We have a post! Send them to their profile post.
wp_redirect ( get_permalink () );
exit;
} else {
// If there are no posts, send them to the homepage
wp_redirect ( get_bloginfo('url') );
exit;
}
wp_reset_query();
} else {
// If they're not logged in, send them to the homepage
wp_redirect ( get_bloginfo('url') );
exit;
}
}
Then, on my profile template, I put this at the top with the opening php tag to run the function:
profile_redirect(); ?>
This is working for me, so I'll leave it as is for now :)