INSTRUCTION
stringlengths
11
999
RESPONSE
stringlengths
0
999
SOURCE
stringlengths
16
38
METADATA
dict
Advice: Template structure - php blocks in sidebar or someting else? I'm trying to create certain modulair blocks which I can add to multiple pages in Wordpress. But I use sidebar-[name].php files for this, what is the best practice for this? Should you add them to a function or add them in a sidebar... It feels Kinda off using many sidebar's. It would be nice if I could add them to a sub-folder in the template. Checkout the image. How do you do this? !enter image description here
I would say to add them as template parts as in content-[name].php. For instance in `page.php` you could have something like: <?php while ( have_posts() ) : the_post(); ?> <?php if (is_page( 'home' ) ){ get_template_part( 'content', 'benefits' ); } elseif (is_page( 'Contact' ) ){ get_template_part( 'content', 'contact' ); } } get_template_part( 'content', 'popup' ); ?> <?php endwhile; // end of the loop. ?> It seems to make more sense as it is content after all.
stackexchange-wordpress
{ "answer_score": 3, "question_score": 2, "tags": "functions, sidebar" }
WP Query / Meta Query How can I use a meta query like this: >>>>>> KEY_X Conditional IS ABSOLUTELY REQUIRED <<<<<<<<<< array( 'key' => 'Key_X', 'value' => 'Value_for_X' ), >>>>>> KEY_Y **OR** KEY_Z ARE REQUIRED / AT LEAST ONE <<<<<<<<<< array( 'key' => 'Key_Y', 'value' => 'Value_for_X' ), array( 'key' => 'Key_Z', 'value' => 'Value_for_Z' ) So the first one is an absolute must, and then one or the other is required (at least one). Thank you so much! Ciprian
Short answer: You can't do that. The query system is a simplified version, by design. It cannot do combinations of ANDs and ORs across keys like that. If you want to do that, you'll need to write your own SQL in some manner. The meta_query is not capable of that complex of a query.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "wp query, meta query" }
Strip Image Classes from HTML Output Does anyone know how to remove all of this from the image HTML? class="aligncenter size-full wp-image-31053"
Take a closer look at get_image_tag() which can take a lot of parameters like `$id`, `$alt`, `$title`, `$align`, `$size`. If you look even closer you'll find the `get_image_tag_class` filter to change the image class names (like class, ID, align and size). You can use the filter within your `functions.php` like this: Note: This will still return an empty tag like: `class=""` function strip_image_class($class, $id, $align, $size) { return ''; } add_filter('get_image_tag_class', 'strip_image_class', 0, 4); Update: To completely remove everything related to the class you'll have to filter the `$html`: function strip_entire_image_class($html) { return preg_replace('/ class="(.*)"/', '', $html); } add_filter('get_image_tag', 'strip_entire_image_class', 0, 4);
stackexchange-wordpress
{ "answer_score": 3, "question_score": 2, "tags": "php, images" }
esc_url returns incorrect URL What would be the reason for `<?php echo esc_url( home_url( '/' ) ); ?>` to be sending me to an incorrect website? I use it in my search bar and when I search a value it sends me to one of my other websites, but I am not sure what I did to make this happen.
It ended up being something very easy, but something I overlooked. Since I always use `<?php get_search_form(); ?>` for my search forms, I naturally assume that in my section template for the search area, I was using that, but I was not. I built the theme custom off of another theme I built for a different website and for some reason in the form's `action=""` I hardcode the url for the first site; that is why I kept getting forwarded there. I thought I checked the section, but must have overlooked it. After two days or so, I decided to re-check the section, thanks to the suggestions in the comments which made me re-think the problem. So yeah, really stupid brain fart, but it is now solved.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "php, search" }
Wordpress Translate Explaination I'm dissecting Wordpress's default theme TwentyThirteen in attempts to learn more about wordpress. I ran into a function call that I simply don't understand even after reading the short codex description. I would greatly appreciate insight on why the programmers/developers decided to format the edit link in this way. edit_post_link( __( 'Edit', 'twentythirteen' ), '<span class="edit-link">', '</span>' );
We have two main functions for translations, `_e()` and `__()`. The first _prints_ the value, and the second _assigns_ the value. As we are feeding a value to a function, we don't print or `echo` (the `e` in the function) anything, so we use the assignment function `__()`. What happens is that `edit_post_link` will receive the translated string for `'Edit'`. As for the function, `edit_post_link($link, $before, $after)`, we could do something like: edit_post_link( 'Edit this', '<strong>', '</strong>' ); And it would make the edit link with a custom, untranslatable, string in bold. To learn more you can dig in the archives of this site.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "functions" }
Updating a live theme safely? Apologies for the general question, but I spent some time looking for an answer and couldn't find anything. I often find myself in a situation where I need to make tweaks to a live site based on a client's feedback after going live, so I'm wondering the best way to quickly make changes on the live site without disruption. Presumably it's possible to duplicate the live theme, rename it in style.css so that it's considered a 'new' theme yet still uses the same database etc. and then work on that? The question is, how would I view that new theme and then switch to it once all updates are done? One day, I'll need to get my head around GIT as from what I've heard that would solve this kind of problem in a very safe way.
As far as my understanding you want to make changes in the theme without affecting the main theme so For this purpose the best practice would be creating child theme. So you can edit this child theme and your main theme will be safe. So, you can update the theme safely. Refer to WordpressCodex on creating child theme. Hope this solves the problem.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "theme development, updates, duplicates" }
wp query by search in titles only & put the posts in loop i need to get posts by search in posts title only not search in full post & put the posts in loop to show it in a slider **Note : i need to get posts by keyword in title & put it in loop to showing it, not limiting search in all of the site** i used `wp_query` to do that but it is get posts by searching in full post "content&title" <?php $query = new WP_Query( 's=mykeyword&cat=22,32&order=dsc&showposts=6' ); ?> <?php if ( have_posts() ) : while ( have_posts() ) : the_post(); ?> <p><?php the_title(); ?></p> <?php endwhile; ?> <?php endif; ?> how can i do that
If you want to limit the filter from this answer (add that function to your plugin or your theme’s `functions.php`) just to one query, remove the filter when you are done: add_filter( 'posts_search', '__search_by_title_only', 500, 2 ); $query = new WP_Query( array( 's' => 'mykeyword myotherkeyword', 'cat' => array( 22, 32 ), 'orders' => 'DESC', 'showposts' => 6 ) ); remove_filter( 'posts_search', '__search_by_title_only', 500 ); if ( $query->have_posts() ) : while ( $query->have_posts() ) : $query->the_post(); the_title( '<p>', '</p>' ); endwhile; wp_reset_postdata(); endif;
stackexchange-wordpress
{ "answer_score": 5, "question_score": 1, "tags": "wp query" }
redirect attachment page to category page I'd like to prevent google from indexing my attachment/image pages. So for the images I placed in my posts that's no problem - I just redirect the attachment page to the post parent by creating a new file "image.php" with this code `<?php wp_redirect(get_permalink($post->post_parent)); ?>` The problem is though that I got images in my category descriptions, which don't even have a post parent, so the redirect doesn't work. Is there a way that I can redirect the attachment page to the category page that has the picture in its description? Or maybe a way I can put all my attachmentpages on noindex?
The best way for this is either use: Attachment Pages Redirect plugin or use Wordpress Seo. You can use Attachment pages redirect to redirect the attachment pages to post page or home page. And also you can use WordPress SEO to redirect to homepage. Hope this worked.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "redirect, attachments, noindex" }
Search for pages with permalink I'm searching for posts this way $args = array( 'name' => $permalink, 'post_type' => 'page', 'post_status' => 'publish', 'posts_per_page' => 1 ); $posts = get_posts( $args ); This works great for "page1" and "foo/page2" when I put "page1" and "page2" respectively in `$permalink`. How can I craft a query to work for the case with where I want to search for "foo/page2"? **edit** i want to get the post object so that I can retrieve some data from it.
If I understand well (and I'm not sure) probably you need only the `get_page_by_path` function: $pagefoo = get_page_by_path('foo/page2'); `$pagefoo` variable contain post object for the page with slug `'page2'` that is child of page with slug `'foo'`.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "wp query, get posts" }
Use Filename for Alt and Title Tags I currently name all of my image files like this: Earth the Blue Planet.jpg Which when uploaded gets changed to this: Earth-the-Blue-Planet.jpg I was wondering if it is possible to have the image's alt and title tags render like this using the filename when adding them to posts: alt="Earth the Blue Planet" title="Earth the Blue Planet" I know the title tag shouldn't be used like that, but I'll just be using the filename as a base to add in the information I want. This would just make it easier. Thank you so much! I love this place for all my Wordpress questions!
The `alt` tag already takes the filename but if for some reason you need to replace hyphens with spaces and include a duplicate title of the alt tag you can do something like: function wpse_120228_seomadness($html, $id, $caption, $title, $align, $url, $size, $alt) { $alttitle = str_replace('-', ' ', $alt); $img = get_image_tag($id, $alttitle, $alttitle, $align, $size); $html = '<a href="' . esc_attr($url) . '">' . $img . '</a>'; return $html; } add_filter( 'image_send_to_editor', 'wpse_120228_seomadness', 10, 9 ); This will only affect images inserted into the editor after the code is added and not images already on your site.
stackexchange-wordpress
{ "answer_score": 2, "question_score": 2, "tags": "php, images" }
Determine if get_the_image has image on Get the image Plugin is there a way / function to determine if Get the image plugin successfully grab the image from post? Something like has_post_thumbnail on WordPress featured image. I need to know if featured image exist, since other HTML elements (position absolute) / depend on the Featured image for positioning. Thanks.
You can just run a conditional check on the result of `get_the_image()`. Either it will have returned an image or not. if ( function_exists( 'get_the_image' ) ) { $image = get_the_image(array('echo'=>false)); if( ! empty ( $image ) ) { // do something with the image } else { // do something if there is no image } }
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "plugins, images, post thumbnails" }
Is it acceptable for a WordPress theme to not accept widgets? I'm developing my own WordPress theme, and I was going through the Theme Unit Test as described by the Wordpress Codex. Now, at some point, the Codex mentions that I should verify that > All widgets display correctly Now, on the other hand, I have seen in the Widget help page that is instructed for users to verify if their theme supports widgets at all. So, **is it ok if my theme does not support widgets?** My goal is to have it published at some point and available to users through the Wordpress.org site, but since the design is quite minimal, I had decided not to support widgets. Am I asking too much?
It depends on where you distribute the theme. If you want to place it on WordPress.org, it must allow and display widgets. If you release it via your own website, or some others possibly, widgets can be optional, though I would always recommend they be supported.
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "theme development, themes, widgets" }
Cannot update user display_name field I'm trying to update user display name when posted through a form. Here's what I'm trying: if ( !empty( $_POST['display_name'] ) ){ //var_dump($_POST['display_name'] ); wp_update_user( array ( 'ID' => $current_user->ID, 'display_name' => esc_attr( $_POST['display_name'] ) ) ); } I can see that the display name is posted correctly, but it just does not update it. I can update the user url successfully but not the **display_name** and **first_name** / **last_name**. Is there any other way to update these fields?
This is because there is no **meta key** named **display_name** , so if you want to update a single meta value better use `update_user_meta` instead of `wp_update_user`, as **update_user_meta()** will create the meta field if it doesn't exist. like if ( !empty( $_POST['display_name'] ) ) { update_user_meta( $current_user->ID, 'display_name', esc_attr( $_POST['display_name'] ) ); } Then you can use the meta key and value the way you want.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 1, "tags": "plugins, user meta" }
add_action second argument missing I don't know what is missing here. I have a **do_action()** and **add_action()**. Only the first argument passed, to the function: function testing($a, $b) { echo $a . $b; // Here is just get A, and an error for missing $b } $a = 'A'; $b = 'B'; do_action('test', $a, $b); add_action('test', 'testing');
You have to say how many parameters your callback function needs. The default is 1, so WordPress will pass just `$a`. To get more parameters, use the fourth argument for `add_action()`: add_action('test', 'testing', 10, 2 );
stackexchange-wordpress
{ "answer_score": 3, "question_score": 0, "tags": "hooks, actions" }
woocommerce Add custom field set like billing fields I am working on E-commerce functions where i require to Add custom fieldset as Profile Fields the fields in it are as billing Below are the Fields that is needed in My Check out and signup form profile_first_name profile_last_name profile_company profile_address_1 profile_address_2 profile_city profile_postcode profile_country profile_state profile_email profile_phone Can you please guide me on this issue how can set add all above fields in my wordpress theme and what Actions or Filters should i use to display in Checkout form Thanks in Advance Nikhil
The "Customizing checkout fields using actions and filters" page in the WooCommerce Codex might help you.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 1, "tags": "customization, themes, plugins, e commerce" }
Completely disable categories Is anyone aware of a plugin that disables categories in WP? By this, I mean completely hiding the feature from view automatically, for existing and new users alike. In particular: * the WP admin menu * the posts list, its screen options, and its filters * the post editor and its screen options * the widgets screen * the writing and permalink settings screens I've run into a variety of aging hacks to do part of this, namely and mostly code to disable meta boxes and a handful of plugin to disable the permalink prefix. I'm turning to SO in the hopes that some web designer or developer might have the entire set of features on hand. If not, might there be new APIs from the past 3-4 years that make the process simpler (my WP skills are getting rusty), or is seeing it through going to be an awkward output buffer manipulation-related hack?
With most credit due to this stackexchange answer: function wpse120418_unregister_categories() { register_taxonomy( 'category', array() ); } add_action( 'init', 'wpse120418_unregister_categories' ); This technically leaves everything in place (so you could bring it back at any time without a loss of data), but it "unhooks" it from everywhere in the admin by removing it from all `$object_type`s. * * * UPDATE And to get rid of the Widget, add this to the function above. unregister_widget( 'WP_Widget_Categories' );
stackexchange-wordpress
{ "answer_score": 10, "question_score": 5, "tags": "categories" }
save_post action firing before I publish / save the post I'm trying to update a posts meta only after it has been saved or updated. My function is pretty simple function update_test( $post_id ) { update_post_meta($post_id, 'copied', '1'); update_post_meta($post_id, 'blurb', 'this value updated by save_post action'); } add_action( 'save_post', 'update_test'); When I add a new post at `wp-admin/post-new.php` I can see the two custom fields values have already been updated. The fields themselves exist with Advanced Custom Fields. But shouldn't be updated until after the post has been published / saved and or updated. Why is this updating the fields as soon as the post-new.php form loads?
A draft or "blank" is saved as soon as you start to create a new post. Those new posts have the `post_status` of `auto-draft`. Check for that to prevent your callback from firing on those "blank" post saves. function update_test( $post_id, $post ) { if (isset($post->post_status) && 'auto-draft' == $post->post_status) { return; } update_post_meta($post_id, 'copied', '1'); update_post_meta($post_id, 'blurb', 'this value updated by save_post action'); } add_action( 'save_post', 'update_test', 1, 2); You may also want to check for the `DOING_AJAX` and `DOING_AUTOSAVE` constants.
stackexchange-wordpress
{ "answer_score": 7, "question_score": 3, "tags": "save post" }
Rewrite rule for incoming urls **Part 1:** How do I get people visiting my blog with ` redirect to ` **Part 2:** What about when the incoming link is like this: `
This solved both parts: <IfModule mod_rewrite.c> RewriteEngine On RewriteRule ^archives/(.*)$ /\?p=$1 [R=301,L,QSA] </IfModule> The `QSA` flag maintained the query string automagically. **Most importantly** , I had to put it _above_ the existing WordPress rewrite rules in order for it to work.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "redirect, urls" }
Add item ONLY to the primairy navigation this code add the proper "home" to navigation... what i try to get is add home to ANLY the primairy navigation, how do i target the "main" only function new_nav_menu_items($items) { $lang = qtrans_getLanguage(); wp_nav_menu( array( 'theme_location' => 'primary', 'items_wrap' => '<ul><li id="item-id"><a href="$current_url">Home</a></li>%3$s</ul>' ) ); $homelink = '<li class="home"><a href="' . home_url( '/' ) . $lang. '">' . __('Home') . '</a></li>'; $items = $homelink . $items; return $items; } add_filter( 'wp_nav_menu_items', 'new_nav_menu_items' );
i did find my answer here : < add_filter( 'wp_nav_menu_items', 'your_custom_menu_item', 10, 2 ); function your_custom_menu_item ( $items, $args ) { if (is_single() && $args->theme_location == 'primary') { $items .= '<li>Show whatever</li>'; } return $items; }
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "menus, navigation, homepage" }
Retain select value in select box How are you all. I am just struggling to make my custom select box keep retain select value in form when page is reload or user come on form via different navigation. my select box is: <?php $args = array('post_type'=> 'portfolio', 'posts_per_page' =>100, 'offset'=> 0); $myposts = get_posts( $args ); foreach ( $myposts as $post ) : setup_postdata( $post ); ?> <option value="<?php the_title(); ?>"><?php the_title(); ?></option> <?php endforeach; in Core Php I know how to do this but in wordpress I am displaying post name in selectbox, so how can i achieve this, help would be appreciated....Thanks
If I have understood correctly, you could use get_the_ID() and compare the value with get_queried_object_id() to archive this: $args = array( 'post_type'=> 'portfolio', 'posts_per_page' =>100, 'offset'=> 0 ); $myposts = get_posts( $args ); $current_id = get_queried_object_id(); foreach ( $myposts as $post ) { setup_postdata( $post ); printf( '<option%s>%s</option>', ( $current_id == get_the_ID() ) ? ' selected="selected"' : '', get_the_title() ); } * * *
stackexchange-wordpress
{ "answer_score": 2, "question_score": 1, "tags": "posts, select" }
media page returnig to 404 in rtmedia I am using rtmedia plugin with buddypress plugin to uploading audio, video and image uploading. I am using latest version of both the plugins. But when I browse to media page(i.e < it returns to a 404 error, don't know what I am doing wrong. Please Help me.
I am from rtMedia Team, please try to fix your Permalink to ` hope it will solve your problem
stackexchange-wordpress
{ "answer_score": 0, "question_score": 1, "tags": "plugins, uploads, buddypress, media" }
What's $GLOBALS['wp_settings']['media']['embeds']? In `wp-admin/options-media.php`, there are a few lines that go: <?php if ( isset( $GLOBALS['wp_settings']['media']['embeds'] ) ) : ?> <h3 class="title"><?php _e('Embeds') ?></h3> <table class="form-table"> <?php do_settings_fields( 'media', 'embeds' ); ?> </table> <?php endif; ?> 'embeds' and "embeds" are nowhere else to be found in the WP code base. Might anyone know what it's for?
Per the two comments by Rarst and myself, the variable itself is is potentially populated by `add_settings_field()`, and the related logic is present for historical/backwards compatibility reasons. (There used to be fields in this area.) The related ticket and changeset for reference: * < * <
stackexchange-wordpress
{ "answer_score": 2, "question_score": 3, "tags": "core" }
Is there any plugin hook that I can latch onto once a site is freshly installed? To customize a fresh new WP install, there are a bunch of pluginable functions that can be overridden. Namely `wp_install()` and `wp_install_defaults()`. And `wp_new_blog_notification()`. I'd like to override a couple of default options without needing to keep custom versions of the latter in sync with core in my `wp-content/install.php` file. I'm not finding any obvious hook to do so in the `wp-includes/upgrade.php` file, however. Might I be missing anything? * * * Edit: so, the `pre_option_$option_name` is valid for options. Is there another, or some not-too-twisted procedure, that would allow to auto-enable permalinks, including (important) writing to the htaccess file as needed?
There are a couple of interesting hooks for use in an `install.php`: * `pre_update_option_{$option_name}` Generally useful to override defaults as they get stored. * `added_user_meta` Allows to disable the welcome screen But for heavy listing such as changing the default category's name, the default post and page, or changing permalinks, hooks are definitely missing. In particular, a bunch of options are added using `populate_options()`, and do so without any plugin hook whatsoever. I've opened a ticket requesting new hooks here: < The easiest in the meanwhile is to override `wp_new_blog_notification()` — the function is relatively simple to keep in sync with the WP core.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 2, "tags": "installation" }
URL of blog when using index.php as blog and front-page.php as homepage I am building a theme and I am using front-page.php for an individuall homepage and index.php (or home.php) for the blog. What is the URL of the blog / how its possible to define the URL of the blog?
Follow instruction for Creating a Static Front Page in Codex. The URL of your blog posts index will be derived from a page you use for "posts page".
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "blog, frontpage" }
How to include code into functions.php file via a plugin I have a lot of custom code in my functions.php file, what I would like to do is move all of this into a plugin for example myplugin-functions.php and then include the file into the themes functions.php file. Can I use hooks to do this or would I have to manually include the file. The reason I want it as a plugin is so that I can easily disable it without editing theme files!
You can directly create a plugin. Just copy all your codes and put it in a new folder. Plugin will call all the functions.
stackexchange-wordpress
{ "answer_score": 3, "question_score": 1, "tags": "plugins, plugin development, functions" }
How can i create a tag with the template's name like below, and what is the purpose of using them? I saw these in a lot of WordPress themes, what are they used for and how can I create my own? I mean for example the "twentythirteen" tag at the end, what contains the actual theme's name. get_comments_number(), 'comments title', 'twentythirteen' edit_post_link( __( 'Edit', 'twentythirteen' )
The code you posted is broken but what you are looking at-- that "twentythirteen"\-- is a "text domain" which is used for theme translation. The text domain is a kind of "Key" for locating the right translation data. That is, the first part, 'Edit' for example, will be translated based on the "twentythirteen" translation strings. # Reference: <
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "theme development" }
Add Title Attribute to WordPress Image the_post_thumbnail i use this code to show post's thumbnail in my site but this code cant show the title Attribute of the thumbnails. **how can i add Title Attribute to WordPress thumbnails?** <?php if ( has_post_thumbnail() ) { the_post_thumbnail('large'); } else {?> <img alt="<?php the_title(); ?>" title="<?php the_title(); ?>" src="<?php bloginfo('template_url'); ?>/img/thumbnail.png"/> <?php }?> you can see my site with this url : <
You can do that because you can add all the attributes you need: the_post_thumbnail( 'large', array( 'title' => get_the_title() ) ); Please read on in the Function Reference of the_post_thumbnail.
stackexchange-wordpress
{ "answer_score": 8, "question_score": 7, "tags": "post thumbnails, thumbnails" }
Send POST request to Wordpress to make a new post I want to make new posts on my Wordpress blog using HTTP POST sent to `post.php`. I was searching for the parameters I should pass but i didn't find any useful information yet. Can anyone give me a reference to the parameters I should send?
I would recommend using XML-RPC. You can find the documentation here. This is a more mature and secure approach than building your own functionality that already exists in core. You can find all of the methods for various operations here.
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "posts" }
get_post_gallery_images returns thumbs . I want full size I have the following code on my site. <?php // image gallery content if( has_shortcode( $post->post_content, 'gallery' ) ) { $gallery = get_post_gallery_images( $post->ID ); $image_list = '<ul id="cfImageGallery">'; foreach( $gallery as $image ) {// Loop through each image in each gallery $image_list .= '<li><img src=" ' . str_replace('-150x150','',$image) . ' " /></li>'; } $image_list .= '</ul>'; echo $image_list; } ?> My problem is that get_post_gallery_images returns thumbs files instead of fill size so Im using the str_replace function to solve it. How can I make to retrieve the full size urls? Thanks
If you're working within a template file, this code should work. However, I didn't test it. <?php echo do_shortcode('[gallery size="full"]'); ?>
stackexchange-wordpress
{ "answer_score": 2, "question_score": 6, "tags": "images, gallery" }
Set Custom Date for Posts I have a blog im working on in draft form. These blog posts are relevant to various days in the past few weeks but I would like to keep them hidden for the moment. When I publish one it gets todays date, is there a way to choose what date it has?
Yes you can put custom date by editing the `published on` date on the top right of the post/page edit. See the image attached for better understanding. !enter image description here
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "date" }
WooCommerce custom payment gateway I'm trying to write a WooCommerce plugin for a client's website that they're going to be selling subscriptions to customers. I've been exploring my options and the best one I can come up with is to roll my own payment gateway module to handle this. (Other advice appreciated if anyone's ever tackled something like this). However, I'm trying to add a custom payment gateway, but it doesn't seem to be working up. It's not showing up under `WooCommerce -> Settings -> Payment Gateways`. The plugin is installed and activated in WordPress, and I've followed a couple guides from their docs pages. * WooCommerce version: 2.0.18 (via plugin installer) * gist code I really don't know why or what would cause my payment gateway isn't showing up. Thanks for the future help.
Right, so the gist is your code; from your description I thought it was someone else's code you read for inspiration. Your woostripe.php file, which loads your gateway class, bails out before loading the gateway class: // bail on constructor if gateway class isn't loaded! if (!class_exists('WooStripe_Gateway')) return; // ... // why are you attempting to load WooCommerce's classes? Don't! include_once(dirname(plugin_basename('woocommerce.php')) . 'classese/abstracts/abstract-wc-payment-gateway.php'); // never gets here to load this class, you've already left this function... include_once(dirname(plugin_basename(__FILE__)) . 'classes/WooStripe_Gateway.php'); Remove the include statement for WooCommerce's class, that's WooCommerce's job not yours. Then move your WooStripe_Gateway include to the top of `woocommerce_gateway_init()` **before** the test to see if it exists. That class cannot exist until it is loaded.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "plugin development, plugins" }
How to disable core and plugin updates Is there any way to disable core and plugin updates? I am modifying a plugin and bit of **WordPress Core** (I know its a sin to do so), but can't help it.
Yes you can do that… define( 'DISALLOW_FILE_MODS', true ); Put this snippet in your `wp-config.php` file and you will able to disable core and plugin updates.
stackexchange-wordpress
{ "answer_score": 9, "question_score": 10, "tags": "plugins, core, automatic updates, core modifications" }
How to redirect to post if search results only returns one post I want to send visitors to my search.php after a search to display list of posts. If there is only one search result, user can directlyto the post in question(something like GOOGLE's I am Feeling Lucky Button) Thank you all.
Add this snippet to your functions.php function redirect_the_single_post() { if (is_search() && is_main_query()) { global $wp_query; if ($wp_query->post_count == 1 && $wp_query->max_num_pages == 1) { wp_redirect( get_permalink( $wp_query->posts['0']->ID ) ); exit; } } } add_action('template_redirect', 'redirect_the_single_post' ); hope this will help you!!
stackexchange-wordpress
{ "answer_score": 12, "question_score": 8, "tags": "functions, templates, search" }
Creating Custom user type just like custom post How to create custom user types (User Role) just like the custom post types. For example: User Role 1: Having a normal profile field. User Role 2: Having 3 extra fields in the profile. 2 different set of users with different user_meta fields.
Well, Roles are in many ways custom user types and you can add meta fields specific to roles. For example... function is_my_user_role($id = null) { global $profileuser; if (empty($profile) && !empty($id)) $profileuser = get_user_to_edit($id); return (in_array('myrole',$profileuser->roles)) ? true : false; } function my_user_fields($profileuser) { if (!is_my_user_role()) return false; // HTML for the fields } add_action('show_user_profile', 'my_user_fields'); add_action('edit_user_profile', 'my_user_fields'); And essentially the same check when you go to save the data.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "users, user roles, user meta" }
"The package could not be installed" when updating plugins, themes, and core files on WampServer Whenever I update anything on my local WordPress development site, whether it be plugins, themes, or the WP 3.7.1 update, I get this error message: > Unpacking the update… > > The package could not be installed.: PCLZIP_ERR_BAD_FORMAT (-10) : Unable to find End of Central Dir Record signature > > Installation Failed I'm using WampServer 2.4, with Apache 2.0.63, PHP 5.2.11, and MySQL 5.0.88.
I had same issue today on my new server. After a while i realize that zip/unzip is not active in my apache/php . When i recompile my apache with zip extension , problem solved.
stackexchange-wordpress
{ "answer_score": 2, "question_score": 1, "tags": "updates, upgrade, localhost, local installation" }
How would go about if I just want a temporary function? **How would go about if I just want a temporary function?** (It's a converter just for converting Access to Wordpress tables). I want to execute several times so therefore I want it automated, but I don't know how to execute the function after adding the filter in add_action(). After I'm done converting, I will delete the function. I want to do something like ` function addcoursecategoriesfromaccess() { //code for converting the table } add_action('convert','addcoursecategoriesfromaccess'); //If I type then I want the addcoursecategoriesfromaccess() to execute if ($_REQUEST['GET'] == 'convert') { do_action('convert'); } I guess I'm missing something very simple, but as a newbie in WP-programming I hope you can help me out :-) I've the code inside functions.php in the theme.
Use e.g. the init hook instead. For instance;: if (isset($_GET['convert'])) add_action('init', 'yourfunction'); (Come up with a better check, though. ?convert could mean anything. And secure it by checking for user permissions, that it hasn't already run, etc.)
stackexchange-wordpress
{ "answer_score": 2, "question_score": 1, "tags": "functions, customization, filters, actions" }
Get all woocommerce comments/reviews What I need to achieve is to get all comments from all products in Woocommerce. This is not getting me ANY comments at all... <?php $comments = get_comments( array( 'post_type' => 'product') ); ?> However <?php $comments = get_comments( array( 'post_id' => '4169') ); Gets me comments for particular product ID. How to query ALL comments? Thanks in advance.
Please try this: $args = array( 'number' => 100, 'status' => 'approve', 'post_status' => 'publish', 'post_type' => 'product' ); $comments = get_comments( $args ); where you can edit the number of comments to your needs. ## Debug: Maybe something is changing it via the `pre_get_comments` hook? To debug it you can check out the SQL query with: global $wpdb; printf( '<pre>%s</pre>', $wpdb->last_query ); where you add this directly below the above `get_comments()` code snippet. Also check the `edit-comments.php` screen if the comments show up there and their status.
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "plugins" }
How to create a page template using custom plugin I am building a plugin. I just want to create page template whenever i install plugin. Page template like full-width template. I have used codes after searching but not able to get success. So please help me. Thanks in advance
If what you want is to actually generate a page template when the plugin is activated, you can use something like this: <?php /** * Plugin Name: Testtest * Description: Ignore * Version: 0.1 * Author: windyjonas */ function myplugin_activate() { $buf = "<?php\n" . "/*\n" . " * Template Name: generated template\n" . " */\n" . "?>\n" . "Hello world\n"; $handle = fopen( get_stylesheet_directory() . '/tpl-plugin.php', 'w' ); fwrite( $handle, $buf ); fclose( $handle ); } register_activation_hook( __FILE__, 'myplugin_activate' ); This only works if the web server user has enough privileges to write to theme directory.
stackexchange-wordpress
{ "answer_score": 1, "question_score": -1, "tags": "plugins, plugin development, page template" }
Yet another get_posts() in explicitly defined order problem I am creating a 'loop' that needs to display _pages_ (not posts) in a defined order of ids. What I did till now is: <?php $ids = array(434, 814, 3660, 3235, 99, 1002, etc.); add_filter('posts_orderby', 'enforce_specific_order'); function enforce_specific_order($orderby) { global $wpdb; $ids_as_text = join(",",$ids); return "FIND_IN_SET(".$wpdb->posts.".ID, '".$ids_as_text."') ASC"; } global $post; $args = array( 'posts_per_page' => 20, 'post_type' => 'page', 'post__in' => $ids ); $myposts = get_posts( $args ); foreach( $myposts as $post ) : setup_postdata($post); ?> <h2><?php the_title(); ?></h2> <?php endforeach; remove_filter( current_filter(), __FUNCTION__ ); wp_reset_postdata(); ?> I can see the pages titles correctly displayed but not in the order I am expecting based on the `$ids`. Any idea?
Instead, you should use WP_Query Something like so: $specific_order_pages_query_args = array( 'post_type' => 'page', 'post__in' => $ids, 'orderby' => 'post__in' ); $specific_order_pages_query = new WP_Query( $specific_order_pages_query_args ); WP_Query's order value `post__in` is a special value to order by the supplied `post__in` ID's See more under Order in WP_Query <
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "get posts, order" }
Woocommerce, ordering products by default on shortcode pages In my woocommerce store I have a Sale Products page. In this page I use the shortcode to display the products on sale [sale_products per_page="40" columns="3"] In the store the products are ordered according to their position in a list in the backend (accessible via the Products->sort products link). This sorts them on normal category pages but on a shortcode page they are sorted by title. I know there is an `orderby` attribute I can add but is there an argument that will achieve this?
You can try to order by `menu_order` like this: [sale_products per_page="40" columns="3" orderby="menu_order"] if the corresponding callback is using `WP_Query()` to query the products.
stackexchange-wordpress
{ "answer_score": 2, "question_score": 1, "tags": "shortcode, plugins, sort" }
Add function to add element on all page I would like to add a function to add for example a link in the top and in the bottom of all my pages. The best would be to create a plugin in order to activate or disable it. Thank you so much.
To do this you have to create a function in your plugin. To have it display only to logged in users use: if (is_user_logged_in()) { then use the wp_head and wp_footer links to add actions to display the link you want, ie: add_action('wp_head','your_function'); add_action('wp_footer', 'your_function');
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "functions" }
WordPress filtering utm_ GET variables from url unless logged in as admin, not sure why? So I am having an issue where I can't pull variables such as mysite.com/?utm_campaign=testing unless I am logged in as admin or editor. When logged out and just a regular users I can't grab any variables which start in utm_ such as utm_campaign. However utmcampaign works, and any other variable I try. Just not utm_ ones. I disabled all my plugins but still have the same issue. Not sure where the filtering is coming from and not sure why it only filters when not logged in as admin. I tried accessing the variable using three different methods: 1\. Injecting PHP code using the "Code Insert Manager" plugin <?php echo $_GET['utm_testing']; ?> 1. Using the built-in function of formidablepro to grab the GET variables. 2. Using the same code as #1 but inside my footer.php file of my template. All have same results.
It's not a core behaviour to overwrite the global $_GET array, which means it's likely that something else then WordPress itself is the issue here. I would suggest the following steps to debug the issue: * Disable all active plugins and revert to standard theme, see if the problem persists. * If the problem is still there, open the `index.php` in your document root and write `var_dump($_GET); exit();` in the first line to see if the variable is making it through the webserver. If it isn't showing up now, it means that it is filtered for some reason by the webserver (i.e. bad .htaccess rule, or conflicting mod_security rule).
stackexchange-wordpress
{ "answer_score": 1, "question_score": 3, "tags": "variables" }
How do I display the text inside the WP editor for a page with a custom template? I am working in a Child theme on a page with a custom template. That custom template is not displaying any text that I enter into the wordpress editor. How do I "call" that text and display it in my custom template? Is there something like <?php get_editor_text(); ?> I just need a way to display the text inside the editor box on the custom teplate page. How would I accomplish this in wordpress?
I was able to fix my problem. In order to access the content I used -- <?php /* Start the Loop */ ?> <?php while(have_posts()) : the_post(); ?> <?php the_content();?> <?php endwhile; ?> By adding that snippet of code directly into my template page I was able to easily add the content from the visual editor. I had attempted to use "the_content()" but this was nonfunctional because I was not within the loop. The loop is an integral part of Wordpress and more information on the Loop can be found at < .
stackexchange-wordpress
{ "answer_score": 3, "question_score": 3, "tags": "page template, editor" }
Empty folder being created by Wordpress, breaks site I have a page on my site at mysite.com/publish. This page leads to a members area where they can add/edit posts from the front end. For some reason, randomly as far as I can tell, Wordpress keeps adding an empty folder to the same folder that Wordpress is in. For instance, my WP install is in a sub-directory called wordpress-2013 which is inside my main public directory. Inside that main directory an empty directory called "Publish" keeps being created so when someone tries to visit mysite.com/publish an error is given because of that folder. I'm not sure where to even start figuring out what might be wrong. Anyone have any ideas? I found a couple threads on here from about 4 years ago that either didn't have answers or did not apply to the current WP version. Thanks in advance.
I figured it out. I had a sub-directory set up with my hosting cPanel that I had completely forgotten about from long ago. I got rid of that and this is now fixed.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 1, "tags": "redirect, directory" }
Edit different parts of a page seperately I'm an experienced PHP developer without a lot of wordpress knowledge (yet!). I have to put together a fairly simple Wordpress page in the next few days. To get started I need to create a custom home page that will pull in content from three other discrete parts and present them in one layout. I'd like to structure it so that on the administrative end you'd have three different pages or posts to edit and the content (an image, some copy, and a link) from each would get pulled into the front page and presented there. What technique should I research for this? A custom page template? Custom fields? Any help is appreciated.
So after a few hours of research I implemented a solution using custom fields. To design my fields and apply them only to certain pages, I used the Advanced Custom Fields plugin. with this I created a set of custom fields for each page type that I needed to which I needed to attach specific content. Then I created a custom template for each of those pages in my theme directory, in which I access those custom fields with a simple call to the_field() function and process them for display. Wordpress made it very easy!
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "custom field, page template" }
How to show more than 10 order on woo commerce order view I am trying to get orders by user id. I have tried this and not working. <?php echo do_shortcode("[woocommerce_view_order per_page='20']"); ?> is there any way to put pagination to show all of order history? I also wonder which file, function I need to modify if I want to add "see more" button at the bottom of the order page show 10 each when it's clicked. we may work on "see more" button with ajax. Thanks,
It appears the shortcode uses the key `order_count` and not `per_page`. You can modify this on the View Order page, where the shortcode exists. [woocommerce_view_order order_count="20"] ~~If you would want some kind of AJAX order loader you may have to make some significant changes.~~ A note `order_count` also accepts the parameter `all` which will get all orders. Perhaps that is a solution? **EDIT:** The shortcode uses the template file `myaccount/my-orders.php`. You could modify this to look through a certain amount of orders, seperate them into seperate divs and have it show the additional divs with each button press. It is also in this template file where they actually get all the orders, so you could add a `paged` parameter to this and quite easily do the AJAX content load.
stackexchange-wordpress
{ "answer_score": 1, "question_score": -1, "tags": "plugins" }
Adding a custom button to WordPress Add Post (and Edit Post too) screen, that can save the post I am writing a plugin that hides the publish box from authors, so that I can have them click on a button in a custom meta box I created, to save their post. (This is not the sole purpose of the plugin, rest, I can't share. But this step is needed to do the rest.) I want WordPress to save the post to DB as it normally would, when I click on that button. How do I invoke WordPress' post save action from a custom button?
Well, the solution couldn't be more obvious. The Add New Post screen is a one big form. Any `<input type="submit"/>` element you put in it will save the post.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "plugin development" }
Display Post Meta in Header I'm trying to get page post meta in my header so I can set some meta tags. I tried to get the global post variable but it only return true. <?php global $post; global $wp_query; echo print_r($post); echo print_r($wp_query->post); die(); ?> All I get is `11` \- is there a way to get my post meta in the header?
Use `get_the_ID()`, the post object is not set up completely on `wp_head()`: if ( is_singular() ) $post = get_post( get_the_ID() );
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "post meta, globals" }
Opening Menu link in another tab I am adding a link to my Menu: !enter image description here !enter image description here Everything is working correctly except I would like the link to open in another tab and can't figure out how to. How would I do this?
When in the `Appearance > Menus` admin screen, click the `Screen Options` tab in the upper right corner, then under `Show advanced menu properties` tick the `Link Target` box. You'll now have a check box for each menu item labeled `Open link in a new window/tab`. That said, many people these days do not take kindly to this sort of behavior. I think best practices are to let the end user decide how new links open via their own browser preferences.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "menus, links" }
get_terms function not returning anything This has had me baffled for days so any help would be appreciated. I cannot get the function `get_terms` to return anything. I've tried the following code in the **index.php** , **single.php** and **page.php** , inside and outside the loop, of the default Twenty Thirty theme as well as my custom theme and no category terms are returned. I've created 10 test category terms and applied them to different test posts and still nothing. It's not working on the live site or the local development site. I've also tried flushing the rewrite rules by going to the Permalink Settings page and re-saving, just to see if that helped. Researching and finding any similar problem online has the same answer: add the `hide empty` part. So I did, to no avail. Any ideas why this function would not be working? `<?php get_terms("category") ?>` `<?php get_terms("category", array("hide_empty" => 0)) ?>`
`get_terms` just returns an array of terms, it doesn't generate output. You have to do something with that array to see the results- $categories = get_terms( "category" ); echo "<ul>"; foreach ( $categories as $category ) { echo "<li>" . $category->name . "</li>"; } echo "</ul>"; See the other examples on the Codex page.
stackexchange-wordpress
{ "answer_score": 3, "question_score": 0, "tags": "categories, taxonomy, terms" }
Display my plugins content based on a pages post_id I have created a plugin that has the frontend content in a file named showmap.php, I currently have a shortcode that includes the contents of showmap.php on the page the shortcode is placed. I addition to the shortcode, I have created an option to allow the user to choose a page to include the content on. The reason is that I have a search widget that needs to post to that page so I had to have a way of detecting it. $db_showmap_options = get_option( 'db_showmap_options' ); $chosen_page = $db_showmap_options['page_id']; How do I detect the chosen page and include showmap.php? Do I have to take permalinks into account. I'm afraid I'm really lost on this one. Thanks in advance for any help.
How you do this could be more or less hard depending on where the content is supposed to be included in the page, and you don't explain that, but assuming you are including it in the post body... add_filter( 'the_content', function($content) { global $post; $db_showmap_options = get_option( 'db_showmap_options' ); if (!empty($db_showmap_options['page_id']) && $post->ID == $db_showmap_options['page_id']) { $content = "whatever you need to do".$content; } return $content; } ); Untested but I am fairly sure that will work. You may need output buffering, depending on how your `showmap.php` is written.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "plugins, plugin development" }
Cant' Grab WordPress Built-in Posts Through Loop Using WordPress 3.7.1 I am trying to display all Regular Post on my created page lest say TestPage. Here are the steps I took to do this: **1-** Generate a Custom Page Template called:Test Page and loaded by following code **2-** Generate a Page Called TestPage based on Test Page Template after updating the page I am not getting any of Post on the page while I have already generated some! <?php /* Template Name: Test Page */ ?> <?php get_header(); ?> <?php if ( have_posts() ) : while ( have_posts() ) : the_post(); ?> <h1><?php the_title() ;?></h1> <?php the_content(); ?> <?php endwhile; else: ?> <p>Sorry, this page does not exist</p> <?php endif; ?> <?php get_footer(); ?> he abouve code actually is loading the page whit title and content of the TestPage and not by Posts!Can you please let me know why this is happening?
> Can you please let me know why this is happening? A loop like yours assumes the data from the "main query". You've created a custom page template so the main query on that page is going to be the single "TestPage" data. That is the way it is supposed to work. That is, `if ( have_posts() ) : while ( have_posts() ) : the_post();` doesn't always give you the post archive data. To get the posts you'd need to create a new query and loop over that. Like this: $newq = new WP_Query(array('post_type'=>'post')); if ($newq->have_posts()) { while ($newq->have_posts()) { $newq->the_post(); the_title(); } } You should probably look over the Template Hierarchy carefully, because this may not be the way you want to go about things at all.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "posts, plugin development, theme development, loop" }
dynamically update permalink and title with the values of custom fileds Im working on an interface for a custom post type where I need the post title to carry the date and venue name. So on the Admin end I've got js that dynamically populate the title as the user fills out the form. If the user dosen't languish this information is then saved as a part of the permalink. Sometimes however the post is saved as a draft before the title is populated and we end up with an misleading URL. My feeling is that it would be best I were to just hide the title all together on this post type, and look for a hook to populate the title AND rework the post url with the field values the user has set when saving the post. As of now I cant find any hooks or filters that look like they would be of help. !example screen shot Help?
You don't need to hide the title. To my knowledge there is atleast two way to do this, one is manual and other through codes. Manual way:-- After you are done with adding the title, if your permalink doesn't match the title just click on **permalink Edit** button clear the text and click **OK**. It will get you the permalink as per the title. Through Code:-- Put the below code in the theme's functions.php file. add_filter( 'wp_insert_post_data', 'wpse_121035', 50, 2 ); function wpse_121035( $data, $postarr ) { //Check for the post statuses you want to avoid if ( !in_array( $data['post_status'], array( 'draft', 'pending', 'auto-draft' ) ) ) { $data['post_name'] = sanitize_title( $data['post_title'] ); } return $data; } The above will automatically change the permalink of the post on the fly. For more detail on how you can use it follow this blog
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "custom post types, permalinks, title" }
how to show this part only in the single post page? I have this part in my index-meta.php file : <ul> <li class="Source"><a>source:</a></li> <ul class="Source-Link"> <li><a href="<?php echo get_post_meta($post->ID, 'source-link', true); ?>" target="_blank"><?php echo get_post_meta($post->ID, 'source', true); ?></a></li> </ul> </ul> this'll show the source of my posts based on the custom fields I've made, and I just want them to show in the content-single.php file, I mean the single posts page. but they also showing in front page (index.php, content.php), I dont' want that. what conditional can I use and how? please help me with this cause I'm pretty weak in php and wp...
You can use `is_single()` in a conditional statement. <?php if( is_single() ){ ?> <ul> <li class="Source"><a>source:</a></li> <ul class="Source-Link"> <li><a href="<?php echo get_post_meta($post->ID, 'source-link', true); ?>" target="_blank"><?php echo get_post_meta($post->ID, 'source', true); ?></a></li> </ul> </li> </ul> <?php }?> Be aware though that this will appear on any single page, meaning a single post page and a single page. <
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "custom field, post meta, conditional tags" }
Get value in custom field with taxonomy I have custom field `my_cf` for Taxonomy/Term. How can I get and output value with custom field for taxonomy/term? I've tried using: $variable = get_field('my_cf', 'basic'); echo $variable; where basic - name for my taxonomy. But this doesn't work. Any suggestions?
I can't really explain it any better than the ACF documentation page I posted in the comments: > All the API functions can be used with a taxonomy term, however, a second parameter is required to target the term ID. This is similar to passing through a post_id to target a specific post object. > > The $post_id needed is a string containing the **taxonomy name + the term ID** in this format: **$TaxonomyName_$TermID** So if your custom field is `my_cf`, and your taxonomy name is `basic` ( _not_ term name) and the term ID within your taxonomy is 42, then you need: $variable = get_field( 'my_cf', 'basic_42' );
stackexchange-wordpress
{ "answer_score": 3, "question_score": 5, "tags": "custom taxonomy, custom field, advanced custom fields, terms" }
Storing values in Post Meta vs new tables I want to store list of user IDs in the post meta who have rated a post . So, for each post I will need to check the post meta to see if the user id exists in it or not. So my question is that, is it good idea to store that information in the post meta OR should I create a table and add it in the table. Will there be any difference in the performance (table vs meta) if the number of values grow very much? I would prefer to store in the post meta as it is much simpler and cleaner way, but I have read one answer which says > never, ever, ever, use an EAV (aka the post_meta table) to store data that you might to need to query.
Based on your comment: > when a user clicks to vote, i get the value of that post meta and check if the user id exists in that (using php explode and foreach). If it does not exist then i add the user id in it. there's no query involved there, so it's perfectly fine to use post meta for that purpose. A query would be something like "load all posts from database where user with ID n has voted". That would be more difficult to achieve, as it's a many-to-many relationship, which WordPress doesn't do natively. Storing user IDs as serialized data (an array) is a PHP construct, MySQL doesn't "understand" that data natively, so that would not be a good use of post meta.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "plugins, plugin development, post meta" }
Get wp_get_attachment_url outside of loop I need to get the featured image outside the loop. This is so that I can have a different full-screen background image for each page, set by the featured image. After doing some research I was able to get the post ID outside the loop. This is what I've got: $page_object = get_queried_object(); $page_id = get_queried_object_id(); $bkgdImg = wp_get_attachment_url( $page_id ); if (!empty($bkgdImg)) { $backgroundImg = $bkgdImg; } else { $defaultbackground = . get_template_directory_uri() . "/images/default-background.jpg"; $backgroundImg = $defaultBackground; } echo $backgroundImg; Thanks!
if the result you're looking for is a printout of the URL, like in your example, then this should work: $page_id = get_queried_object_id(); if ( has_post_thumbnail( $page_id ) ) : $image_array = wp_get_attachment_image_src( get_post_thumbnail_id( $page_id ), 'optional-size' ); $image = $image_array[0]; else : $image = get_template_directory_uri() . '/images/default-background.jpg'; endif; echo $image;
stackexchange-wordpress
{ "answer_score": 8, "question_score": 4, "tags": "pages, query, attachments" }
Using post ID in custom tinyMCE button I'm building a simple plugin and need to be able to access current post id when user clicks custom tinyMCE button (inside its onclick function). How should I get current post ID to do that. Just for this example, code from this tutorial: < can be used, and after clicking on the button, current post id could be logged into console (console.log) or alerted to screen.
You would need to place a globally namespaced javascript variable in your php code where you enqueue the script to be loaded for the editor pages. So, this code will enqueue a script function to be added to the "edit post/page" screens: add_action('admin_head','my_add_styles_admin'); function my_add_styles_admin() { global $current_screen; $type = $current_screen->post_type; if (is_admin() && $type == 'post' || $type == 'page') { ?> <script type="text/javascript"> var post_id = '<?php global $post; echo $post->ID; ?>'; </script> <?php } } Now, in your editor_plugin.js file for your tinymce button; you can access this post ID by simply calling the `post_id` javascript variable.
stackexchange-wordpress
{ "answer_score": 3, "question_score": 1, "tags": "tinymce, plugin tinymce" }
Change appearance based on category but post is in two main categories I want to change header and menu based on what category a post is listed in. I could duplicate the post and assigned each of the two categories separately but this sounds messy and bleh. The post/s in this example belong in both "pirtek" and "btcc". < but the posts with pirtek need to be styled with custom header etc. (and eventually custom menu...which makes me think perhaps I should just duplicate for easy implementation of a seperate menu?) What do you think? As it stands my standard header is prioritised every time <php if ( has_category('pirtek') ) { $header = ' } else { $header = ' } ?>
One easy way is to use `has_category` function. E.g. in your header you can use if ( has_category('pirtek') ) { $header = '/path/to/pirtek/header' } else { $header = '/path/to/standard/header' } If the post has the 'kirtek' category, then the condition inside `if` is `true`, no matter what other categories the post belongs to. This kind of `if` statement can be used everywhere you need, however, the snippet above works well in singular templates and inside the loop. If you want to use that conditional outside the loop, you need to pass the post object as second argument of `has_category`. $postid = 10; if ( has_category( get_post($postid) ) ) { // do something }
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "categories, menus, headers" }
Trying to use WP_Query to display a custom post type I'm trying to use WP_Query in function.php to display a custom post type on a certain page. I just can't seem to get it to work, can anyone see issues with my code? nothing is output at all and there are apparently no errors. /*** add venues to venue page ***/ add_action( 'woo_post_inside_after', 'venue_loop' ); function venue_loop() { if ( is_page(123) ) { $args = array( 'post_type' => 'tribe_venue', 'orderby' => 'title', 'order' => 'DESC', 'posts_per_page' => 10 ); $venue_posts = new WP_Query($args); if ( $venue_posts->have_posts() ) { while( $venue_posts->have_posts() ) { $venue_posts->the_post(); $output .= '<li><a href="' . get_permalink() . '">' . get_the_title() . '</a></li>'; } } return $output; } }
Typically, you would be `echo`ing content from an action hook, rather than returning it, and from I can find about this Woo Theme hook that looks to be the case here too. Try `echo $output;` instead of `return $output;` See: Clarification on filters and hooks Difference Between Filter and Action Hooks?
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "wp query" }
Upon registration, redirect new user to Dashboard How could I redirect someone to the dashboard rather than the front end once they have registered on my site? **EDIT:** What I would like to do is to redirect someone to the Dashboard once they have signed in with their username and password. Many thanks.
Usually, WordPress redirects the user to the dashboard unless it is coded otherwise. Can you look for a function hooked to the filter **login_redirect** in your `functions.php` file. For details check the codex
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "user registration" }
SESSION in WordPress Plugin Development I wondering the session was disable in wordpress. I try to find some information on using session variables in the wordpress. I tried the following method to implement session variables in the wordpress site. I tried this way. <?php session_start(); $_SESSION['firstname'] = $_POST['firstname']; ?> If i echoing the `$_SESSION['firstname']` is not come's up. So I googled to find the reason why it doesn't support. function register_session() { if (!session_id()) session_start(); } add_action('init', 'register_session'); This above method i tried and implemented but it also doesn't work. Right now i integrating session in plugin so i don't want to edit the core file. Because i doing the custom plugin development. How to enable the session in wordpress plugin. Any Suggestion would be great Thanks.
Your code doesn't seem to be wrong, it's just how I would do it - see my answer here. So the question would be is your session getting started? Try debugging this: // do you have a session id $s_id = session_id(); print_r($s_id); // can you declare a bogus session variable, yours might just be empty $_SESSION['bogus'] = 'bogus'; print_r($_SESSION['bogus']); Another advisable step is to lower the priority of the `add_action()` call: add_action('init', 'register_session', 1); just to make sure you have your session ready before it's needed by another action/function.
stackexchange-wordpress
{ "answer_score": 4, "question_score": 3, "tags": "plugins, plugin development, session" }
Check if meta key value already exists Let's say that I have few posts with meta key "videoid". Value of that meta key is different for every post (and has to be different). When adding new post, how can I check if videoid with that exact value already exist for some older posts? I used this as a refference for adding custom meta box to admin area of WP: <
Just do a query with `WP_Query` using the Custom Field parameters (`meta_query`) to look for posts with the meta key and the value - exemplary code: // args to query for your key $args = array( 'post_type' => 'your_post_type', 'meta_query' => array( array( 'key' => 'videoid', 'value' => $new_posts_videoid // for example: '111' ) ), 'fields' => 'ids' ); // perform the query $vid_query = new WP_Query( $args ); $vid_ids = $vid_query->posts; // do something if the meta-key-value-pair exists in another post if ( ! empty( $vid_ids ) ) { // do your stuff } There is no need to use `query_post()` \- see: When should you use WP_Query vs query_posts() vs get_posts()? . If you need a complete array of post objects, not just the ids, remove `'fields' => 'ids'`.
stackexchange-wordpress
{ "answer_score": 7, "question_score": 2, "tags": "metabox, post meta" }
Custom fields in Permalinks? I'm wondering how to add a custom field value to a custom post type's permalink? For example, I have the custom post file ex: cpt-cities.php, which handles registering the custom post type and all of those specifics. Within that file, I'm trying to set it's permalinks to include one of the 'cities' custom field values. I'm able to set the permalinks using add_permastruct. However I'm not able to get the value of the custom field, and get_post_meta() does not work. This may be due to $post->ID not working (since it's within the custom post type file, and not a post loop). Anyone know of a way to get the custom field value within a file like this? Is there somewhere else I can declare the add_permastruct, that will allow me to pull in the custom field value? Any help is greatly appreciated, this is one of the last parts of a pretty extensive project.
1. Use `add_rewrite_tag( $tag, $regex );` to register a rewrite tag for the custom field. 2. Filter `post_type_link` to replace the rewrite tag. The second argument is the post object, so you have always access to the post ID. For a sample implementation see my plugin T5 Rewrite. It does exactly that in the class `T5_Rewrite_Tag_Custom`.
stackexchange-wordpress
{ "answer_score": 3, "question_score": 1, "tags": "custom post types, custom field, permalinks" }
Every time I de-activate a custom plugin, the site encounters a critical error I have a custom plugin that I no longer use. I was looking to de-activate it from my site (and, subsequently, my network) but every time I attempt to, I get this error: > Please activate the {plugin name} plugin with no further output from WordPress (it's just the text and nothing else!) I'm effectively locked out of everything on the web end with no options but to restore the DB to an earlier version. Has anyone ever experienced something like this before?
Your custom plugin is probably directly integrated into your theme or some other plugin. The developer must have added this notice to prevent you from deactivating by mistake the plugin and making your site behave in an unexpected way, this is not a notice issued from wordpress itself. You need someone to look into your plugins and theme code, check where this notice originates, and remove the dependencies.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "plugins, plugin development" }
Function naming convention While developing more and more customized Wordpress themes, I began adding more custom functions to my theme's functions.php file. While I try to make their names to be self-explanatory, I think this is not enough. Considering that you might not be the only web developer working on a theme, or that there might be somebody else who will be put in charge of continuing the development of said theme, I wonder, how should we name our functions to distinguish them from core WP ones? Edit: Re-worded the question **Q: Are there any patterns that help developers co-working on the projects namespace functions to avoid confusion whether they are native to Wordpress or not?**
I almost used the same convention as @GhostToas but to me I usually use classes to minimize conflict. For internal or company project: `class MyCompany_Classname {}` For Client specific project: `class ClientProject_Classname {}` Using a class will absolutely help you avoid conflicts and thus, you can name your function using generic function names. Say for example: class MyCompany_ThemeSettings { function saveSettings() { } function displaySettings() { } function getSettings() { } }
stackexchange-wordpress
{ "answer_score": 3, "question_score": 0, "tags": "functions" }
Edit draft from other author I need that editors in my blog can read and edit drafts from other authors. I've tried some access manager plugins: 1. Advanced Access Manager 2. User Role Editor But none of these helped me. I've also looked for similar questions like this and this, but again, nothing found. How can I do this? It is possible?
Please review the information here: < Specifically, the following: > Editor – somebody who can publish and manage posts including the posts of other users. An Editor is exactly that - someone who can edit what other people are doing. Ensure that the Users who you want to have Editor rights are assigned as Editors in the Users menu. If this doesn't answer the question, please revise your question with more information and perhaps this may also help understand a bit more: Allow Editors to edit pending posts but not draft ones
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "permissions, draft" }
Planned private posts get published immediately Somehow, it doesn't seem to be possible to plan post for my subscibers (visibility private) as they get published private automatically as soon as I save them. Is there any way I can keep wordpress from doing so?
The problem is that changing the post **visibility** to private invokes a **status** change, in a way private is not only a visibility but also a publishing status. Or to quote the **Wordpress Codex** , section »Content Visibility - Private Content«. > Once you change the visibility to private, the post or page status changes to "Privately Published" as shown. Private posts are automatically published (...). To achieve what you want you probably have to work with the publish_post or even better the publish_future_post hook. Another possibility is to work with Post Status Transitions and the according hooks.
stackexchange-wordpress
{ "answer_score": 3, "question_score": 1, "tags": "posts, private" }
Is there a way to verified if an add_filter is already applied? I have in my theme this filter: add_filter('widget_text', 'do_shortcode'); Now I'm developing a plugin where I have that same filter. I would like to know if is there a conditional that I can check if filter is already placed? I don't want to run it twice. I don't know if that may cause any problem. I just want to play safe.
<?php has_filter( $tag, $function_to_check ); ?> <
stackexchange-wordpress
{ "answer_score": 4, "question_score": 2, "tags": "plugin development, filters" }
Changing site_url domain breaks image links I am using Responsive theme from CyberChimps. I relocated the Wordpress installation on the same server by changing the Url from settings and renaming folder from FTP. Everything is loading, Wp-Admin, CSS, JS, Pages etc. except for a few images, including the site logo. I tried lot of solutions, clearing bowser cache etc. but it didn't worked out. I debugged it and when I go to customize.php, it shows the same old Url for website logo. Can anyone tell me in customize.php line 138, from where exactly its loading `$section->maybe_render();`? I can even see the logos in media library with updated domain. But apparently customize.php has either cached or for some other reason bound to old domain name.. Any suggestions?
This really has nothing to do with the theme customizer. From the Codex on moving WordPress : > Existing image/media links uploaded media will refer to the old folder and must be updated with the new location. You can do this with the Velvet Blues Update URLs plugin, or with a search and replace tool, or manually in your SQL database. The values in the database (where your logo's URL is stored... nor the URLs for images that are inserted into posts) are not automatically changed. These must be changed manually, or you can use certain plugins/scripts to automate the process. I have used both the Velvet Blues Plugin and the Serialized Search and Replace script with much success. If I had to pick, I'd say that Velvet Blues is easier to use for people who don't/can't do FTP access.
stackexchange-wordpress
{ "answer_score": 2, "question_score": 2, "tags": "domain mapping" }
How to create and use Custom hooks I am newbie in wordpress. I have just created contact us plugin for my own project. In my plugin I have used many functions you can take a look of my code. I want to make this plugin based on custom hooks instead of only PHP functions. I don't want simple plain php functions. Can you suggest me where can I add custom hooks and how to use it? I know how to add custom hooks and use it i have referred this document.. so I am clear with hooks (how to create it and use it)
Where to put hooks will depend on each project. However, some _basic places_ to think about: * Shortcodes * Querying posts * Extending markup I would recommend the article Writing Extensible Plugins With Actions and Filters. It may help you to expand your ideas.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "plugins, plugin development, hooks" }
How to handle a Wordpress blog with articles in different languages? Most multilanguage plugins have the approach to provide each post in different languages. In that case, qTranslate or WPML are good plugins. But in my case, articles have one language and instead of translating them, there should be versions of the blog showing only the content in one language. For example the `en.example.com` should only show posts written in English language, and also display Theme texts in English, while `de.example.com` should only show German articles and also use German as system language for Wordpress. (URLs could also have the language code in slashes instead of using a subdomain, like `www.example.com/en/`.) Is there a good solution for this use case? I could think of using a plugin or integrating the concept into the theme. Or is the best solution to set up one Wordpress installation for each language?
In most cases you are better with using two different installations or two different sites on a network installation. The only use case for the plugins is when you need almost all of your content to be translated or when you need good control over what was translated and what wasn't.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "plugins, themes, multi language, customization, language" }
How do I programatically insert a new menu item? I'm developing a plugin and I want to insert menu items programmatically. When my theme creates a menu, it uses this call: wp_nav_menu( array( 'theme_location' => 'primary', 'menu_class' => 'nav-menu' ) ); Which resulted in something like this in the HTML: <div class="nav-menu"><ul> <li class="current_page_item"><a href="somewhere">menu-item-1</a></li> <li class="page_item page-item-107"><a href="somewhere-else">menu item 2</a></li> </ul></div> I want to be able to intercept this somehow and insert my own HTML programmatically before the closing `</ul>`. How do I hook it up?
Before being printed, all the menu items get run through a filter. You can target the `wp_nav_menu_items` filter to tack things on to the menu: // Filter wp_nav_menu() to add additional links and other output function new_nav_menu_items($items) { $homelink = '<li class="home"><a href="' . home_url( '/' ) . '">' . __('Home') . '</a></li>'; // add the home link to the end of the menu $items = $items . $homelink; return $items; } add_filter( 'wp_nav_menu_items', 'new_nav_menu_items' ); Or, to be more specific, you can target only the desired menu by replacing the `add_filter` line from above with the following, and replacing `$menu->slug` with your menu's actual slug name: add_filter( 'wp_nav_menu_{$menu->slug}_items', 'new_nav_menu_items' ); Source Tutorial
stackexchange-wordpress
{ "answer_score": 20, "question_score": 8, "tags": "plugin development, menus" }
Should I escape the attributes when using get_month_link? I am not sure should I use `esc_attr()` with `get_month_link()` like this: <a href="<?php echo esc_attr( get_month_link( get_the_time('Y'), get_the_time('m') ) ); ?>"> <?php the_time( get_option( 'date_format' ) ); ?></a> Or should I code it like this (without escaping): <a href="<?php echo get_month_link( get_the_time('Y'), get_the_time('m') ) ; ?>"> <?php the_time( get_option( 'date_format' ) ); ?></a> So security wise which is the best option? Thank you.
Yes, escaping everything (and as close to output as possible) is a way to go. Right until the point excessive escaping is causing issues in specific circumstances. Note that while this happens in context of attribute, `esc_url()` is more fitting for URLs. > Always use esc_url when sanitizing URLs (in text nodes, attribute nodes or anywhere else). > > Codex > Data Validation > URLs
stackexchange-wordpress
{ "answer_score": 3, "question_score": 0, "tags": "date time" }
Combining external feed into post loop I don't even know where to start on this. I would like to combine an external JSON or XML feed into the post loop and sort it by date. The page will need to auto-load the next posts and have the ability to filter by category. I'm not sure if the best way to do this is to create a custom post type for this external feed and create a post for each item.
What I ended up doing was CURLing down the external feed and then merging arrays together.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "loop, feed" }
Display custom text when comments are closed When I close comments on a post it's showing "Comments are closed". Is there any way to edit this text and show a personal note instead of the pre-configured one? I would prefer to do this in a 'universal' type of thing, meaning that the same message would appear even if I change the wordpress theme.
If you go to `comments.php` in your theme - and search for "Comments are closed", you should find it. You should also be able do this in `functions.php`: function comment_text ($arg) { $arg['title_reply'] = __('Too Late - Comments are Closed!'); return $arg; } add_filter('comment_form_defaults','comment_text'); Edit: Just noticed that you want this to work cross theme. So if you go to: `wp-comments-post.php` in the top level of your Wordpress install, you should find it there too.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "comments" }
Comment form - different title if no comment yet this isn't major but would be nice. Would like to have 2 titles for the comment form, one that says "no comments yet start the discussion" and another that says "join the discussion". I've had a good look around but I can't see anything already posted about doing this. Can anyone assist? Skip. (I may use different phrases but you get the general idea I'm sure).
Use `get_comments_number()` to get … well … the number of comments. In your theme’s `comments.php` you can use its return value to do something: $num = (int) get_comments_number(); if ( 0 === $num ) echo 'Be the first! But please don’t write just “First!”'; elseif ( 100 < $num ) echo 'Yeah, add some noise. Nobody will read it.'; else echo 'Please write a comment';
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "comments, comment form" }
if the post has content I am setting up a one page WordPress site. I am getting some pages listed in my site that does not have content. For example, I will get the empty blog page as well as the blog template. So I thought I could throw in a check to see if the page has content and if it does go ahead and post that information. I am having trouble getting it to work. I am using a custom query for the homepage. So I thought I could do this if ( $page_query->have_posts() ) : while ( $page_query->have_posts() ) : $page_query->the_post(); if( $page_query->post_content != ''){ get_template_part( 'content', get_post_format() ); } endwhile; endif; problem is that I get an error on that code and I can't figure out why. I get this error > Notice: Undefined property: WP_Query::$post_content in
The content is a property of the `post` object, not of the query object. Use `$post` or `get_post()` instead: if( '' !== get_post()->post_content ) { // do something }
stackexchange-wordpress
{ "answer_score": 23, "question_score": 12, "tags": "content" }
Is it possible to add the_post_thumbnail to style.css? I'm wondering if it's possible to add `the_post_thumbnail` location to style.css. I'm using these images as backgrounds, and I can easily do that on the template, of course, but I'm thinking that for responsive design it would be way easier to simply add `the_post_thumbnail` location to style.css and then reference that location to serve the proper background to any given size instead of serving one giant image for (say) mobile devices. Is there a way to do this?
If you want to add background image you can do inline css in html PHP: <?php if(has_post_thumbnail()) { $desktop_src = wp_get_attachment_image_src(get_post_thumbnail_id(), 'desktop'); $ipad_src = wp_get_attachment_image_src(get_post_thumbnail_id(), 'ipad'); $mobile_src = wp_get_attachment_image_src(get_post_thumbnail_id(), 'mobile'); $desktop = 'style="background: url('.$desktop_src[0].');"'; $ipad = 'style="background: url('.$ipad_src[0].');"'; $mobile = 'style="background: url('.$mobile_src[0].');"'; } ?> HTML: <div id="desktop" <?php echo $desktop; ?>></div> <div id="ipad" <?php echo $ipad; ?>></div> <div id="mobile" <?php echo $mobile; ?>></div>
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "post thumbnails, css" }
Let users register weight each day and save it in DB I need a way that lets my users register they're weight (kg) and maybe % of bodyfat and save that information on each user in the DB. Then i need a way to output that number again on the logged in user What would be the easiest approach to do something like this?
I feel the best way to do is add two options `Body weight` and `Body fat(%)` in the user profile, and then you can show it with the user logged from the db. I guess this would be a simpler way.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "php, database, users, mysql, user meta" }
Author profile comments system I have a custom PHP file to get all the users/authors from the DB in WP, so it's all showing correctly and working BUT, I want to make the comment to work properly, what i did now is: <?php comments_template(); ?> I added the above line in the file, but the issue is that if i comment on one author the comment won't stay ONLY on his profile page, but it will publish in all the authors page, it's like the comment are not individual.... Any ideas how can i make the commenting work for each author separated from the other?
Comments are bound to post IDs. So you need a post ID for each user. Register a custom post type, make it not public and create one hidden post for each user. Store the ID in an user-meta field. Now assign the comments to that post’s ID. Do not use `comments_template()`. That’s an ugly monster, dealing with globals and way too complex to hack around. Fetch the comments with `get_comments()` instead. The print the comment form, add a hidden field for author archive URL, hook into `comment_post_redirect` and send the commenter back correctly.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "custom post types, plugins, theme development, comments" }
set cookies for my whole site is not working I'm trying to set the cookie to my site to **hide a div on click action**. Description of the problem. 1. I wanna set the cookie for the whole site not for particular page. I'm setting the cookie `on click` the div by > jquery-cookie.js 1. when I'm clicking the div on home page the div is invisible throughout the site. but if I'm trying to remove my div on other page it is not invisible throughout the site. 2. I've tried the following functions of the **wordpress codex** `site_url()` `get_site_url()` `home_url()` `get_option('home')` by these methods I've named the **domain** but it is not working. I've also tried `/` for the domain name it is also not working. these all are not working for me. please suggest me some other method to do that. My plugin site consist of 4 pages url as follows site/wordpress/ site/wordpress/contact-us-2/ site/wordpress/sample-page/ site/wordpress/test-page/
in domain Name I've used this $urlOfSite = get_option('home'); $url = parse_url($urlOfSite, PHP_URL_PATH); url path . This is working for me .
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "plugins, cookies, site url" }
How can I filter a query by post id? In my wp_postmeta table, I have the following values: !enter image description here I'm trying query the posts whose ID lie in the `meta_value` column associated to a given post (the current post being viewed). For example, lets suppose I'm viewing post `94`. As illustrated above I would like to retrieve the posts `108,78,90` associated with `94` and display their titles. In this way the an area (post type) is associated with a post by its ID being one of the meta values for the post's 'area' meta key. I start with this: $args = array( 'post_type' => 'area', 'posts_per_page' => -1, ); $areas = new WP_Query($args); But how I can specify I want the posts associated with the post `94`?
So you want the values `108,78,90` corresponding to the meta key 'areas' for the post with ID 94? First retrieve those IDs: $the_post_id = 94; $area_ids = get_post_meta( $the_post_id, 'areas', false ); //Make sure they're all positive integers $area_ids = array_map( 'absint', $area_ids ); if( $area_ids ){ //We have IDs, retrieve posts $areas = get_posts( array( 'post_type' => 'area', 'numberposts' => -1, 'post__in' => $area_ids; )); if( $areas ){ //We have areas foreach( $areas as $area ){ echo get_the_title( $area ). '<br/>'; } } } The above has not been tested, but should work in theory. If you want `$the_post_id` to the be ID of the post currently being viewed then you can use `get_the_ID()`.
stackexchange-wordpress
{ "answer_score": 4, "question_score": -1, "tags": "wp query" }
How is comment spam received without a comments form? The theme one of my sites is using does not have a comments form nor is there any HTML markup for comments anywhere within the code. So, how am I receiving spam comments? All the spam is caught by akismet and I can change the Discussion Settings so only registered and logged-in users can comment (and a few other settings) -- so the question is not "HOW to reduce spam" but how do spammers (bots or humans) submit spam without a form?
You don't need a form to submit a comment to the wp-comments-post.php file, or to send a pingback or trackback. Spammers don't use forms, they simply send their spam directly. Removing the form doesn't "turn off" comments. To do that, go to the Posts screen, and use the Quick Edit to actually disable comments and trackbacks for the various posts. Also visit the Settings->Discussion page, and set it to disable comments and trackbacks for new posts as well. Once you do this, then the comments being sent directly will be rejected by WordPress. That will actually turn them off.
stackexchange-wordpress
{ "answer_score": 6, "question_score": 4, "tags": "comments, spam" }
Manually trigger a wp_schedule_event item? I have successfully added an event via `wp_schedule_event` and I'd like to trigger it manually without disrupting the existing schedule. Is there a way to tell WP to execute an event immediately without the cha-cha where I have to swap values in-and-out to get the event to fire _and_ save/restore the existing (pre-manual call) timing on the event?
Why not just to do_action($hook) of your cronned event?
stackexchange-wordpress
{ "answer_score": 6, "question_score": 2, "tags": "wp cron" }
How to keep WP from using https to get to wordpress.org? See question “Unexpected error” on update requests Turning off SSL on the server is not something we can do since we use the server to serve content on other SSL binding servers. What can I do in WP to make the WP core just use http? I want all of our admin stuff going to < There is an SSL variable - $ssl - that is being read. How do I set that to FALSE everywhere so that WP doesn't try to use it. I have no security needs since I am behind proxy/firewall.
You don't need to turn off SSL on the server. You need to install an HTTP client method that supports SSL transport. This has nothing to do with your server supporting SSL as a server. In this case, WordPress is acting like a web-browser, and trying to make an HTTPS connection to WordPress.org, so that you can download files securely. Typically, you need to reconfigure your PHP installation on the server so as to have CURL and OpenSSL available to PHP. How to do this precisely depends on your hosting service or system.
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "ssl" }
Change CSS for logged in users In my css i have a hidden `div id`: #example {display:none;} How can I set this to `display:block` for logged in users only? I am assuming using Jquery would be the best option here for best performance? Or is it better to use a function in functions.php ?
You need to use the `body_class()`: < If you use the function `body_class()` you can set on your css like this: .example { display: none; } .logged-in .example { display: block }
stackexchange-wordpress
{ "answer_score": 6, "question_score": 0, "tags": "functions, jquery, css" }
Including php file in directory above WordPress installation I'm having trouble including an external .php file into my WordPress theme. **WordPress installation URL:** mydomainname.com/blog **PHP File URL:** mydomainname.com/testing/assets/inc/analytics.php I'm trying to include this PHP file from within header.php of my WordPress theme. My line of code looks like this: <?php include ( site_url() . '/testing/assets/inc/analytics.php' ); ?> I've also tried variations of `PATH` and `ABSPATH` but I can't get it to work. Interestingly, when I change the `include` to `require_once` it breaks the site. Please help me figure out what exactly I'm doing wrong. Thank you!
You need to use file paths, not urls, so if mydomainname.com/blog is at /home/account/public_html/blog then your file is /home/account/public_html/testing/assets/inc/analytics.php. I would recommend putting it into a one-off plugin though.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "include" }
Where to populate custom terms in custom taxonomy in plugin? I have a plugin that successfully creates a custom taxonomy for a custom post type. What I'd like to do, is on activation (or wherever works), create a default set of terms for the custom taxonomy. I've successfully done this before by using `wp_insert_category` in a function called upon plugin activation. That same function isn't working for the custom taxonomy, though. My guess is that it is because the custom taxonomy isn't registered yet when the function gets fired. I can't seem to find out where to hook the function so that it works with a custom taxonomy. I've tried calling the function from `wp_loaded` also and I curiously get `Call to undefined function wp_insert_category()` That puzzles be as well because I thought that hook meant all of Wordpress was loaded. Any advice would be greatly appreciated. Thanks.
Hook into `registered_taxonomy`. This is called after the taxonomy was registered successfully. Sample code: add_action( 'registered_taxonomy', 'insert_default_terms', 10, 3 ); function insert_default_terms( $taxonomy, $object_type, $args ) { if ( 'your_tax_name' !== $taxonomy ) return; // insert terms }
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "plugins, custom taxonomy, terms" }
obtain the author id given the post id If `$a` contains the ID of a certain post, how can one obtain the corresponding author ID? I've tried with $b = get_post( $a); $c = $b->post_author; $d = $c->ID; but it does not work.
$b = get_post( $a); // post_author already contain author ID. //So you can assign author's ID to $c same as to $d $c = $d = $b->post_author;
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "posts, author, id" }
'rewrite_rules_array' or 'generate_rewrite_rules' for adding custom rewrite rules? Is there any reason why I should use `rewrite_rules_array` instead of `generate_rewrite_rules`? `generate_rewrite_rules` works out of the box, but I couldn't get `rewrite_rules_array` to work. And I am told that any array actions [when adding custom rewrite rules] should be done via `rewrite_rules_array` and the rest of `*_rewrite_rule` filters (e.g. `add_rewrite_rule`). It's unclear why.
This is possibly a matter of opinion, but I would say - neither. If you're simply adding new rules, use `add_rewrite_rule` hooked to the `init` action.
stackexchange-wordpress
{ "answer_score": 3, "question_score": 1, "tags": "url rewriting, rewrite rules" }
Separate Uploads folder on other server Is there a way to separate wp-content/uploads on different server ? I mean if i have two servers. Serv1 and Serv2 . On Serv1 is the wordpress installation and on Serv2 stays only the uploads folder. I try to use ftp like: `define( 'UPLOADS', 'ftp://user:pass@Serv2/wp-content/uploads' );` on Serv1.It works but when you point image on the site the URL is with ftp user and password. So that's unusable. Is there any normal way to do it ? Regards.
Assuming you want to have a CDN effect or even for some security reasons (we also look into that but CDN will cost us too much (we have over 1TB monthly)), maybe following links will guide you into the right direction. This info I found here on stackechange itself _These links tell some about using a subdomain as goal but seems also very usefull._ \- This link shows explenation for redirecting your images. (or actual your upload dir) \- Another link with info (for subdomains) you find here. Hopefully it helps you into the right direction. As soon I figured out best way myself I will put answer here also.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "uploads" }
How can I prove if wp cron is running my task if I have DISABLE_WP_CRON set to true I am trying to trigger a wp cron task via a real (linux) server cron and have followed online instructions to add this to wp-config: define('DISABLE_WP_CRON', true); My cron job does this : wget -O - I have proved that the server's cron job is working (i receive the cron emails from the server when I remove > /dev/null 2>&1) but am unsure if my actual scheduled task is running. How can I prove this?
I always found that logging cron job execution to a file is very helpful. Otherwise you have no idea if it's working right. Just have your code open a file, write a timestamp, and close. Something simple like: $logfile = $_SERVER['DOCUMENT_ROOT'].'/CRON.txt'; $handle = fopen($logfile , 'a') or die('Cannot open file: '.$logfile ); $data = 'cron task called at '.date('D, d M Y H:i:s',time())."\n"; fwrite($handle, $data); fclose($handle);
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "wp cron, cron" }
Hide View and preview from custom post types Is it possible to hide the ability to view or preview custom post types? I as, for custom post types like carousels and other forms that render in a particular way where viewing or previewing them out side their intended rendering purpose would not make any sense.
You need to set argument `public` to false at register_post_type() function. > Whether a post type is intended to be used publicly either via the admin interface or by front-end users. Default: false > > * 'false' - Post type is not intended to be used publicly and should generally be unavailable in wp-admin and on the front end unless > explicitly planned for elsewhere. > * 'true' - Post type is intended for public use. This includes on the front end and in wp-admin. >
stackexchange-wordpress
{ "answer_score": 8, "question_score": 6, "tags": "custom post types" }
Remove space when post title is blank I want my custom post type title leave no spaces when there is no title in the post. I tried to use following code but is removed h1 and other tag. Please help. <?php if (the_title() != '') { ?> <h1 class="post_title"><a href="<?php the_permalink() ?>" rel="bookmark" title="Permanent Link to <?php the_title_attribute(); ?>"><?php the_title(); ?></a></h1> <?php } else { } ?> !enter image description here
You need to use `get_the_title()` (codex). `the_title()` (codex) doesn't actually _return_ anything but _prints_ the title.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "custom post types, get the title" }
Wordpress hide the username/password fields in login page I have installed the wordpress social login and I want users to login only using social website IDs. Now as a second step I do not want the username and password fields for users in the login page as that is redundant. One way is to hack the php files that display the login page... but I want a more modular structure. I plan to make the username and password fields invisible by adding custom css (using a custom css plugin) and adding the following: label[for='user_name'] { visibility:hidden !important; } label[for='user_pass'] { visibility:hidden !important; } However the fields still remain visible. Any solutions please?
If you are ready to do this with css, you can do it in the following clean way. Add the following code in the current theme's **functions.php** file add_action( 'login_head', 'wpse_121687_hide_login' ); function wpse_121687_hide_login() { $style = ''; $style .= '<style type="text/css">'; $style .= '.login form{ display: none }'; $style .= '.login #nav a, .login #backtoblog a { display: none }'; $style .= '</style>'; echo $style; } or use the below way to enqueue the css file to the login page then use the css. Add the below code in your current theme's functions.php file add_action( 'login_enqueue_scripts', 'wpse_121687_hide_login' ); function wpse_121687_hide_login() { wp_register_style( 'hide-login', plugins_url( 'path to /css/hide-login.css' ) ); wp_enqueue_style( 'hide-login' ); } And then add the css in the **`hide-login.css`** file
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "css, wp login form" }
Retrieve user_meta and copy to post_meta As geo mashup only retrieves post_meta, I am trying to copy over the geo_location from a custom registration field into the meta for page containing the map. The code I am using is: <?php $blogusers = get_users_of_blog(); if ($blogusers) { foreach ($blogusers as $bloguser) { $user = get_userdata($bloguser->user_id); $user_location = the_author_meta('geo_address', $user->ID); add_post_meta( 463, 'geo_move', $user_location); }} ?> This creates the post meta, but the value is written as a blank, so it looks like $user_location isn't working. Any suggestions?
First of all `get_users_of_blog` has been deprecated, so you should use `get_users` instead, or run a `WP_User_Query`. After that, `the_author_meta` **echo** the meta value, not return anything. To **return** the meta you should use `get_the_author_meta()` $blogusers = get_users( $args ); // for args see codex if ($blogusers) { foreach ( $blogusers as $bloguser ) { $user_location = get_the_author_meta('geo_address', $bloguser->ID ); $has_meta = get_post_meta(463, 'geo_move', true); if ($user_location && ! $has_meta) add_post_meta( 463, 'geo_move', $user_location); } }
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "post meta, user meta, geo data" }
How long is "as long as possible" in wp_cache_set()? The documentation for `wp_cache_set()` says that if you pass in 0 for `$expire` (which is also the default), then it is cached for "as long as possible". How long is this? What determines it? Are we talking hours, days? In my case: I have a _very_ expensive SQL query on a multisite network of literally 100s of blogs, the result of which could be cached for weeks (really forever - could just manually flush it when needed). Should I use WordPress's cache or sort something out myself?
The WordPress object cache isn't a persistent cache, it's meant to cache data within a single page load, so "as long as possible" will never be longer than a single request. Use the Transients API if you want to store your data across multiple page loads, or even simpler, just store it in an option manually.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "multisite, database, cache, customization" }
Using existing widget code! Maybe this was answered many times but I couldn't find my answers so here I go: Am I allowed to use widgets php code from other existing themes and modify it for my needs?
It depends entirely on the license of theme you're intending to make a derivative work of. You'll find a related debate on wordpress.org here: < ...and another individuals cumulative research on the matter here: < Additionally, here's an example of the a web designer legitimately modifying a premium theme on Theme Forest and reselling it as his own (Stack Overflow): <
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "php, themes, widgets" }
Changing the site URL # Overview: I have a self-hosted WordPress installation _currently_ without a domain. Example: < In a few days a domain will be pointing to this installation and I'll need to update the site URL. I'm not migrating. I'm simply changing the home/site URL from an IP-based URL to a domain-based URL. I've already read through the codex on the matter but apart from changing the Home URL and Site URL under General Settings, the codex appears to be outlining fixes rather than any other steps additional to changing the URLs via General Settings. # Questions: 1. In your experience, is it a straight forward process changing from an IP-based site URL to domain-based site URL? Is it a problematic affair that should be avoided by creating a fresh hosting account entirely? 2. Is anyone aware of potential problems this could create with plugins such as WooCommerce? Note: I have reviewed existing questions/answers on this website.
If you have access to phpmyadmin the best way in my opinion is to get WP migrate Db Plugin, then create an export sql file with new url address and upload it with PhpmyAdmin. That way you ensure that every place in the site with old url get replaced with new url in a **safe way** (you can't do a simple search and replace because it won't work) Regarding your 2 questions: 1 With this plugin is pretty straight forward. Create a database backup just in case, but you shouldn't have problems 2 No problem if is replaced this way.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "domain, site url, home url, ip" }