INSTRUCTION
stringlengths
11
999
RESPONSE
stringlengths
0
999
SOURCE
stringlengths
16
38
METADATA
dict
Wordpress CDN Subdomain URL not accessible to the public I recently started serving images to my wordpress website via a subdomain. It worked perfectly. But i noticed that if i enter the subdomain url eg. < into the browser it displays all my files in the uploads folder. I would love to make this inaccessible to the public. Only the direct links to the media files should be available for download and the subdomain folder shouldnt be made accessible via the browser. Please how do i go about doing that? I have tried to change the permission on the subdomain folder from cpanel but seems like i dont have the right permission.
To prevent folder listing you could add an .htaccess file to the root of your subdomain with this content: Options -Indexes
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "subdomains" }
What is the correct syntax to append a URL using a shortcode for an iframe? I need to iframe a series of content on our site. I need to pass on the the user information via a URL - vendor request. I have tons of shortcodes that display the username. It works fine. But when I append the src record it doesn't work. <iframe src=" width="800" height="450"> <p>Your browser does not support iframes.</p> </iframe> > This should display: > > < > > but of course it displays... > > < I know of ways I can do this via templating and in php. Would like a way to do this inside the html editor so that our authors have more flexibility. Am I just having a brain fart or is it that complicated?
<iframe src= width="800" height="450"> <p>Your browser does not support iframes.</p> </iframe> Simply removing the quotes around everything worked. All modern browsers add these back in - when that stops working (doubt anytime soon) we might have to create some advanced shortcode but this leaves us more options right now.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "shortcode, html editor" }
Advanced custom fields Repeater conditional statement not working Even if no value for a field is entered my elements inside my echo still show inside my conditional statement. Thinking that is just checking if the field exists rather then checking if a value is entered. <?php if( have_rows('catalog', 'options') ): ?> <?php while( have_rows('catalog', 'options') ): the_row(); if(get_sub_field('catalog_product_title')); { $catalog_product_title = get_sub_field('catalog_product_title'); echo '<tr><th colspan="3" align="left"><h1>' . $catalog_product_title . '</h1></th></tr>'; } ?> <?php endwhile; ?> <?php endif; ?>
if(get_sub_field('catalog_product_title')); > **;** is for ending a statement in php If you remove that ; your if statement should work.
stackexchange-wordpress
{ "answer_score": 1, "question_score": -1, "tags": "php, advanced custom fields, conditional tags" }
Create user role restricted to specific CPT I am trying to create a role that can create and submit to a CPT only. When I take away edit_post from the role, it revokes the ability to create and edit any of the assigned and registered CPTs as well. I have registered and assigned the edit_CPTs capability to the role as well. So basically, I have this: edit_cpt edit_cpts and I have taken away edit_posts But once I remove `edit_posts` the role cannot even see the CPTs in the dashboard interface. Any help would be greatly appreciated.
You need to register the CPT with your custom capability, then assign that specific cap to the user. When passing the arguments to `register_post_type`, set `capability_type` to your new capability, so the check turns into `'edit_cpts'` instead of `'edit_post'`. By setting `'capability_type' => [ 'cpt', 'cpts' ]`, 'cpt' will map to 'post' for standard capability checks, so where you'd usually check for 'edit_post' you'll now check for 'edit_cpt'. When you completely remove the primitive `'edit_posts'` cap from users/roles as you've done, you'll need to add in your new one with `WP_Role::add_cap()` and check for it with `current_user_can( 'edit_cpts' )`.
stackexchange-wordpress
{ "answer_score": 4, "question_score": 3, "tags": "custom post types, user roles, capabilities" }
Check for image with same filename but different extension I'm using the following code to show images in an ACF Gallery field <?php $images = get_field('gallery'); if( $images ): ?> <?php foreach( $images as $image ): ?> <figure class="wp-caption aligncenter"> <img class="b-lazy" src="<?php echo get_template_directory_uri(); ?>/assets/images/spinner.gif" data-src="<?php echo $image['sizes']['featured-720']; ?>" alt="<?php the_title();?>"> </figure> <?php endforeach; ?> <?php endif; ?> What i would like to do is to check for each $image, if there is another attached image with the same filename but different file extension (png). For example: There is an image attached called "ThisTitle.jpg" and I want to check if there is also another image attached called "ThisTitle.png" I hope this make sense :)
You can use pathinfo() and getimagesize(): $info = pathinfo($image); if ( @getimagesize($info['dirname'] . '/' . $info['filename'] . '.' . $extension_to_check) ) { // do something }
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "advanced custom fields, php" }
uploading files to the uploads folder via ftp What is the reason/s that the WordPress Media Folder, doesn't display images that were uploaded via FTP, directly to the uploads folder? Why doesn't WordPress "see" them? why do we always have to upload via the WordPress media uploader? What does it do?
Because WordPress is not scanning all the folders all the time. When you upload images Wordpress also makes an entry in the database, records the caption, the sizes that are available and so on.
stackexchange-wordpress
{ "answer_score": 2, "question_score": 3, "tags": "uploads, media library" }
Adding second comments.php for reviews I've just started a business directory website. I'm using a custom post type for this. I'd like to extend the site's purpose by allowing visitors to add reviews on each business. I therefore wondered if I could create another comments.php file for the purpose of visitors leaving reviews on single business pages while leaving the original comments.php for blog comments. Of course, I've tried a few review plug-ins without success!
I don't know what your `comments.php` looks like, so I cannot tell how to adapt your current code, but I can generally tell you how to approach this. Normally, WP will assume that you want the latest comments of the current post. If you want something else, you start with the condition under which you want your second set of comments to show and add this to `comments.php`: `if (my_condition) { show second comments set; }` Now, you have to tell WP which set of comments to use. You need to set `$args` which are available in the `get_comments` function. There are too many options to describe here. Once you have retrieved comments with `$comments=get_comments($args);` you can feed them into the display function `wp_list_comments($args,$comments)`. The `$args` to this function determine how the comments are displayed. You can have them shown completely different from you other comments set.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "custom post types, comments" }
Can you hide empty terms using get_term_children? I'm trying to `get_term_children` of a specific term: $style_categories = get_term_children( 29, 'product_cat' ); if ( $style_categories ) : foreach ( $style_categories as $style ) : $child = get_term_by( 'id', $style, 'product_cat' ); echo '<h3>' . $child->name . '</h3>'; // post query goes here endforeach; endif; This works, but it shows terms when they're empty, and there doesn't appear to be a `hide_empty` option for get_term_children. Is there a way to do this?
With the `get_term_children()` function there is nothing to pass which will hide empty terms. You could do that in your foreach as each term has a property which holds how many posts it is assigned: foreach( $style_categories as $style ) { $child = get_term_by( 'id', $style, 'product_cat' ); // Skip empty terms if( $child->count <= 0 ) { continue; } } The way it stands now you're creating multiple queries - a better solution would be to use `get_terms()` instead. get_terms( [ 'taxonomy' => 'product_cat', 'child_of' => 29] ); `get_terms` will hide the terms that have no post, you can change that with the `hide_empty` argument.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "custom taxonomy, terms" }
Add a filter to an action I feel like this is a really simple question, but I can't seem to find anything. I want to add a filter to an action, so I can run `preg_replace` on it to add a class to a link. The action is: do_action("tribe_events_single_event_after_the_content"); This is what I'm trying to use for my filter, I'm sure I'm doing something dumb: function fix_tribe_button_class($content) { $content = preg_replace("/tribe-events-button/i", "tribe-events-button button", $content); return $content; } add_filter("the_content", "fix_tribe_button_class", 999, 1); I've even tried doing `return "test";` to see if maybe I was matching incorrectly. It just didn't affect anything at all.
The action name suggests it is run `_after_the_content`, not within the `the_content` itself, so you might have to do something different here like @SamuelElh is suggesting... You would add a function to the action with early priority to buffer, then add a filter to the final output with a late priority: add_action('tribe_events_single_event_after_the_content','tribe_events_single_event_buffer_start',0); function tribe_events_single_event_buffer_start() {ob_start();} add_action('tribe_events_single_event_after_the_content','tribe_events_single_event_buffer_end',999); function tribe_events_single_event_buffer_end() { return apply_filters('tribe_events_single_event_filter_output',ob_get_clean()); } function tribe_events_single_event_filter_output($content) { $content = preg_replace("/tribe-events-button/i", "tribe-events-button button", $content); return $content; }
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "filters, actions" }
Categories box not showing on post edit pages for some reason I don't get the Categories meta box on my standard 'post' edit pages in the wp admin. It shows up on my custom post types, and they show up in the 'Quick Edit' view on the Posts list page, but not on the actual Edit Page for standard posts. Is there a setting for it somewhere?
Posting this here as an answer for anyone else who has the same issue. Basically, you need to do a global search of plugins and themes and look for this hook: `remove_meta_box( 'categorydiv' , 'post' , 'normal' );` More info in the wordpress codex: <
stackexchange-wordpress
{ "answer_score": 1, "question_score": 3, "tags": "posts, categories, wp admin" }
Automatically add class-attribute to gallery? I'm making a theme for a client in WordPress and he wants each gallery to have a grouped lightbox, so there's a lightbox for each gallery. I found out you can make it add an attribute to the gallery automatically, so what I want is an attribute called `'class'` that has a number that adds by 1 for each gallery created. How would I do that? **Edit:** I see that I was not being specific enough so here's some more information: I want a `'class=""'` attribute added automatically to the shortcode when the post gets created. Inside that class attribute I want it to have a number that goes up by 1 for each post containing a gallery. So the shortcode would end up like this: `[gallery class="1" ...]` and the next `[gallery class="2" ...]` and so on...
If you take a look at native galleries they already have IDs with counter implemented: $instance++; ... $selector = "gallery-{$instance}"; ... $gallery_div = "<div id='$selector'class='gallery... So first gallery within a post will have `<div id="gallery-1"...` and so on. This is used by core itself to target different styles at each instance. If you need to do something more custom you can use `gallery_style` filter, which gets passed those styles and opening `div` markup, to similarly keep track of instances and inject your custom classes as necessary.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "shortcode, gallery" }
Is there a way to optionally hide the title bar when logged in? When I'm creating a theme and I'm logged in, there is a wp admin bar that runs across the top of the page. This is helpful for normal use but it makes it hard to see what I'm working on when I'm making a theme. It would be helpful if there was a way to hide this. Is there a disclosure button to hide or minimize the title bar or maybe a plugin?
I am not sure if this is what you are looking for, but when you login into wp-admin and go under "Users" -> "Your profile", you have an option to hide the admin bar. ![enter image description here](
stackexchange-wordpress
{ "answer_score": 3, "question_score": 0, "tags": "theme development, admin bar" }
Problems Including File I read that if you create a php file and save it in the /wp-content/mu-plugins/ directory, WordPress will auto-load it. However, I haven't yet figured it out. I don't have a folder named mu-plugins; it's just wp-content/plugins. I created a file at wp-content/plugins/echo-values.php, put a simple echo value in it and uploaded it, but I don't see the value I echoed in my source code. I then opened wp-content/plugins/index.php and pasted in the following code: require_once("echo-values.php"); require_once("/wp-content/plugins/echo-values.php"); Again, I don't see anything in my source code, so it looks like those files aren't being included. For good measure, I echoed some text in /wp-content/plugins/index.php, but I don't even see that in the source code. Can anyone tell me the best way to include my own PHP file? It doesn't have to be in the plugins folder, though I was advised that's the best place to put it.
Yes, you can use a `/wp-content/mu-plugins` folder for * single file * autoloading plugins. The only thing you will have to do is to use a plugin header comment in this file: <?php /* Plugin Name: I am a MU-Plugin */ Then you will find a link on top of your `/wp-admin/plugins.php` page that says > "Must-Use Plugins" where you will find the list of mu-plugins. Those plugins can not be deactivated by an administrator or anyone else — only someone having access to your servers filesystem will be able to deactivate them by removing them from this folder. Note, that plugins residing in subdirectories in this folder will _not_ get loaded.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "include" }
Display posts with empty custom field How to list post with specific custom field which is empty? I have some posts with custom field 'author', and for some posts that custom field is emty, so I would like to find those posts to delete that custom field for them. <?php $args=array( 'post_type' => 'post', // Post type is post. 'post_status' => 'publish', // Post is published. 'meta_key' => 'author', 'value' => '', 'meta_compare' => '=', 'posts_per_page' => 100, // Posts per page. 'caller_get_posts'=> 100 // Get posts per page ); $my_query = null; $my_query = new WP_Query($args); if( $my_query->have_posts() ) { while ($my_query->have_posts()) : $my_query->the_post(); ?> <?php // my code; ?> <?php endwhile; } ?>
You probably need the `NOT EXISTS` `meta_compare` value. This will test if a meta value exists or not for that particular key. Also, as I pointed out in comments, `caller_get_posts` is long time deprecated, a notice you should have clearly recieved if you had debubbing turned on. The correct parameter is `ignore_sticky_posts` and accepts `0` ( _`false`_ ) or `1` ( _`true`_ ) ## EDIT One issue I missed is, `value` should be `meta_value` when not using a proper `meta_query`
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "custom field, post meta" }
How to remove proudly created by WordPress in theme? How to remove proudly created by WordPress in theme?
You can delete it from the footer.php file or you can hide the CSS that displays it which is better in case you update the theme as the footer.php file may get over-written. If you choose the CSS route, then paste the following into your CSS file: #site-generator { display: none; }
stackexchange-wordpress
{ "answer_score": 1, "question_score": -2, "tags": "theme development, themes" }
Generate Sub-Comments with WP-CLI Using wp-cli, it is possible to generate random comments for posts. Is it also possible to generate sub-comments? If so; how?
Currently it is not available in WP CLI. See < If you want, you can have your own customized comment generation command. See command cookbook. <
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "comments, wp cli" }
How to remove Nextpage tag inside posts text depending of utm_campaign Is it possible to remove "nextpage" tag inside posts text depending of utm_campaign ? Depending of where my visitors are comming from, I want to remove the <!--nextpage--> of my post. I am using this if($_GET['utm_campaign']== 'nonextpagecampaign') { directly in my template in order to display or not things depending of the campaign name but for the nextpage tag, it's not that easy.
You can use `the_post` hook to remove `<!--nextpage-->`. In this case: add_action( 'the_post', 'campaign_remove_nextpage', 99); function campaign_remove_nextpage ( $post ) { if ( ($_GET['utm_campaign']== 'nonextpagecampaign') && (false !== strpos( $post->post_content, '<!--nextpage-->' )) ) { // Reset the global $pages: $GLOBALS['pages'] = [ $post->post_content ]; // Reset the global $numpages: $GLOBALS['numpages'] = 0; // Reset the global $multipage: $GLOBALS['multipage'] = false; } }; Read more about this issue More in general, you may want to read this warning about SEO effects of using `<!--nextpage-->`.
stackexchange-wordpress
{ "answer_score": 6, "question_score": 4, "tags": "posts, tags, content" }
Post Title to featured Image ALT i saw a interesting post on Stackoverflow where someone showed a code to to use the post title als alt tag for the featured post. So i tried to use the code for myself and change it a bit because mine differs a bit. Original Code $title=get_the_title(); the_post_thumbnail( array(150, 150),array( 'alt' =>$title) ); I changed it to <?php $title=get_the_title(); the_post_thumbnail( array($size),array( 'alt' =>$title) ); ?> The problem is that $size is not working correctly anymore it came out with 150px x 150px. (My original code is `<?php the_post_thumbnail( $size ); ?>` ) I hope that someone could tell me what is wrong with it =o
If `$size` is already an array in your original code as it looks to be, then the argument passed will become `array(array(150,150))` instead of just `array(150,150)` and fail, so you can just do: <?php $title=get_the_title(); the_post_thumbnail( $size, array( 'alt' =>$title) ); ?>
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "posts, post thumbnails" }
Screen Options & Help Buttons not working when including Bootstrap Css The wordpress 'Help' and 'Screen Options' Buttons in the wordpress Admin Panels are not working when including bootstrap and specifically the bootstrap-css files. It is caused because bootstraps css overides: .hidden { display: none !important; } How can I make the buttons working again? It is related to this Thread but it is not linked to bootstrap therefore I answer it here again as a bootstrap specific problem.
Check if you or a plugin include bootstrap and the bootstrap CSS / Theme files. Bootstraps `.hidden` class looks like: .hidden { display: none !important; } But overrides wordpress' definition of `.hidden`: .hidden { display: none; } The Top 'Help' & 'Screen Options' bars are displayed via inline style `display: block`, which is overridden by bootstraps `.hidden {display: none !important}` css class. This can be fixed by rewriting the Top Bars Css via Jquery / JS. Working example: jQuery(document).ready(function ($) { $("#contextual-help-link").click(function () { $("#contextual-help-wrap").css("cssText", "display: block !important;"); }); $("#show-settings-link").click(function () { $("#screen-options-wrap").css("cssText", "display: block !important;"); }); });
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "wp admin, twitter bootstrap" }
Media previews on posts _Firstly a quick disclaimer - I'm fairly inexperienced when it comes to WordPress. I'm a programmer by profession but don't work with PHP or wordpress a lot._ I've just done a theme change on a blog that is linked to our actual site - for a number of reasons. Anyway - the old theme had a preview if there was media from SoundCloud or Youtube (and probably other media platforms) with custom tags, eg: [soundcloud url=" width="100%" height="450" iframe="true" /] or <iframe width="100%" height="450" scrolling="no" frameborder="no" src=" Would appear in the post preview as a soundcloud embed item with the post's text below it. However, on the new theme the previews don't appear, and when open the single post version of the posts there is also no play option of the media. The old theme was Blogoma and the new one is Radiate (the free version). Any ideas?
Okay so I figured out what was happening - either the new theme or an unintentional wordpress update, lead to media links being handled differently. My new theme now only needs the URL - no shortcodes or iframes - and it seems to automatically process it to display how it used to display them. Only issue with this is that the old posts have to be edited to reflect the change.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "themes, media, embed" }
Using WP Query to search within ALL keys in meta query What is the best way to create a meta query that searches through ALL meta fields (keys)? What I'm trying to do is something such as: $posts = new WP_Query(array( 'meta_query' => array( 'relation' => 'OR' array( 'key' => ALL, 'value' => keyword ) ) )); Does that make sense? What is the proper way of doing it? Thanks
As @Howdy_McGee suggested and I made a quick test. Removing `key` do the trick so you can just remove the `key` and add compare `LIKE` if you do not want exact match. Example:- $posts = new WP_Query(array( 'meta_query' => array( array( 'value' => 'meta_value' ) ) )); This will produce the SQL like WHERE 1=1 AND ( CAST(wp_postmeta.meta_value AS CHAR) = 'meta_value' ) That is what we want!
stackexchange-wordpress
{ "answer_score": 5, "question_score": 2, "tags": "wp query, meta query" }
Disable resizing of gif when uploaded Animated gifs are getting more popular on the web (again) and currently there is no good tool for resizing animated gifs. So I want to disable resizing/generation of image sizes for the gif mimetype and just save the original gif. Someone that can help me out with this? Which filter to use will be a good start.
image_make_intermediate_size was not the hook I was looking for, but intermediate_image_sizes_advanced. Here is a working code: function disable_upload_sizes( $sizes, $metadata ) { // Get filetype data. $filetype = wp_check_filetype($metadata['file']); // Check if is gif. if($filetype['type'] == 'image/gif') { // Unset sizes if file is gif. $sizes = array(); } // Return sizes you want to create from image (None if image is gif.) return $sizes; } add_filter('intermediate_image_sizes_advanced', 'disable_upload_sizes', 10, 2);
stackexchange-wordpress
{ "answer_score": 6, "question_score": 4, "tags": "filters, uploads, images" }
Run function when WordPress new multisite is created or ACF field is updated I have created a function on the main site in my multisite network that loops through each site in the network, pulls the values from their options page in ACF, and saves the data to a JSON file. However, I am unsure about how to get it to run outside of a single .php page that I've tested. My questions are: * When is the best time to run this function? * Is the easiest method putting it in a custom plugin and giving it a button to click to run? * Is there any way I can automate the process, as ideally I would like it to run either when a new site is added to the network or the ACF options of an existing site change? One issue I have is that my main site and subsites are on separate themes and don't share the same functions.php file, so I don't think using something like acf/save_post would work.
Create a plugin for the mu-plugins directory and have your function run when the wpmu_new_blog action fires. Reference, here: < The hook you cited for ACF seems to be the way you ought to run you function, if you want that to happen upon ACF save...
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "functions, multisite, advanced custom fields, json" }
$wpdb->prepare not working with update table prefix The following does not work with my custom table: $wpdb->prepare("UPDATE $wpdb->jch_gigs SET available = available - %d WHERE ID = %d", $quantity, $item) ); But this does: $wpdb->prepare( "UPDATE jch_gigs SET available = available - %d WHERE ID = %d", $quantity, $item) ); What am I doing wrong?
Your problem is likely that `$wpdb->jch_gigs` is undefined. Is `jch_` the prefix of your DB tables, as defined in `wp-config.php`? If so, try this: $wpdb->prepare( "UPDATE {$wpdb->prefix}gigs SET available = available - %d WHERE ID = %d", $quantity, $item ) ); `wpdb` class on the Codex
stackexchange-wordpress
{ "answer_score": 4, "question_score": 2, "tags": "wpdb" }
How can I modify the WordPress default widget output? I don't want to style the default widget with only CSS. I want to display the default 'Categories' widget content with my own HTML structure. Is there available any filter or hook to do that?
To expand on Mark's answer, there's not much (generally) available in the way of filters in the default WordPress widgets (except for perhaps `widget_text`). But adding your own custom widget is easy - put this in your `functions.php`: require_once("my_widget.php"); add_action("widgets_init", "my_custom_widgets_init"); function my_custom_widgets_init(){ register_widget("My_Custom_Widget_Class"); } Then you simply want to copy the existing categories widget from `wp-includes/widgets/class-wp-widget-categories.php` to `my_widget.php` in your theme, and change the class name to the same name as that used in the call to `register_widget()` above. Then make whatever changes you like! I suggest changing the title too so you can distinguish it from the default Categories widget.
stackexchange-wordpress
{ "answer_score": 16, "question_score": 19, "tags": "filters, widgets" }
How can I ask to an existing category? I want to echo the child category name. That works. But how can I ask after an existing category, so that I have no `<h6>`-tag when I have no category? Where is my mistake? <?php $category = get_the_category(); $last_category = end($category); $category_name = $last_category->cat_name; $category_id = get_cat_ID( $category_name ); $category_link = get_category_link( $category_id ); if (is_category($category_name)) { ?> <h6 class="cat-child-name"><a href="<?php echo esc_url( $category_link ); ?>"><?php echo $category_name ?></a></h6> <?php } ?>
If you want to check whether a certain post has a certain category, you need `in_category`, so your test would need to be: if (in_category($category_name))
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "categories" }
In theme development, are there functions which write HTML in a standard fashion to reduce "spaghetti code"? For example, if I'm building a list in a plugin that loops over an array to produce a list `ul` or `ol`. I typically see code as follows. foreach($list as $item) { $output .= '<li>' . $item['value'] . '</li>'; } I guess I'm looking to see if there is a comparable to such functions in the Drupal world such as `theme_list()` (reference). I'm looking to give my list of items to a function and have it write the HTML block in a standardized way.
There are specific functions like `wp_list_categories()` and `wp_list_pages()` along with some others which will do this for you but for arbitrary arrays, WordPress doesn't have a function to neatly print it out into HTML for you. You could simply write your own functions for this purpose if you really need to I guess.
stackexchange-wordpress
{ "answer_score": 3, "question_score": 2, "tags": "theme development" }
How to remove admin footer text from inside child theme? I am using this set of functions in child theme to remove unneeded footer info: add_filter( 'admin_footer_text', '__return_empty_string', 11 ); add_filter( 'update_footer', '__return_empty_string', 11 ); It all worked well while in theme sixteen. Now, in child theme, those filters are not working. How to solve this issue, as this is not only filter I am using.
As suggested in the comments, these kind of modifications would be better served with a custom plugin, as they are not theme dependent. Here's an example: <?php /** * Plugin Name: Remove Footer Text * Description: Remove admin footer text and update footer text through filters. * Version: 0.0.1 * Author: Name * Author URI: */ add_filter( 'admin_footer_text', '__return_empty_string', 11 ); add_filter( 'update_footer', '__return_empty_string', 11 ); _Setup_ : Create the `/wp-content/plugins/wpse-remove-footer-text/plugin.php` and activate the plugin from the backend as usual. If other plugins or the themes are adjusting the footer text, then we might need to increase the _priority_ value.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "functions, child theme" }
How to get posts from a current post's month? I want to display the titles of the post of the same month as the blog post. I tried this .. <?php $year = the_date('Y')?> <?php $month = the_date('M')?> <?php $theids = $wpdb->get_results("SELECT ID, post_title FROM $wpdb->posts WHERE post_status = 'publish' AND MONTH(post_date)= '".$month."' AND YEAR(post_date) = '".$year."' ORDER BY post_date ASC"); foreach ($theids as $theid): ?> <?php echo $theid->post_title; ?> <?php endforeach; ?> but it's returning nothing. How can I make it work? Thanks.
There is `date_query` which can handle this and an SQL query is not a good practice when you can take advantage of WordPress Query API: $pid = 1; // post ID here $args = array( 'posts_per_page' => -1, 'post_type' => 'post', 'date_query' => array( array( 'year' => get_the_date('Y', $pid), 'month' => get_the_date('m', $pid) ), ), ); $posts = get_posts( $args ); print_r( $posts ); Hope that helps.
stackexchange-wordpress
{ "answer_score": 3, "question_score": 0, "tags": "posts, query posts, get posts" }
Store All Post Categories In Array I'm trying to collect a list of all categories used on posts. However, the following code only returns the first category. How could this be adapted to collect all categories, if the post has multiples? $category = get_the_category(); $the_cats[] = $category[0]->term_id; Ultimately, I would like to use the `term_id` list to show/hide HTML elements on the page, depending on the selection.
Try this function wp_get_post_categories() Check more reference from here: <
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "categories, id" }
Redirect to dashboard after login I use the following code to redirect users on login to dashboard instead of their profile. It works fine but it also redirects to dashboard when there is `redirect_to=` in url ` Is possible when there is `redirect_to=` in url to redirect to the appended url and not to dashboard? // Redirect to dashboard on login (instead of profile) add_filter( 'login_redirect', 'app_login_redirect', 10, 3 ); function app_login_redirect( $redirect_to, $request, $user ) { //is there a user to check? if ( isset( $user->roles ) && is_array( $user->roles ) ) { //check for admins if ( in_array( 'administrator', $user->roles ) ) { // redirect them to the default place return $redirect_to; } else { return admin_url( 'index.php' ); } } else { return $redirect_to; } }
The second input argument `$request`, in your `app_login_redirect()` callback function, takes it's value from source: isset( $_REQUEST['redirect_to'] ) ? $_REQUEST['redirect_to'] : ''; so if I understand you correctly, you could just check if it's empty or not, if you need to know that within your logic parts.
stackexchange-wordpress
{ "answer_score": 5, "question_score": 5, "tags": "redirect" }
How to add CSS class to custom logo? I enabled `custom-logo` for my theme and have it printed with `<?php the_custom_logo(); ?>` into the header. Is there any chance to simply add some more classes to this image directly? Per default it only comes with `custom-logo`.
WordPress provide a filter hook to custom logo customization. The hook `get_custom_logo` is the filter. To change logo class, this code may help you. add_filter( 'get_custom_logo', 'change_logo_class' ); function change_logo_class( $html ) { $html = str_replace( 'custom-logo', 'your-custom-class', $html ); $html = str_replace( 'custom-logo-link', 'your-custom-class', $html ); return $html; } Reference: How to change wordpress custom logo and logo link class
stackexchange-wordpress
{ "answer_score": 26, "question_score": 22, "tags": "theme development, themes, css, add theme support, logo" }
Max no of simultaneous active sessions for a single user Is there any limitation to log in with multiple devices simultaneously using a single subscriber (user) account ?
No, there isn't. WordPress login "sessions" are cookie-based and work on each device as if they were the only one in existence.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "users, login" }
wp_editor returning invalid html I am using `wp_editor` in my plugin. It is displayed on the page as: <?php wp_editor(get_option('edpp_card_design'), 'edpp_card_design', array( 'textarea_name' => 'edpp[card_design]' )); ?> When I post the form it is returning invalid HTML, doing a `print_r` on the posted data returns something that looks like this: <span style="\&quot;color:" #ff0000;\"=""><strong>Some Test School</strong></span> Viewing it Text in the editor has it right at <span style="color: #ff0000;"><strong>Some Test School</strong></span> I don't get why this is happening, am I missing something? Is `wp_editor` configured wrong here or should I be running the output through a function before I use it?
Turns out that the output from `wp_editor` is safe to save to a database. It needs passing through `stripslashes()` before echoing into HTML.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "wp editor" }
Change Background Color For CPT Template Please help. Anyone knows of the proper way how to change the background color for a custom post type template only? Using chrome's inspect, I saw that my theme uses the ID of "#main" for all the page's background color so if I try changing it, all pages got affected. Just looking for a way on how only the CPT template will get affected. If it helps, below is a snapshot of the theme. ![New attachment](
You can use the body's classes : body.single-artist #main{ background-color:red; }
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "custom post types, customization, themes, css, custom background" }
Conditional string comparison failing for basename/slug I am trying to display a particular block of html for one page in particular. I have created a conditional statement that compares the basename of the page to my string. <?php if ( has_tag( 'Sponsor' ) && basename( get_permalink() != 'sponsor-one') ) : // show sponsor's footer if applicable ?> <div class="sponsor-footer <?php echo basename( get_permalink() ); ?>"> <p>Our text here</p> </div> <?php elseif ( has_tag( 'Sponsor' ) && basename( get_permalink() == 'sponsor-one') ) : // show sponsor one's footer if applicable ?> <div class="sponsor-footer <?php echo basename( get_permalink() ); ?>"> <p>Our other text here</p> </div> <?php endif; ?> It always outputs the first block of code even when the slug is "sponsor-one". If I `var_dump( basename( get_permalink() ) );` I get `string(11) "sponsor-one"`, so why is it saying that the basename is not equal to "sponsor-one"?
The 2nd part of the condition seems wrong `basename( get_permalink() != 'sponsor-one')` should be `basename( get_permalink() ) != 'sponsor-one'` Please check where the parenthesis ends. Also in your code if that is the only condition, then you can have an `else` statement instead of having another `elseif`.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "php, templates, comparison" }
Wordpress Integration with Google Groups I'm having some trouble trying to make an area on my WordPress site, that must be accessible only to members of my Google Group. I tried to make it with some plugin, but most of them would take me to have to ask the users to register themselves in the website, and that would not include a validator to see if he is a member of the Google group. So, my point is: Is there any way to make a area of my website themselves accessible only by members of a Google Group? If so, how could I do that?
Most of your question is off topic, I guess, because it involves a question about Google's APIs. You would need three things: 1. Create the possibility to login to your site with a Google account. There are plugins that make this possible, like this one. 2. Import the list of group members from Google. There probably is an API for this, but that is out of the scope of this site. Once you have an array of users an mailaddresses, you can use `wp_create_user` to make new entries in your user table. You would have to set a transient for this, to prevent looking for new group members at Google with every pageload. Also, you should create a special user role for group members. 3. Finally, in your templates you can add a check for users that are logged in with that special role to display exclusive information.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 1, "tags": "plugins, database, ajax, user registration" }
Generic plugin (de)activation hook? I am looking for a way to track which user activates or deactivates a plugin for logging purposes. I've been searching around, but can only find information for plugin developers to have a hook to (de)activate their own plugin, but I want to be able to track which plugins are (de)activated from my theme or otherwise my own plugin. Is there a generic hook for when a plugin gets (de)activated?
> do_action( 'deactivate_' . $plugin, $network_deactivating ); Fires as a specific plugin is being deactivated. > do_action( 'deactivated_plugin', $plugin, $network_deactivating ); Fires after a plugin is deactivated. The above hooks don't fire when silent mode is activated (eg: during an update). **Refer:** `deactivated_plugin`
stackexchange-wordpress
{ "answer_score": 2, "question_score": 3, "tags": "plugins, hooks" }
From where the header-text can be changed in WordPress custom header? I am developing a small theme as I am beginner. I am setting up `custom-header` using `add_theme_support()` function. From there I can change the header image in the front end. Ok, so far is good. Now In codex of the WordPress ( < ) there is `$defaults` arguments for the `custom-header` to enable some features. I can use most of them, but when I use the `header-text` I thought I should get option in the customizer (backend) to change the text. But I did not get. But I am sure that option remains where I do not know. Anyone please suggests some to know 1. from where the header-text can be changed? 2. to show in the frontend?
The `header-text` option in the custom header allows you to switch off the header text, not to change its content. You can change the header text in the customizer. To show it in your front end you must must use `echo get_bloginfo('name')` for the blog title and `echo get_bloginfo('description')` for the tagline.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "php, theme customizer, custom header, header image" }
How do I evaluate a get_posts array with is_page? How do I evaluate a condition in which specific pages in a `get_posts()` array are returned `true` by `is_page()`? Basically, I am trying to evaluate an array containing pages with a specific tag, so if the page is included in that list, show something. From the docs, it seems I can use an array as an argument in `is_page()`, but the array returned from `get_posts()` doesn't work. $top_level_pages = get_posts( array( 'posts_per_page' => 10, 'post_type' => 'page', 'tag_slug__and' => 'Top Level' ) ); if (is_page($top_level_pages)) { //Show content for respective page }
Use `wp_list_pluck` to extract an array of IDs from your query, then pass those to `is_page`. $top_level_ids = wp_list_pluck( $top_level_pages, 'ID' ); if ( is_page( $top_level_ids ) ) { // do something }
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "pages, get posts" }
How to add a translatable string to post date I am trying to add a translatable string, like "posted on:" to my Wordpress theme post dates. I have already added a font-awesome icon next to it and I'd like to have the string after the icon. The code for the date is $time = '<i class="fa fa-clock-o" aria-hidden="true"></i>' . '<time datetime=' . get_the_time('Y-m-d') . '>' . get_the_time('j F Y') . '</time>' I know that, to make a string translatable in Wordpress, I need to add the string inside `__()`, but can I do so for the above code? Any ideas?
You should use placeholders: $time = sprintf( '<i class="fa fa-clock-o" aria-hidden="true"></i> %s: <time datetime="%s">%s</time>', esc_html__('Posted on', 'textdomain'), get_the_time('Y-m-d'), get_the_time('j F Y') );
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "translation" }
How to display all custom fields associated with a post type - IN THE ADMIN AREA? I know know how to get all the custom fields from a custom post type, that's easy. However, when I create a custom post type, it displays a beautiful page automatically in the administration part of Wordpress, but with only "title" and "date" as fields: ![no custom fields]( If I want to add a field called "size" for the chimpmonks so that it displays in that administration screen, what should I do?
You need an action called `manage_$post_type_posts_custom_column`. This will allow you to add columns to your custom posts page. To be more precise, you need a filter to generate the column and an action to fill it with content. In your case something like this (untested): add_filter( 'manage_chimpmunks_posts_columns', 'set_custom_size_column' ); add_action( 'manage_chimpmunks_posts_custom_column' , 'fill_custom_size_column', 10, 2 ); function set_custom_size_column($columns) { $columns['size'] = __( 'Size', 'your_text_domain' ); return $columns; } function fill_custom_size_column( $post_id ) { $terms = get_the_term_list( $post_id , 'size' , '' , ',' , '' ); if ( is_string( $terms ) ) echo $terms; else echo __( 'No size', 'your_text_domain' ); } }
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "custom post types, plugins, php, customization, custom field" }
How to handle single quote in a translatable string in Wordpress I have two translatable strings as follows in my 404.php file esc_html_e( 'I couldn't find the page you were looking for.', 'themename' ); esc_html_e( 'Try a search or one of the links below.', 'themename' ); At its present form, the first string does not get translated. Escaping the single quote with a backslash does not help either. Any ideas?
You can wrap it inside double quotes: esc_html_e("I couldn't find the page you are looking for.", "themename");
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "translation" }
Remove and restore one shortcode I would temporarily remove a shortcode, make something and restore it... it's possible? // override default wordpress "the_content" hook remove_filter('the_content', 'do_shortcode', 11); add_filter('the_content', 'my_the_content', 11); function my_the_content($content) { remove_shortcode('some_shortcode'); $content = do_shortcode($content); // restore the shortcode add_shortcode('some_shortcode', '?????????????????????????????'); return $content; } the problem is how restore it correctly... original shortcode is in a class, eg.: class foo { function __construct(){ add_shortcode('some_shortcode', array($this, 'get_some_shortcode')); } public function get_some_shortcode(){ return 'bar'; } }
Another old unanswered question. Hopefully useful to someone in the future. WordPress stores shortcode tags and callbacks in the `$shortcode_tags`. This is how I'd do it. function my_the_content( $content ) { global $shortcode_tags; $tag= 'some_shortcode'; //* Make sure it's actually a valid shortcode if( ! isset( $shortcode_tags[ $tag ] ) ) { return $content; } $func = $shortcode_tags[ $tag ]; remove_shortcode( $tag ); //* Do something useful //* Restore the shortcode add_shortcode( $tag, $func ); return $content; }
stackexchange-wordpress
{ "answer_score": 1, "question_score": 2, "tags": "shortcode, hooks" }
Does My Child-Theme Functions.php Need if{die} Security In It? I'm new to PHP, but I've noticed just about every PHP file has a security snippet, "Die if not accessed in the correct manner" script at the beginning; **my question** , does a child-theme `functions.php` need something like this as well to make it secure? **PHP:** if ( ! defined( 'ABSPATH' ) ) { die( 'Direct Access Not Permitted' ); }
Does it _need_ it? Probably not (other than this edge case, props @bravokeyl). Should you add it? In my opinion, yes: 1. From a coding/architecture POV, you're declaring "this file needs WordPress". 2. Any direct hit to one of your theme's files (curious users, bots, "script kiddies" etc.) has the potential to leak a little bit of info (most likely filesystem) and/or litter your error logs (e.g. `Undefined function get_header in /bada/bing/bada/boom`) 3. Reiterating 1), it's just good practice. **However** , I absolutely _hate_ this: die( 'Direct Access Not Permitted' ); IMO it should simply be: if ( ! defined( 'ABSPATH' ) ) exit; There is just no point in having that "message". And I'm a big fan of `exit`. It communicates the fact that this is an _expected_ possible scenario, and in that scenario, I simply wish to quit. I use `die` for "unexpected" scenarios, like filesystem write errors, database errors etc.
stackexchange-wordpress
{ "answer_score": 5, "question_score": 6, "tags": "php, functions, security" }
index page is not loading anndoe | |-------css/ anndoe.css |-------js/anndoe.js |--functions.php |--header.php |--index.php |--style.css I added below code to functions.php, and my index page doesn't show up. iF I remove this code my index page works. <?php function anndoe_script_enqueue() { wp_enqueue_style ('customstyle', get_template_directory_uri() . '/css/anndoe.css','1.0.0','all'); } add_action ( 'wp_enqueue_scripts', 'anndoe_script_enqueue') In my header.php I added `<?php wp_head(); ?>` above `</head>` tag
You're missing a semicolon on your add_action.
stackexchange-wordpress
{ "answer_score": -1, "question_score": -2, "tags": "errors, wp enqueue style" }
How i can put $_GET codes in function.php? if(isset($_GET["link"])){ $link = $_GET["link"]; header("Location $link"); } this my redirection codes. i put this code in function.php but not working. Example link: < How can i do it for working?
function custom_function_redirect() { if ( isset( $_GET[ 'link' ] ) && $_GET[ 'link' ] != '' ) { wp_redirect( $_GET[ 'link' ], 301 ); }else{ die('test'); } } add_action('template_redirect','custom_function_redirect'); Try this it worked for me. For redirection you should hook the function in template_redirect
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "functions, redirect, code" }
Customizing WP tables or adding new ones? I would like to extend user data, adding picture, department, phone, etc. You may achieve this adding custom fields to the usermeta, however I wonder if this techniques is deprecated and it would be better to create new tables with custom data to prevent future potential pitfalls when WP is updated. What is the right way?
You should avoid adding new tables or customising the existing tables to add fields for users. If you want to store a phone number etc, do it using user meta: add_user_meta( $user_id, 'riccardo_phone_number', '0123-456-7890' ); .... $phone_number = get_user_meta( $user_id ); User meta is a key and a value with a post ID in the database. There is no need for changes to the table structure/schema to add new information. Modifying the `WP_User` table will cause major issues with future upgrades of WordPress. When WordPress Core modifies their Database schema, you run the risk of it failing on update, or data destruction. Creating new tables and modifying the core tables also means writing custom SQL queries, duplicating the main query, and giving up all the APIs for data access, as well as introducing a new point of failure. Custom post types, post meta, and custom taxonomies are almost always a better choice, bringing other benefits with them.
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "user meta, table" }
Redirect Plugins.php to New Plugin Page I have a multisite install and need to redirect the default plugin page to another admin page that will handle plugins. For example, if they request `/wp-admin/plugins.php`, then it should redirect them to `/wp-admin/admin.php?page=pretty-plugins.php` if they are not a network admin. The code below is what I have come up with so far, but I need help finishing it. Any help and suggestions would be appreciated. function block_direct_plugin_page_access() { if ( ! current_user_can( 'update_core') && ) //And requests plugins.php { //Redirect to new plugin page because they are not a network admin. wp_safe_redirect( '[Insert Link Here]', 301 ); exit; } } add_action("muplugins_loaded", "block_direct_plugin_page_access");
After a little bit of trial and error, I finally got my code to work. This will redirect ` to ` if the current user doesn't have access to update core. add_action( 'admin_menu', 'block_direct_plugin_page_access' ); function block_direct_plugin_page_access() { global $pagenow; if ( ! current_user_can('update_core') && 'plugins.php' === $pagenow ) { if ( function_exists('admin_url') ) { wp_redirect( admin_url('admin.php?page=pretty-plugins.php') ); } else { wp_redirect( get_option('siteurl') . '/wp-admin/' . 'admin.php?page=pretty-plugins.php' ); } } }
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "plugins, multisite, wp admin" }
Converting HTML to Wordpress theme: integrating pages function and using its text editor, conditional enqueuing Recently I attempted to convert my static HTML to a Wordpress theme but to no avail. I was able to understand how to separate my code for my header, content, and footer, and I integrated the header and footer with the `home.php`. However, now I want to create new pages using the text editor in Wordpress and input the text/HTML into an area in the file. I created a template already, for the new pages, but I do not know the php to integrate it into the file. Also, I don't quite understand how to use the conditional `wp_enqueue_style` and `wp_enqueue_script` functions. I would like to make a parent page, then have all of its children have those CSS/JS files. Thanks for the help!
For editing content, I used the plugin Advanced Custom Fields. As for the conditionals, I just added `if (is_page_template('template_name.php')` before each `wp_enqueue_script`.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "pages, css, javascript" }
Hook/notify when any option or setting is added or updated I know about: add_option_{option_name} update_option_{option_name} but these need specific option names. What I am looking for is a way to know if and when _any_ option is changed (added or updated). What I am really trying to avoid is running a query to find all option names, then running a loop through them to add both `add_option_{option_name}` and `update_option_{option_name}` for those options dynamically. (If indeed this is the only way to do it, is this an alright way to do it?) Any suggestions?
Looking at the sources (core files, `wp-includes/option.php`) you can always find your target hook tags: add_action('added_option', 'wpse230212_callback_add', 10, 2); add_action('updated_option', 'wpse230212_callback_update', 10, 3); function wpse230212_callback_add( $option_name, $option_value ) { // do stuff on add_option } function wpse230212_callback_update( $option_name, $old_value, $option_value ) { // do stuff on update_option } Hope that helps.
stackexchange-wordpress
{ "answer_score": 7, "question_score": 4, "tags": "hooks, options, notifications" }
What is the replacement for rich_edit_exists()? A plugin inserts users into a database. If the user is an author, the visual editor isn't showing until the user saves their profile. I'm trying to figure out what setting isn't being added to the database and found the deprecated `rich_edit_exists()`. Is there a replacement?
This is stored in the _user meta_ table under the `rich_editing` meta key for each user. You could one of these (untested): 1) Add it for your specific users, e.g. via `add_user_meta( $user_id, 'rich_editing', 'true', true );` 2) Within the `wp_default_editor()` function, that determines the default editor, the `user_can_richedit()` function is applied. It checks for `get_user_option( 'rich_editing' ) === 'true'`, among other things. It's filterable through the `user_can_richedit` filter: /** * Filters whether the user can access the rich (Visual) editor. * * @since 2.1.0 * * @param bool $wp_rich_edit Whether the user can access to the rich (Visual) editor. */ return apply_filters( 'user_can_richedit', $wp_rich_edit ); 3) Try to filter the `get_user_option( 'rich_editing' );` if it's missing.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "plugin development" }
Custom template for post type not working I have a post type `shopping` and in my `single.php` I am trying to get a certain template for this post type. So I did: \\ in the single.php get_template_part( 'template-parts/content', get_post_format() ); and in `template-parts` directory, I created a file named `content-shopping.php`. But no matter what, the single template used is the default `content.php`. However, if I do something like this: if ( 'shopping' === get_post_type() ) { get_template_part( 'template-parts/content-shopping' ); }else{ get_template_part( 'template-parts/content', get_post_format() ); } then the template is used for that post type. I am not sure why the first method is not working. Any idea?
`get_post_format` and `get_post_type` are completely different. Post Formats can be one of the following: * 'standard' (default one) * 'aside' * 'chat' * 'gallery' * 'link' * 'image' * 'quote' * 'status' * 'video' * 'audio' And `shopping` is the **post type** you have created and not **post format**. You can add post format for the post type(shopping) like this add_post_type_support( 'shopping', 'post-formats' );
stackexchange-wordpress
{ "answer_score": 4, "question_score": 2, "tags": "custom post types, single" }
Link to WP-CONTENT not working We have a couple PDF files that are included in our WP-CONTENT folder which the links are not working. Trying to debug I created domain.com/wp-content/test.php and when I point the browser to this page I get a wordpress 404. Any idea what could be causing this? Below is a copy of our .htaccess file which is the only thing I can figure would be causing it but I don't see any issues. <IfModule mod_rewrite.c> RewriteEngine on RewriteRule !(js|ico|gif|jpg|png|css|swf|flv|libraries|maint|admin|login|logout|reg) index.php [QSA,L] </IfModule> # BEGIN WordPress <IfModule mod_rewrite.c> RewriteEngine On RewriteBase / RewriteRule ^index\.php$ - [L] RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule . /index.php [L] </IfModule> # END WordPress
I have experience with this issue and find solution maybe work with your problem 1. Check Wp-Content Permission change to 775 2. Delete or rename your .htaccess like .bkphtaccess 3. Setting permalinks as default and save 4. Turn back permalinks as your custom permalink and save If allowed new .htaccess will create automatic, if not copy text at the bottom permalink settings save as file .htaccess in root Wordpress Instalation try to access your link
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "404 error" }
WP Capabilities to Add Media, Use Media, But Not Edit Them I just want to have role that can specifically adding media, use the existed media, but not edit OR delete them. I was looking for the capability, but I don't see it listed. Or it's really impossible to do that? How can I do achieve it programmatically?
What you are asking is default behaviour for the author role. So you don't have to do anything. When an author is in the process of inserting somebody else's media in his post, it _looks_ like he can edit the properties, but this is only true for that current post. If he changes, for instance, the `alt` attribute, he will get a different `alt` attribute only for his own post. You could try to prevent that in the media manager, but that doesn't make sense, because when the html is inserted into the post, the author can change the attributes anyway.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "uploads, media, capabilities" }
Exclude current post from an array of posts? I'm trying to exclude the current post from an array and I know that the codex says that it's not possible to combine **post__in** and **post__not_in** in the same query... But in wordpress everything (well, almost...) is possible and I know that must be a way to exclude the current post from my posts array. If I can't use the together, how can I exclude current post from the array? Any hints are very welcome. This is my current query: $this_post = $post->ID; $args = array('post__in' => array(17,111,108,158), 'post__not_in' => array($this_post)); $posts = new WP_Query($args);
Use `array_diff()` to remove the current post ID from an array of other post IDs. $include = array( 17, 111, 108, 158); $include = array_diff( $include, array( $post->ID ) ); $args = array( 'post__in' => $include ); $posts = new WP_Query( $args ); Edit to include a point raised by Pieter Goosen\--If `$include` is not a hard-coded array of IDs but something that comes from the database, you should verify that it is not `empty()` prior to performing the query. Passing an empty array to `'post__in'` will get an unfiltered list of posts, rather than returning no posts as you might expect.
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "wp query, exclude" }
The post order is different for logged-in and non-logged-in users? I noticed that for some reason on my site, the post order changes depending on whether a user is logged in or not. When I am logged in as the admin, the posts display is chronological order. But when I log out, the oldest post is displayed first, then chronological order, and then the newest post is at the bottom. What is going on here? Update: I checked my theme's functions.php file and the extras.php file (which includes extra functions) and neither of them have any filters affecting the post order. Update: I changed my theme to Twenty Sixteen and am still having this issue. I also am on a clean install of Wordpress. Then I updated Wordpress to make sure I didn't accidently change something but I still have the issue.
I found out what was causing this problem. I had a plugin installed called Simple Posts Generator which I used to generate 10 sample posts for testing purposes. Since I generated the articles all at the same time, the _post_date_ value in the database was the same for each post, which confused Wordpress as to what post should come first. I fixed it by going into the database and manually changing the _post_date_ values so they are all different, which solved the problem. Now all my posts are sorted correctly in chronological order.
stackexchange-wordpress
{ "answer_score": -1, "question_score": 0, "tags": "posts, theme development, loop, users, login" }
No compression occurs on my jpegs after adding jpeg_quality hook to my functions.php file I'm attempting to perform some basic jpeg compression by using the jpeg_quality hook inside my functions.php file but there is no compression/resizing taking place. I'm only measuring file compression on jpegs added to the library after the functions.php file had been edited. Here is the code: function custom_jpeg_quality($quality) { return 20; } add_filter('jpeg_quality', 'custom_jpeg_quality'); Thanks in advance to anyone who can assist.
WordPress uses that when it resizes images to set the quality, but it will not go back and resize images it's already processed. If it did, your site would be continuously checking your uploads and grind to a halt You have these choices: * Delete your attachments and reupload them * Use a tool such as the regen thumbnails plugin to recreate the images ( will take some time ) These will only affect the image sizes, not the original image that was uploaded ( image size `full` )
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "functions, images, compression" }
Rewriting a page with a custom parameter I have an issue similar to this one: Rewrite Rule for Custom Page with Query Vars in URL We have those two rules we're trying to add through the Rewrite plugin. ![rewriting rules]( We tested it and the GET parameters don't seem to follow as shown here. ![rewriting analysis]( When using PHP on that resulting page to show the $_GET values, it's empty. The red bar on top of the parameters shows a tooltip saying "This query variable is not public and will not be saved". Our page is available here: < But we'd like to feed it dynamic with one or two parameters as such: < How do you make a custom GET parameter not public so this would work?
To fix this issue, we had to add the "query variables" into the `functions.php` of our theme to add them to the public variables. function add_query_vars_filter($vars){ $vars[] = "subject"; $vars[] = "param"; return $vars; } add_filter('query_vars', 'add_query_vars_filter'); This allowed us to retrieve the variables' value this way. `$subject = get_query_var('subject', false);`
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "url rewriting" }
Shortcode call not working in WP Template I'm working with a Visual Composer shortcode to call a text resizer into being. When using the Visual Composer or the classic WYSIWYG, if I insert it's shortcode [enlarge_text small='A' medium='A' large='A' default_value='medium'] into the editors it works with 0 issue. So in the interest of making my life easier, I went to add this into the Wordpress base templates with: <?php echo do_shortcode('[enlarge_text small='A' medium='A' large='A' default_value='medium']'); ?> Sadly, no joy. I've checked to confirm the base templates are using the content callout, and should I edit them incorrectly they definitely take down the site, so I feel I'm in the right place instead of this theme having some special custom set hidden away that I'm just missing. Thoughts? Thank you in advance!
First, check the quotes: <?php echo do_shortcode('[enlarge_text small="A" medium="A" large="A" default_value="medium"]'); ?>
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "theme development, shortcode, templates" }
Only Get A Certain Number of Posts From WP_Query I'm not sure what I'm doing wrong. None of my WP_Queries are returning the given number of posts. From what I can tell, it's returning all of them. How do I fix this? Here is the code I'm currently using for my loops: <?php wp_reset_query(); ?> <?php $review = new WP_Query(array( "posts_per_page" => 1, "category_name" => "reviews", 'nopaging' => true )); ?> <?php if($review->have_posts()): while($review->have_posts()): $review->the_post(); ?> <!-- Everything here works as expected --> <?php break; ?> <!-- I have to break the loop by force, which is bad --> <?php endwhile; else: ?> <!-- Placeholder content goes here --> <?php endif; ?> <?php wp_reset_postdata(); ?> What am I doing wrong? How do I fix this?
`nopaging=true` override `posts_per_page` and sets it to `-1` which will return all posts. Remove that and you should be fine
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "php, posts, wp query" }
Is there a global action for when a plugin is uninstalled? I need to do something anytime any plugin is uninstalled. There's a hook for when MY plugin is uninstalled but I don't see an uninstall equivalent of `deactivated_plugin`. Does uninstalling a plugin fire the deactivation action?
No, `deactivated_plugin` won't fire during a plugin's uninstallation process. But there are indeed two hooks that fire when a plugin is uninstalled: * `pre_uninstall_plugin`, which is called right before a plugin is uninstalled. It acts globally, targeting any plugin. * `uninstall_{$file}`, which fires after a specific plugin is uninstalled. Its scope it's limited to a unique plugin with basename `{$file}`. If you want to access the basenames of the whole plugins list, you can check the keys in the array that `get_plugins()` returns.
stackexchange-wordpress
{ "answer_score": 3, "question_score": 3, "tags": "plugins, actions" }
Open link in a new tab checked by default when adding a new link in visual post editor When adding a link in the WP visual post editor you have to click the settings after adding the link and then click the **Open link in a new tab** to have it add a link with a target in a new window/tab. I am looking for a way to have this automatically checked by default. Is there a filter or JavaScript code to do this? ![enter image description here](
Add this function in your theme's functions.php function my_enqueue($hook) { if ('post.php' != $hook ) { return; } wp_enqueue_script('my_custom_script', get_template_directory_uri() . '/js/myscript.js'); } add_action('admin_enqueue_scripts', 'my_enqueue');` In myscript.js place this code jQuery(document).ready(function(){ jQuery('#wp-link-target').prop("checked", true); }) It worked for me.
stackexchange-wordpress
{ "answer_score": 2, "question_score": 2, "tags": "links, tinymce, editor" }
Add post type pages with plugin Can I add the archive and single page for a custom post type added by my plugin? I know it will only have to be a best guess with contents like: <?php get_header(); ?> <h2><?php _e('My Post Type', 'my-slug'); ?></h2> <?php //get posts and list ?> <?php get_footer(); ?> Which would mean it would need to be possible for a user (or me) to override those pages in a theme using `archive-{post-type}.php` and `single-{post-type}.php` or something similar.
You can't without hooking a filter to recognise the files in your plugin BUT you can hook into the template_include filter and register your own file e.g. add_filter('template_include', 'my_function_name'); function my_function_name( $template ) { if( is_post_type_archive( 'post_type' ) ){ $template = dirname( __FILE__ ) . '/templates/archive-post_type.php'; } if( is_singular( 'post_type' ) ){ $template = dirname( __FILE__ ) . '/templates/single-post_type.php'; } return $template; } I was given this code by another WSE user when I had this exact need
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "custom post types, plugin development" }
Setting a fluid content width I'm thinking about setting the content width theme feature in my theme's functions.php file using: if ( ! isset( $content_width ) ) { $content_width = 600; } My understanding is this will set the max allowed width for any text and images in my theme. My layout is rather fluid (I don't have a fixed width) so would like to use a percentage value. How can I set the max content width to 100%? Ref: <
`$content_width` is a global variable that can indeed be used by themes and plugins to set a maximum width on content elements. Therefore it's always a fixed value in pixels. The plugins don't know about your `css`. However, this does not limit your possibilities in your theme. You can still set image sizes larger than `$content_width` and use them. Keeping the theme fluid is a matter of `css`. The thing you'll find is that embeds (amongst others) use `$content_width` to determine their max width. So make sure that it is larger than the max column in your site if you want it to fit neatly.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "theme development" }
Get (eventual) permalink from post within Edit Post in Admin panel I'm working on a plugin that needs to access grab the Permalink from within the Edit Post screen to send it to a link-shortener API. The catch is that I will need to grab the permalink before the post has been published (while it's in Draft state). So for instance, if I have a post titled "My New Post" and it's a draft and its post ID is 2048, my permalink currently shows with `mydomain.com/?p=2048` instead of `mydomain.com/my-new-post` if I use `<?php echo get_permalink(get_the_id()); ?>` I need a function that can grab the permalink that is displayed at the top of the Edit Post admin page which matches `mydomain.com/my-new-post`. Can anyone suggest a way of accessing this?
**get_post_permalink** won't work for draft or pending posts. But there are a couple workarounds you could use. Here there is a similar post with two options.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "plugin development, permalinks, wp admin, shortlink" }
Shortcode to eliminate <p> and replace </p> with <br> I have a filter that removes opening p tags and replaces closing p tags with a br tag sitewide. The client would like this filter in a shortcode that they can use only on specific portions of the site. Could the following code be adapted for use inside of a shortcode? add_filter( 'the_content', 'remove_p' ); function remove_p( $content ) { $paragraphs = array("<p>","</p>"); $noparagraphs = array("","<br>"); return str_replace( $paragraphs, $noparagraphs, $content ); } We've tried an assortment of plugins that toggle wpautop but were not happy with the results. Thanks in advance for any assistance.
You've got the $content available to you in your remove_p function - so inside that function just look for the existence of a special string (i.e. your "shortcode"), to allow the filter to do the str_replace. For example: if ( false !== strpos( $content, "[p-filter]") ) { $paragraphs = array("<p>","</p>","[p-filter]"); $noparagraphs = array("","<br>",""); return str_replace( $paragraphs, $noparagraphs, $content ); } else return $content; This will work as long as your client doesn't want to turn on/off your filter multiple times within a single POST object...if he does then it could still be done, but will be more complicated to implement.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "functions, filters, shortcode, the content, customization" }
Add Filter to get_next_posts_link As we see in the source, we can apply filters for `$attr`. So I create something like this function asdff(){ return 'class="iamclass"'; } add_filter('get_next_posts_link', 'asdff',10,2); or function asdff($attr){ $attr .= "class='iamclass'"; return $attr; } add_filter('get_next_posts_link', 'asdff',10,2); It should be like this at front end `<a href="#nextpage" class='iamclass'>`, but it doesnt work. My class doesnt appear. How to achive that, did i miss something at `add_filter` ?
You can indeed add a filter to `get_next_posts_link`, but it has a different name, namely `next_posts_link_attributes` Complete code would look like this: add_filter('next_posts_link_attributes', 'wpse_230552'); function wpse_230552() { return 'class="iamclass"'; }
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "plugins, posts, filters, links" }
How to rewrite a folder in WordPress? I'm using "The7" theme and don't want to use the standard Portfolio archive template. I have used the default template to create a page that looks great, let's call it `/our-portfolio/`. Currently the permalink structure for portfolio items is `/portfolio/item-1/`. Though the theme allows me to change the slug for the portfolio, if I do this, the `/our-portfolio/` page will be replaced with the Portfolio Archive page, which I don't want. So my question is, can I use a rewrite rule or a plugin to rewrite `/portfolio/item-1/` to `/our-portfolio/item-1/`?
I think you may be mixing up a couple of concepts here. Use the new template page you made and name it archive-portfolio.php. This will display all portfolio post types in your new template at `yoursite.com/portfolio` and the url for the portfolio items should take care of itself. They will still be at `yoursite.com/portfolio/item1` so no need to change the permalinks - or slug. If you want to change the single item display you need to edit `single.php`, change the name to `single-{post_type}`.php and it will be used automatically
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "permalinks, themes, url rewriting, htaccess" }
After upgrade to php 7 plugin/them updates broke I upgraded my Ubuntu server to php 7 and setup ssh2. Afterwards, my WordPress plugins/themes will not update. I am receiving the Unable to locate WordPress Content directory (wp-content). This feature worked fine prior using php 5. My permissions were not changed and remain 755 (folders) 644 (files). I am using the same ssh user as before, which is my primary user on the server. I unzipped the php7.zip file to create the pecl-networking-ssh2-php7 directory in my user's home directory. I made the extension and set it in the php.ini file. Any ideas on what is hanging the plugin updater?
I solved the problem by installing php-ssh2, which removes libssh2-php on the install. $ sudo apt-get install php-ssh2 I also had to change permissions on the wp-content folder to 775, but it worked leaving the wp-content/plugins at 755. $ chmod 775 wp-content
stackexchange-wordpress
{ "answer_score": 0, "question_score": 1, "tags": "plugins, php, updates, ssh" }
How to string lines from the_content() hook in WordPress? Inside my content-video.php template, I have the following codes: <iframe src="<?php echo get_the_content(); ?>" width="960" height="540" frameborder="0" allowfullscreen="allowfullscreen"></iframe> The `<?php echo get_the_content(); ?>` string the whole content which is normally a video link posted by the user and then embed with a frame. I would like to string only the First line which is normally the link and then display what's below the link into the post. Is their some way of doing so? Basically the codes should the be something like this: <iframe src="<?php echo get_the_content('Line 1'); ?>" width="960" height="540" frameborder="0" allowfullscreen="allowfullscreen"></iframe> <?php echo get_the_content('Line 2 & Below'); ?>
> I don't know any other way There is a much, **much** better way to do this - custom fields. ![Custom Fields]( As per these instructions in the custom fields docs, let's say you use the field name `iframe_url`: <iframe src="<?php echo esc_url( get_post_meta( $post->ID, 'iframe_url', true ) ?>" width="960" height="540" frameborder="0" allowfullscreen="allowfullscreen"></iframe> <?php the_content() ?> See how much cleaner that is? You've separated _data_ from _content_ ; no nasty regular expressions or string hacking.
stackexchange-wordpress
{ "answer_score": 0, "question_score": -1, "tags": "custom post types, php, functions, hooks" }
Get WordPress page Id inside customizer I'm trying to move to using the WordPress customizer more. I need to find a way to get the ID of the page the user is viewing in the window. I was wondering is this is possible in the customizer? Another question is, is it possible to use a loop to create a setting for each individual page? I'm trying to let the user upload an image to the customizer to use as a banner. So I want to be able to get the page id to uniquely create a setting for each page then in my theme grab the image if it exists. I know the customizer has gotten more advanced but I've done a bit of digging and cant find anything.
I think you work about the ajax call. Inside the theme, in the right frame works all default WP functions inside the loop. But if you get the post inside the customizer you can use the ajax call and get the id from the URL. ## Source Example ### JavaScript add_action( 'wp_ajax_fb_custom', 'fb_customizer_ajax' ); function fb_customizer_ajax() { if ( ! wp_verify_nonce( $_POST[ 'ajaxnonce' ], 'fb_customize_ajax_nonce' ) ) { die( -1 ); } $current_url = $_POST[ 'current_url' ]; $current_id = url_to_postid( $current_url ); echo $current_id . '<br>' . $current_url; die(); } ### PHP The same should be possible in php. Use the help of the function `url_to_postid()`, this return value is the ID of the post for a url. The url is in the global `_GET`, like `$_GET['url']`.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "theme customizer" }
How can I Use 2 databases with one WordPress install What I'd like to do is have the regular WordPress application run from its regular database, and then have a separate database for a game server which will hold all game data. What I need is to make a connection between the two so when someone signs up through WordPress, it automagically registers them in the game database as well. What would be the best way to go about doing this?
You can use the user_register hook to capture user information after their details are saved to the database.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "php, mysql" }
How to escape the single quote character in i18n translation strings? How should I properly escape the single quote character in a translation string? I'm using it as an apostrophe. For example: __( '404. This isn't the page you're looking for.', 'textdomain' ); I believe there are a few approaches but which is the proper way? **Approach 1:** Using the backslash: __( '404. This isn\'t the page you\'re looking for.', 'textdomain' ); **Approach 2:** Using the character entity: __( '404. This isn&apos;t the page you&apos;re looking for.', 'textdomain' );
Use the first option. translated strings are supposed to be "raw", and escaped only by the calling function. In addition many will not understand what `&apos;` mean and how to translate it without looking at the actual page which can be annoying.
stackexchange-wordpress
{ "answer_score": 7, "question_score": 6, "tags": "translation, localization" }
How to escape single and plural i18n text strings? I've come across the `esc_html_e()` and `esc_attr_e()` functions which allow me to escape translated text strings. I'm now using these instead of `_e()` where appropriate. The `_n()` function allows for both single and plural forms to be translated. I don't think there's an `esc_attr_n()` function in WordPress. How can I escape the translated text in this case? Here's my current use of the `_n()` function: printf( _n( '1 item', '%d items', $count, 'textdomain' ), number_format_i18n( $count ) ); Ref <
`esc_html_e()` and `esc_attr_e()` are merely wrapper functions for `_` to save a little bit of typing and help with readability. You're right, there isn't one for `_n`, so you'll just need to do the "wrapping" yourself: printf( esc_attr( _n( '%s item', '%s items', $count, 'textdomain' ) ), number_format_i18n( $count ) );
stackexchange-wordpress
{ "answer_score": 5, "question_score": 4, "tags": "translation, localization" }
Where to find the html for Wordpress site? Where can I find the HTML for a Wordpress site? I'm using the "X" child theme. I found a tutorial explaining how to achieve an effect that I want and it says that "All I need is an HTML markup and to call the script". Also, what does "calling the script" mean? The child theme has a PHP file and a CSS file (the tutorial gives me a javascript file and a CSS file, where would the javascript go? In the PHP file?)
You got javascript file and CSS file! Then you have to put those files in you child theme folder like `themes -> your_child_theme_folder -> js(if you dont have js folder then create one) and place your js file here` AND you have to put you css file in css folder inside your child theme. > Now you need to call js file from functions.php If you dont have functions.php file in you child theme folder then create it first. Here is the code for calling js file function wpdocs_theme_name_scripts() { wp_enqueue_script( 'script-name1', get_stylesheet_directory_uri() . '/js/YOUR_JS_FILE_NAME', array('jquery'), true ); //Path of you js file } add_action( 'wp_enqueue_scripts', 'wpdocs_theme_name_scripts' ); In the above code `script-name1` is the custom name that you will give to every script you call and the name shud be unique. And I hope you are already aware of calling css file..
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "php, css, javascript, child theme, html" }
Server Hardware for Wordpress Is this hardware good for 5000/7000 daily user? _Amazon EC2 instance_ | vCPU | Mem (GiB) | Storage SSD (GB) --------------------------------------------- r3.large | 2 | 15,25 | 3 x 40 3 SSD Storage are used for: 1. Ubuntu SO 2. Wordpress 3. MySQL 5.6 Server service are: * Apache 2.4 * PHP 5.6 (PHP-FPM) with OpCache * Memcache * MySQL 5.6 Wordpress use: * W3 Total Cache * SEO Yoast * AVADA theme The question is: I'm scared! 2 CPU it seem few... are really few?
This is why AWS is great. Monitor you server and if that's either too much or not enough, scale up or down. But it sounds like more than enough.
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "performance" }
How to create Blog Post Specific Widget I want to create widgets which will display based on post. I have considered the option of creating a widget post type using Advanced custom post type plugin and populate this widget while writing post. What I want to understand is, is there any out of box functionality available which can be achieved easily. Or in other word if a widget can be customised to be display based on blog post? Thanks & Regards
Since it sounds like you're trying to do this without code I would do it this way: Create an 'Advertisement' post type which supports categories. Then use a 'Related Posts' widget that allows you to select custom post types as well as related categories. Possibly one of these And use the widget settings to call the appropriate Ad UPDATE: Not sure how clear my answer is but to use your example - you have a blog post in the category 'dairy' in your sidebar you use the 'Related Posts' widget to display posts of type 'Advertisement' in the category of the current post. Obviously, set up your Advertisement posts in the appropriate categories.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "custom post types, widgets, blog, blog page" }
Redirect if current user is logged out and current page is /my-account I need my woocommerce site to do the following. If the user visits the /my-account page but is logged out I need it to redirect to the /login page. I currently have half of it (if is logged out) but I need to test if it's the my-account/ page as well which I can't figure out. Any help would be really appreciated! if ( !is_user_logged_in()) { wp_redirect( '/login' ); die(); }
Fixed! I had to use the wp hook which means that the redirect function is only run once the whole page is loaded! Sweet :) add_action( 'wp', 'redirect' ); function redirect() { if ( is_page('my-account') && !is_user_logged_in() ) { wp_redirect( home_url('/login') ); die(); } }
stackexchange-wordpress
{ "answer_score": 8, "question_score": 2, "tags": "woocommerce offtopic" }
CPT defaults to single.php? This is more of a clarification question, but if I don't have a `single-CPT.php` script in my child theme, then will all my CPTs default onto `single.php`? I am just wanting to clarify more than anything. It appears that way on my local dev, but I thought this wasn't the case?
Yes, they will. You will find the WordPress template heirachy useful, particularly this graphic: ![enter image description here]( This shows how the templating system works - in particular, how WordPress will select the most specific template it can find, with fallbacks to the least specific (eventually, to `index.php`). In your case, you'll see in there that `single-$posttype.php` falls back to `single.php`, then `singular.php`, then finally `index.php` (direct link to single post section of docs).
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "custom post types" }
Search query -> Show all pages except certain template These are my arguments for the search query: $args = array( 's' =>$s, 'post_type' => array( 'post', 'p24_cases', 'page') ); Using these arguments, the search results will show all pages that contain the search word. I want to show all pages, except for the page template called 'bedankt' (thanks in Dutch).
## REWORKED ANSWER TO ANSWER THE QUESTION In order to exclude all pages with a certain template, all you need to do is to run a `meta_query` to exclude all pages with the custom field `_wp_page_template` set to `bedankt`. Remember, WordPress saves the template assigned to a page as a hidden custom field called `_wp_page_template` With this in mind, we can do the following $args = [ 's' => $s, 'post_type' => ['post', 'page', 'p24_cases'], 'meta_key' => [ [ 'key' => '_wp_page_template', 'value' => 'bedankt.php', 'compare' => 'NOT IN' ] ] ]; ## ORIGINAL ANSWER - misread question You simply need to get the post ID of that page, anf then pass it as an array to `post__not_in` 'post__not_in' => [1], // Replace 1 with actual page ID Or pre PHP 5.4 'post__not_in' => array( 1 ), // Replace 1 with actual page ID
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "query, search, post type" }
Wp Admin Bar Customizing Labels I would like to replace the Label the Plugin WP Custome Area sets on the admin bar. This is the initial parto of code that sets the menu title: public function build_adminbar_menu($wp_admin_bar) { $wp_admin_bar->add_menu(array( 'id' => 'customer-area', 'title' => __('WP Custome Area', 'cuar'), 'href' => admin_url('admin.php?page=wpca') )); This is the hook i tried but without any joy... function replace_content() { $content = $wp_admin_bar->get_node('customer-area'); $content->title = __('Custom Title', 'cuar'); } add_filter('the_content','replace_content'); Any help will be much appreciated
Don't use add_filter with the_content that way; that is meant for a different context - when you are filtering a returned WP post object. Try something like this instead: function replace_customer_area_title( $wp_admin_bar ) { $newtitle = __('Custom Title', 'cuar'); $wp_admin_bar->add_node( array( 'id' => 'customer-area', 'title' => $newtitle, ) ); } add_filter( 'admin_bar_menu', 'replace_customer_area_title' , 33 ); `add_node` should modify an existing node, if found. This must run after the original node was added with priority of 32, so we have used 33 here as an example.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "title, admin bar, customization" }
WooCommerce Variable Product Price not showing on single product page I made custom `attribute` for `variation` other than size or colour, but when i apply as `variation` to this `attribute` its not showing on single page.
It's seems you have all variations same price. That's why it's not showing, it's a WooCommerce default behavior. You can change this WooCommerce default variable price filter with this hook. add_filter('woocommerce_show_variation_price', function() { return TRUE;});
stackexchange-wordpress
{ "answer_score": 24, "question_score": 12, "tags": "woocommerce offtopic" }
How to add search to menu? How to add search to menu? I want to have: add_filter('wp_nav_menu_items','add_search_box_to_menu', 10, 2); function add_search_box_to_menu( $items, $args ) { if( $args->theme_location == 'primary' ) return $items. get_search_form (); return $items;} in my `functions.php`. But it calls standard search template. I have created `searchform.php`in my child theme folder. This part of example, but its hardcoded. return $items."<li class='menu-header-search'> <form action=' id='searchform' method='get'> <input type='text' name='s' id='s' placeholder='Search'></form></li>";
Use the get_search_form filter: add_filter('wp_nav_menu_items','add_search_box_to_menu', 10, 2); function add_search_box_to_menu( $items, $args ) { if( $args->theme_location == 'primary' ) return $items. get_search_form(); return $items; } add_filter( 'get_search_form', 'custom_search_form' ); function custom_search_form( $form ) { ob_start(); // get_stylesheet_directory will get // the main directory of the child theme include( get_stylesheet_directory() . '/searchform.php' ); $form = ob_get_clean(); return $form; }
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "menus, templates, search" }
Prevent add_filter being applied to wp-admin pages I'm applying a filter to a custom fields plugin. add_filter('acf/load_value', word_swap); My problem is this applies it to pages within the wp-admin also. I only want the filter applied to the actual WP site, and not the admin panel. How can I prevent the filter being applied to the wp-admin pages? I imagine I'd do something like if(page == 'wp-admin') add_filter('acf/load_value', word_swap);
You need the `!is_admin()` check. This will return false on admin pages, failing your condition. On front end pages, that condition will return true, executing your conditional statement if ( !is_admin() ) { // Do something only on frontend }
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "filters, wp admin" }
how to get list of all users and their metadata How do I get a list of all users with role = 'Customers' including all the metadata per user, means wp_users + wp_usermeta. Query blow does not generate the wanted results. $query = "SELECT * FROM wp_users INNER JOIN wp_usermeta ON wp_users.ID = wp_usermeta.user_id ORDER BY ID DESC'); "; $data = $wpdb->get_results($query,ARRAY_A); But that list is not correct. It shows each user x times depending on the number of rows in wp_usermeta. How can I filter it? That each user shows per record all his user + metadata?
I think you should use wp-api functions which will do everything for you. * get_users() function will get all users data just define fields which u require. * get_user_meta() function will get usermeta data. $users = get_users( array( 'fields' => array( 'ID' ) ) ); foreach($users as $user){ print_r(get_user_meta ( $user->ID)); }
stackexchange-wordpress
{ "answer_score": 28, "question_score": 19, "tags": "user meta, wp user query" }
Welcome Email Going to Spam The user sign up welcome email is going directly to spam, Gmail says `this email may not have been sent by ****@gmail.com` Would setting up a domain specific email address and changing the site owner email to `***@thedomain.com` help keep these messages from going into spam folders?
Add SPF record to your DNS so emails from your server IP are classified as legitimate Edit. Do the above with what you said. "Would setting up a domain specific email address and changing the site owner email to ***@thedomain.com help keep these messages from going into spam folders?" This will be fine as it will be the smtp server on your Web server which is sending the emails and hence will now get through spam checks
stackexchange-wordpress
{ "answer_score": -1, "question_score": -3, "tags": "email, email verification" }
How to choose the content from a post which is in the right category? I have a shortcode, which contains the post title. This shortcode loads in the frontend the content from a post. Thats works fine: function title_content($atts, $content = null ) { global $wpdb; $post_id = $wpdb->get_var($wpdb->prepare("SELECT ID FROM {$wpdb->posts} WHERE post_title = %s",$content)); $getpost = get_post($post_id); return $getpost->post_content; } add_shortcode( 'content', 'title_content'); But I have in different categories posts with the same post title. So this loads sometimes the wrong content, because I don't want to use the post id or post slug in the shortcode. I just want the the contents from posts with the right category (name "blog"), so I have no conflicts with the same post title anymore. Has someone an idea, how I can solve this?
You can use the function `in_category` to test if a post is in a certain category. It takes one or more categories and the post as input. So you may differentiate your function like this: function title_content($atts, $content = null ) { global $wpdb; $post_id = $wpdb->get_var($wpdb->prepare("SELECT ID FROM {$wpdb->posts} WHERE post_title = %s",$content)); $getpost = get_post($post_id); if (in_category('blog',$getpost)) { return $getpost->post_content; } else { ... do something else ... } }
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "categories, shortcode" }
Custom taxonomy hide meta box but show in menu If set `show_ui` `false`, this hide the taxonomy meta box and admin menu link both, how to hide only meta box? $args = array( 'hierarchical' => true, 'labels' => $labels, 'show_ui' => false, 'show_admin_column' => false, 'show_in_menu' => true, 'show_in_nav_menus' => true, 'query_var' => true, 'rewrite' => array( 'slug' => 'wheel' ), ); register_taxonomy( 'wheel', array( 'product' ), $args );
You're looking for the `meta_box_cb` argument. $args = array( 'hierarchical' => true, 'labels' => $labels, 'show_ui' => false, 'show_admin_column' => false, 'show_in_menu' => true, 'show_in_nav_menus' => true, 'query_var' => true, 'rewrite' => array( 'slug' => 'wheel' ), 'meta_box_cb' => false, ); register_taxonomy( 'wheel', array( 'product' ), $args ); You can also define a custom callback function for displaying your own metabox if you'd like. Refer to the documentation for register_taxonomy().
stackexchange-wordpress
{ "answer_score": 7, "question_score": 5, "tags": "custom taxonomy, metabox, taxonomy" }
How to allow users to view pending posts of a specific custom post type? I have a form on the front end that allows users to post a custom post type. The posts enters the database as **pending** for later moderation, how do I allow users to view these posts on the front end? Currently I get a 404 because it is in pending status, but in this case it is okay to display the post.
You need to make a custom query to display these pending posts. Here is an example using `get_posts()`: $args = array( 'post_type' => 'post_type_name', 'post_status' => 'pending', // -1 shows all 'posts_per_page' => -1, ); $pending_posts = get_posts( $args ); foreach( $pending_posts as $pending_post ) { // post object properties $id = $pending_post->ID; $title = $pending_post->post_title; $content = $pending_post->post_content; // output echo $id; echo $title; echo $content; } If you need to filter an existing query instead of making a new one (for example, on an archive page), you should use `pre_get_posts()`.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "filters, user roles" }
How to check if comments are paginated? I'm trying to determine if there's more than one page of comments in single.php. In archive.php I can do something like this to check if there's more than one page of posts: if ( $wp_query->max_num_pages > 1 ) { // There's more than one page of posts in this archive. } As far as I can tell, this doesn't work for comments. How can I check if comments are paginated in single.php?
_Just some additional info for the main comment query:_ Since you mentioned the global `$wp_query` object, we can see that it stores: $wp_query->max_num_comment_pages = $comment_query->max_num_pages; in the main comment query in the comments template. There exists a wrapper for this, namely: get_comment_pages_count(); that's available after the main comment query. If we need it before the main comment query runs, then we might check if `get_comments_number( $post_id )` is greater than `get_option( 'comments_per_page' )`. But we should keep in mind that the `comments_per_page` parameter can be modified through e.g. the `comments_template_query_args` filter.
stackexchange-wordpress
{ "answer_score": 2, "question_score": 2, "tags": "php, comments, pagination" }
Adding Extra Customer Email In Woocommerce Checkout I want to know how to call out a extra email filed in woocommerce checkout page. By default there is a email filed for customers to fill in, once he/she checkout they will receive the order copy. I just want to call out another email filed eg Email 2 then that email also should receive the copy. Already tried finding for plugins but didn't work. Any idea to execute..! Thank You
This solution seems to be very close to what you need. But can't say duplicated as you will need to do some coding to get 2nd email address. Check out. Adding a second email address to a completed order in WooCommerce To get email field from checkout try get_post_meta( $order_id, '_custom_field', true ); now you might want to get $order_id add_action ('woocommerce_thankyou', 'myfunction'); function myfunction($order_id) { $order = new WC_Order($order_id); print $order_id.', '.$order->get_total(); } Hopefully this will take you in right direction.
stackexchange-wordpress
{ "answer_score": 0, "question_score": -1, "tags": "woocommerce offtopic" }
null callback in add_settings_section Some code I'm looking at from a Plugin contains this line add_settings_section("section", "Settings", null, "theme-options"); which has a `null` callback. Having looked at < it says > $callback - (string) (required) Function that fills the section with the desired content. The function should echo its output. So, why is this `null` and what are the implications?
`$callback = NULL` means there is the `$callback` variable but it has no the `value`. In this case, unless you add any setting fields by `add_setting_field()` and register those settings by `register_setting()`, you'll get the `Settings` subheader on the `Settings` page without any content in this section. Here is an old tutorial which can be useful to show what I'm talking about. See the third screenshot and the code above it. Also: * add_setting_field() * register_setting() * Settings API
stackexchange-wordpress
{ "answer_score": 2, "question_score": 1, "tags": "plugin development, settings api" }
Add a "Next Post" & "Previous Post" styled button manually to a post Can anyone walk me through the exact steps? I want to create two buttons that sit next to each other at the bottom of a post for the NEXT and PREVIOUS posts...I want to be able to insert this manually (html), and using a style/class to do it. I'm assuming I have to do something in the functions.php file first? Then create a custom CSS button? Then add the code in the bottom of my post?
This is standard WordPress functionality, contained in `previous_post_link` and `next_post_link`. You don't need to edit `functions.php`. Just add to your template: <div class="buttons"> <span class="previous-button"><?php previous_post_link() ?></span> <span class="next-button"><?php next_post_link() ?></span> </div> Now you can style the buttons with `css`. Follow the codex links for customizing options to the functions.
stackexchange-wordpress
{ "answer_score": 1, "question_score": -4, "tags": "php, css, previous, next" }
.htaccess home configuration How to configure .htaccess to this: I need that my home page is < but I cant do this. Anyone want help me please? Thanks! Now, my htaccess is : # BEGIN WordPress <IfModule mod_rewrite.c> RewriteEngine On RewriteBase / RewriteRule ^index\.php$ - [L] RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule . /index.php[L] </IfModule> # END WordPress
Try this: <IfModule mod_rewrite.c> RewriteCond %{HTTP_HOST} ^www\.mydomain\.com [NC] RewriteRule ^(.*)$ [L,R=301] </IfModule>
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "htaccess" }
Update post meta - Custom field does not match meta-key I am trying to update my acf with `update-post-meta`: //ga_analytics_settings update_post_meta($my_post, 'ganalytics_settings', serialize($ganalytics_settings)); `$ganalytics_settings` is an array, which I would like to store `serialized` within the field. ![enter image description here]( However, I get the following condition is not met(taken from meta.php): function update_metadata($meta_type, $object_id, $meta_key, $meta_value, $prev_value = '') { global $wpdb; if ( ! $meta_type || ! $meta_key || ! is_numeric( $object_id ) ) { return false; //I am getting here in, but I do not know why. } Any suggestions what I might do wrong? I appreciate your reply!
Arrays are serialized by default, so just do update_post_meta($my_post, 'ganalytics_settings', $ganalytics_settings); < > $meta_value (mixed) (required) The new value of the custom field. A passed array will be serialized into a string.(this should be raw as opposed to sanitized for database queries) Default: None Also, make sure that `$my_post` is post ID, not the post object. And, if you want to update ACF field, you should use it's `update_field` function. <
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "php, advanced custom fields, post meta" }
Wordpress multisite apply different options over each site from same plugin I created a plugin for the bootstrap navbar. Then I created an option page for my plugin. In my options page, I have two types of navbar (Default navbar and Full-width navbar) you can only choose one of them. I want to use WordPress multisite and create two sites within it. Then in the first site show the Default navbar and, in the second site, show the full-width navbar. Can I can activate the same plugin in each site and use different options in each site? Or must I install WordPress two times then using the plugin in each WordPress installation folder?
Put the plugin in the `wp-content/mu-plugins` directory. Each site in your network has its own `_options` table in the database so as long as you are using built-in WP functions for handling your plugin's options, each site will have its own distinct set of options.
stackexchange-wordpress
{ "answer_score": 3, "question_score": 3, "tags": "plugin development, multisite" }
List child pages alphabetically I am using the following code to list sub pages of a particular page. How would I change ot to sort by alphabetical order? <?php $args=array( 'post_parent' => 15901, 'post_type' => 'page', 'orderby' => 'the_title', ); $my_query = null; $my_query = new WP_Query($args); if( $my_query->have_posts() ) { ?> <ul> <?php while ($my_query->have_posts()) : $my_query->the_post(); ?> <li><h4><a href="<?php the_permalink() ?>"> <?php $brand_name = get_post_meta($post->ID, 'brand_name', true); ?><?php echo $brand_name; ?> </a></h4> </li> <?php endwhile; } ?> </ul> <?php wp_reset_query();?>
Please change `'orderby' => 'the_title'` to `'orderby' => 'title'` then you will get the posts in alphabetical order.
stackexchange-wordpress
{ "answer_score": 1, "question_score": -1, "tags": "list" }
wp_update_user() does not update user_data With code below, I try to update the email address of a user. The $_POST is correct, but the data is not saved into wp_users table. $user_id = $_POST['ID']; // correct ID wp_update_user( $user_id, 'user_email', $_POST['user_email']); // correct email address Also tried this with success: wp_update_user( array( $user_id, 'user_email', $_POST['user_email']) ); What is wrong with this update?
The function needs an array with the parameters. See The Codex. Also, you map the parameter with the value: ex. `'user_email' => $_POST['user_email']`. In your example, the code should look like this: $user_id = (int) $_POST[ 'ID' ]; wp_update_user( array( 'ID' => $user_id, 'user_email' => $_POST[ 'user_email' ] ) ); Also, the important hint: you should validate the data. Especially the data from the `$_POST` array. Maybe you're doing this, and it is not in your example source.
stackexchange-wordpress
{ "answer_score": 8, "question_score": 4, "tags": "users" }
Hide specific content from excerpts I am using Inked Blog to generate lists of articles on a page. However, I need to remove a specific headline (with the class `sow-headline-container`) from the excerpts. This is a bit of a struggle, but using the code from How to hide <pre> and <table> content from auto-generated excerpts? I managed to remove the headline. However, this resulted in all post excerpts on the page to be the same. Anyone has any clue to why this is happening? I am using Wordpress 4.5.3 with a custom theme based on Customizr 3.4.2.1 as well as the Inked Blog from Page Builder by SiteOrigin 2.4.10 Thank you in advance! :)
Ok, I've found the answer myself through a lot of Googling :) If anyone else is struggling, this pastebin provides a solid solution for stripping out headings from the excerpts. The solution was provided by Michael at the Wordpress Support Forum.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "content, excerpt" }