INSTRUCTION
stringlengths
11
999
RESPONSE
stringlengths
0
999
SOURCE
stringlengths
16
38
METADATA
dict
Paginate Links function: Page 1 doesn't work I got this: $pagination_args = array( 'base' => '%_%', 'format' => '?listpostspage=%#%', 'total' => $the_query->max_num_pages, 'current' => $paged, 'show_all' => false, 'end_size' => 1, 'mid_size' => 2, 'prev_next' => true, 'prev_text' => __( 'Zurück', 'Theme' ), 'next_text' => __( 'Weiter', 'Theme' ), 'type' => 'plain', 'add_args' => false, 'add_fragment' => '' ); Strangely the page 1 link is always the page im currently on? What is wrong?
The Base is the Problem: 'base' => add_query_arg('listpostspage','%#%'), Here ist the full code: $pagination_args = array( 'base' => add_query_arg('listpostspage','%#%'), 'format' => '?listpostspage=%#%', 'total' => $the_query->max_num_pages, 'current' => $paged, 'show_all' => false, 'end_size' => 1, 'mid_size' => 2, 'prev_next' => true, 'prev_text' => __( 'Zurück', 'Theme' ), 'next_text' => __( 'Weiter', 'Theme' ), 'type' => 'plain', 'add_args' => false, 'add_fragment' => '' ); Thanks goes to raison over at stackoverflow who posted this answer.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "pagination, paginate links" }
Function has_custom_logo when used in Customizer I'm attempting to integrate the `custom-logo` functionality introduced in 4.5 and I'm running into some issues with the Customizer interface. I'm checking `has_custom_logo` and, if it's false, I'm providing a text version of the site name and description as a fallback. It works perfectly fine when you add a custom logo. However, when you "Remove" it, it appears `has_custom_logo` still returns `true`. Example: if ( function_exists( 'the_custom_logo' ) && has_custom_logo() ) { the_custom_logo(); } else { echo 'Fallback'; } Anyone else had any luck with something similar?
You have it around the wrong way `has_custom_logo()` will return false if there is no logo. `function_exists( 'the_custom_logo' )` however will return true if you are using a version of Wordpress that support this function. So if you seperate your if statement like below it will work. if( function_exists( 'the_custom_logo' ) ) { if(has_custom_logo()) { the_custom_logo(); } else { echo "No logo"; } }
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "theme customizer, logo" }
Running custom defined WP-CLI commands without Wordpress installation present I have registered custom commands that scaffording some files. These commands don't rely on any wordpress funcionality, basically outputs some files with content (what commands do is irrelevant in this problem, so I won't paste here any code). Example command: `wp make:some file` When I run these command **when Wordpress is installed everything works perfectly** , but **if there is no Wordpress wp-cli alerts** with: Error: This does not seem to be a WordPress install. Pass --path=`path/to/wordpress` or run `wp core download`. There is any way to run that commands without active Wordpress installation present?
This may be helpful. < This is what actually `wp-cli` tries. $_SERVER['HTTP_HOST'] = 'example.com'; define('WP_ADMIN', true); require('wordpress/wp-load.php'); You must have these WordPress files files and the database. So the answer is NO unless you create hack. I am not aware of any. * * * If you pass: $ wp make:a.txt --skip-wordpress Error: This does not seem to be a WordPress install. Pass --path=`path/to/wordpress` or run `wp core download`. * * * wp --version WP-CLI 0.23.1
stackexchange-wordpress
{ "answer_score": 0, "question_score": 1, "tags": "wp cli, command line" }
How to get post's current parent term ID? How do you get the ID of the parent term of the current child term assigned to a post. For a custom taxonomy? Custom taxonomy: "location" Countries * Japan * USA * Mexico Cities * New York * Austin Say we are on a post assigned to "Japan" how do I get the ID of the parent called "Countries"? For this case it doesn't matter if it takes the highest parent or just the direct parent. I found this: $term_id = 21; $child_term = get_term( $term_id, 'location' ); $parent_term = get_term( $child_term->parent, 'location' ); But it doesn't work.
If you just need IDs, `get_ancestors` will return an array of parents for any type of object: $term_id = 21; $ancestors = get_ancestors( $term_id, 'location' );
stackexchange-wordpress
{ "answer_score": 0, "question_score": 1, "tags": "php, custom taxonomy, taxonomy, terms" }
How to delete old custom-css-stuff in the customizer-live-preview? I have a problem in the **customizer**. I want to see the **live-preview** from the CSS **pseudo-elements** and **custom_css** , too. So I append the `<style>` in the `<head>` like this, in the _customizer.js_ : wp.customize( 'custom_css', function( value ) { value.bind( function( newval ) { $('head').append("<style>"+ newval + "</style>"); } ); } ); So every change, append the style in the head. !<head> This is ok with the pseudo-elements, but when i delete the custom_css in the customizer: the change would be not remove. How can I delete the old custom-css-stuff in the customizer-live-preview? Thanks for your help. :)
`<style>` tag accepts all the global HTML attribute, including class and id. So, you could do something like this: wp.customize( 'custom_css', function( value ) { value.bind( function( newval ) { if ( $("#my-custom-style").length > 0 ) { $("#my-custom-style").remove(); } $('head').append("<style id="my-custom-style">"+ newval + "</style>"); } ); } );
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "theme customizer" }
How do I remove all hyperlinks that begin with a #? Facebook's Instant Articles rejects articles that contain hyperlinks to the current page (e.g. `<a href="#_ftn1">[1]</a>`). How can I filter the post content to remove these links before publishing to Facebook Instant Articles? I'm aware of a similar question on StackOverflow: How to remove hyperlink of images in wordpress post?, but my RegEx skills aren't good enough to convert that to what I need. PS - I'm using the semi-official Instant Articles for WP, which means I can filter `instant_articles_content`. PPS - It would be nice to know both how to remove the link but leave the link text, and how to remove both the link and the link text.
Inspired by @Samuel Elh, but accounting for single or double quoted attributes and a `href` that might not be the first attribute of an anchor: function wpse_227315_strip_hyperlinks( $content ) { preg_match_all( '!<a[^>]*? href=[\'"]#[^<]+</a>!i', $content, $matches ); foreach ( $matches[0] as $link ) $content = str_replace( $link, strip_tags( $link ), $content ); return $content; } add_filter( 'the_content', 'wpse_227315_strip_hyperlinks' ); ~~Note this will completely remove the link node/HTML from the post content.~~ This will replace the HTML link with just the inner text.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "facebook, regex" }
Secondary menu in WP 4.5 There's a lot to read about secondary menus in WP, however it looks like the tricks are for older WP version. I see that WP 4.5 supports multiple menus in the dashboard. What's not clear, once you have made your secondary menu, is how to insert it in theme location (in header for example) Does it still takes this? <?php wp_nav_menu( array( 'theme_location' => 'secondary-menu', 'menu_class' => 'topper', 'fallback_cb' => '') ); ?> Moreover, Do i need to place this code in functions.php? add_action( 'init', 'my_custom_menus' ); function my_custom_menus() { register_nav_menus( array( 'primary-menu' => __( 'Primary Menu' ), 'secondary-menu' => __( 'Secondary Menu' ) ) ); } Last question is: will it be automatically visible in the mobile menu version? Thans
Yes, you need to add this: add_action( 'init', 'my_custom_menus' ); function my_custom_menus() { register_nav_menus( array( 'primary-menu' => __( 'Primary Menu' ), 'secondary-menu' => __( 'Secondary Menu' ) ) ); } to your functions.php. It will create the menu locations in the menu admin area. More info: < In your theme, usually in header, you need to add this line where you want your secondary-menu: <?php wp_nav_menu( array( 'theme_location' => 'secondary-menu', 'menu_class' => 'topper', 'fallback_cb' => '') ); ?> More info here: < If you want to customize the menu code you can create a custom walker, you can refer to: < As for the last question, it should be but it's theme related.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "menus" }
Can't get order_by meta_value_num to work properly This query is working ALMOST as intended, but for some reason I can't get it to order by the custom field `opl_submission_tempo`. That field is set up to be a number, so I'm not sure where I went wrong here. $tempo_query = new WP_Query( array( 'post_type' => 'opl_tempo_submission', 'order_by' => 'meta_value_num', 'meta_key' => 'opl_submission_tempo', 'order' => 'ASC', 'posts_per_page' => 1, 'meta_query' => array( 'relation' => 'AND', array( 'key' => 'opl_submission_exercise_type', 'value' => $exercise_type, 'compare' => '=' ), array( 'key' => 'opl_submission_exercise_number', 'value' => $exercise_number, 'compare' => '=' ) ) ) );
There is no `order_by`. Change `order_by` to `orderby` and it should work. The default value of `compare` is `=` so it is unnecessary, you can remove it. Also, you should specify `type` of the `meta_value` if it is a specific type rather than the default `CHAR`.
stackexchange-wordpress
{ "answer_score": 2, "question_score": 1, "tags": "custom post types, plugins, php, wp query" }
Cloud flare, cache, minify question If I am using Cloud Flare to serve my site, and use their Cache and minify options, is there sense in caching and minifying at the Wordpress level as well? Is this a waste of time or do I get a double positive impact?
In general no, there is no advantage in having two caching entities in the way of each request. But you should be careful and understand how the caching works. For example cloudflare do not cache your pages in a central repository but each data center has its on cache so in an edge case you might get many requests at the same time from all of them, or a bug in one might flood your site. The bigger your site is the more protection you will want against edge cases, and you will want to have as much caching layers as it makes sense, but for small sites it is probably not needed and just complicates the maintenance of the site.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "cache" }
How to handle single entries of a custom post type? I have a custom post type called Projects. It contains a text-area "project description" and a repeater image field. I know that I can use the function WP_Query to return an array containing all my Projects post. This works when I want to show all the projects in one page. My question is how do I handle single entries in the Projects post type. More specifically, I want to know about the function that returns reference to a single entry of Project post type and the template file to be edited so as to achieve the styling of that single custom post page.
As per comments the single view of your CPT will be handled according to template hierarchy. Within appropriate template you can use template tags normally, so simply `get_post()` without arguments will get you a current instance. It is a little more tricky if you want to refer to a _specific_ post in code outside of its context. The most reliable within custom site is hardcoding its ID. Personally I also use `get_page_by_title()` (despite name can work on arbitrary post type) which is easier for human to read, but depends on title staying unchanged.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "custom post types" }
Querying posts from only one category and exluding the latest post I want to run the loop so that it retrieves posts from only one particular category AND outputs only 4 posts AND excludes the latest one. To query only one category, I found this: <?php query_posts('cat=1'); ?> <?php if ( have_posts() ) : while (have_posts() ) : the_post(); ?> <?php the_content(); ?> <?php endwhile; endif; ?> And to exclude the latest post and output only 4 posts, I found this: <?php query_posts('posts_per_page=4&offset=1'); ?> <?php if (have_posts() ) : while ( have_posts() ) : the_post(); ?> <?php the_content(); ?> <?php endwhile; endif; ?> However, I don't know how to combine the two. Can I do that, or is there a better way?
Try this code global $myOffset; $myOffset = 1; $paged = get_query_var('paged') ? get_query_var('paged') : 1; //Use 'page' instead of 'paged' if you are on home page $args = array( 'post_type' => 'post', 'cat'=> 1, //Selecting post category by ID to show 'posts_per_page' => 4, //No. of posts to show 'offset' => $myOffset, //Eexcluding latest post 'paged' => $paged //For pagination ); $loop = new WP_Query( $args ); while ( $loop->have_posts() ) : $loop->the_post(); the_content(__('Continue Reading')); endwhile;
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "loop" }
Upload a website on WAMP and modify it I have a website, all precompiled (modules, plugins, template etc), well zipped in a folder. I want to upload it on WordPress, using WAMP (maybe) so that I can modify it properly. May you please describe, step by step, how can i do that?
There are two components to a web site: files and data. ## Files WP tends to use simplistic directory structure with all of the files in web root. Getting files in place is a matter of unpacking them to a new location. ## Data Data is a little more tricky. Typically it would be a dump of MySQL database, but might also be a WP export file. Overall you need to get it into database one way or another (SQL import, WP import, possibly third party tool that automates restore from its backup). Once you are done you would need to follow the procedure to change site URL for a new location. Without seeing what kind of export you actually have this is about as specific as it gets.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "installation, local installation" }
Return Taxonomy/Term Information with Posts (WP_Query/get_posts) Is it possible to return taxonomy/term information for posts along with the posts themselves when querying with get_posts? I have around 150 items I am querying so I don't want to loop and pull each individually.
WordPress will cache all terms for taxonomies attached to all post types in the query result set by default - well, so long as you haven't set either `cache_results` or `update_post_term_cache` to `false` (codex). So calling `get_the_terms` etc. within the loop will not hit the database. **However** , `wp_get_object_terms` _will_ hit the database as it by-passes WordPress' object cache.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "wp query, taxonomy, terms, get posts" }
How to add attribute in menu code I want to make a menu with hover animations. My HTML syntax looks like this: <ul class="menus"> <li class="current"><a href="#" data-hover="Home">Home</a></li> <li><a href="#" data-hover="About Us">About Us</a></li> <li><a href="#" data-hover="Blog">Blog</a></li> <li><a href="#" data-hover="Services">Services</a></li> <li><a href="#" data-hover="Products">Products</a></li> <li><a href="#" data-hover="Contact">Contact</a></li> </ul> How can I add a data attribute like `data-hover="About Us"` for each menu dynamically?
I found one small and nice solution. add_filter( 'nav_menu_link_attributes', 'cfw_add_data_atts_to_nav', 10, 4 ); function cfw_add_data_atts_to_nav( $atts, $item, $args ) { $atts['data-hover'] = $item->title; return $atts; } I tested it and it works.
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "menus, walker" }
$wpdb->delete column values IN ARRAY()? I am wondering if this is possible? $wpdb->delete( 'table_name', array('id' => array(1, 2, 3)), array('%d') ); So, in this situation, it should remove 3 rows at once, and call the database only 1 time. I have a lot of deletions that could be possible with my script and would rather it just perform the deletion once, instead of having to loop through all of the ids and do a `$wpdb->delete` on each one individually. Is this possible? Seems like it should be...
No, `wpdb::delete` does _not_ handle anything other than `WHERE field = X`. You can just use the `query` method instead: $ids = implode( ',', array_map( 'absint', $ids ) ); $wpdb->query( "DELETE FROM table_name WHERE ID IN($ids)" );
stackexchange-wordpress
{ "answer_score": 12, "question_score": 5, "tags": "php, database, mysql, wpdb" }
Hook to change Author Info Is there a hook or filter that will allow me to change the author of a post when someone views the page? Thanks!
Apparently "the_author" is an appropriate filter. Also, $author is apparently a universal variable, so this code worked out fine: add_filter("the_author", "change_author"); function change_author($author) { $author = "NEW AUTHOR!"; return $author; }
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "hooks, author" }
esc before saving or before displaying does it matter? In a lot of how to create a custom meta box tutorials, when saving data, i.e., update_post_meta the data is escaped: update_post_meta( $post_id, 'city', esc_attr( ucwords( $_POST['city'] ) ) ); Some tutorials do not esc when saving and do it on screen output. However, escaping protects the output to the screen, i.e., echo: echo esc_attr( $city ); So does it matter if you esc before you output to the screen or before it's saved? If you esc on save does the order of esc-ing, sanitizing and validating matter? Do you esc then sanitize and validate or sanitize, esc and sanitize . . . etc.?
Yes it does. Escaping depends on context and in worst case like using `esc_html` when writing directly to the DB are just a security hole. Even if there is no security issue, there is theoretical one. The user asked you to store A, and you are storing B. In a simple cases B is exactly how A should be displayed in the HTML, but life is rarely simple and while at one point you want to display A in an input for which you want to do `esc_attr` and at another in a textarea for which you will want to use `esc_html`. If you already transformed A into B in the DB, it is a PITA to reconstruct for B what was the original A to apply the correct escape function on it. Rule of thumb: In the DB you should store the raw values the user submitted (probably sanitized, but not escaped), escaping should be done only on output.
stackexchange-wordpress
{ "answer_score": 4, "question_score": 3, "tags": "metabox, post meta, escaping" }
How to insert a local image with custom size I am not very familiar with PHP yet but I am trying to build a Wordpress theme. In one of my theme files I simply want to insert an image (located at the theme directory /img/image.jpg) with a link to < Since I have already included `add_image_size( 'testtest', 333, 333, true );` in my functions.php I would like to use this function to display the image at this size. How should I write this with PHP code in my template file? In other words, how can I display an image that uses the pre-defined size and add a link to it with PHP?
**`add_image_size`** function has nothing to do with the images that are located in theme root directory. When you add **`add_image_size`** function , we are saying that : Hey WordPress! Can you please **also re-size** my uploaded images via **WordPress admin** to this particular size also hard crop the image if image size is bigger ( since third argument is set to `true` ). So whenever we upload images after adding this function WordPress **generate** this extra size image in addition to default sizes. These generated images are available in `/wp-content/uploads/` folder by default unless you have changed the default uploads folder. So to resize the image you need to upload the image via WP admin panel and look at the uploads folder. > How should I write this with PHP code in my template file? Generally this is used to get thumbnail attached to a post/page/CPT, like the_post_thumbnail( 'testtest' ); The above function generates required html for image tag.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 2, "tags": "php, images" }
is it possible to create cart functionality without woocommerce? I was wondering about how I can create custom cart functionality without installing WooCommerce plugin. Is it possible?
WooCommerce is not the only plugin that will do this for you. Perhaps you want to take a look at this list of other options. If you think of building a cart on your own, don't think of it too lightly. Especially the interface to a payment option will be difficult. You may take inspiration from this code on github that implements a simple cart with paypal payment.
stackexchange-wordpress
{ "answer_score": 3, "question_score": -3, "tags": "php, e commerce" }
Add menu page on multisite I'm trying add menu page in multisite (settings will be global for all blogs). Current code created in plugin and activated in network function wpdocs_register_my_custom_menu_page() { add_menu_page( __( 'Custom Menu Title', 'textdomain' ), 'custom menu', 'manage_options', 'myplugin/myplugin-admin.php', ''); } add_action( 'admin_menu', 'wpdocs_register_my_custom_menu_page' ); But it show only in blog menu, I think should be different action hook, maybe someone can help me ?
I believe you're looking for the `network_admin_menu` hook. Here's how you'd use it: add_action('network_admin_menu', 'function_name'); function function_name() { add_menu_page( "page_title", "menu_title", 'capability', 'menu_slug', 'function_callback' ); }
stackexchange-wordpress
{ "answer_score": 6, "question_score": 3, "tags": "multisite, admin, admin menu" }
Add Font Awesome Embed CDN Script To WordPress This is my original code that pulled Font Awesome icons, which is placed in my functions.php file: wp_enqueue_style( 'prefix-font-awesome', '//cdnjs.cloudflare.com/ajax/libs/font-awesome/4.6.1/css/font-awesome.min.css', array(), '4.6.1' ); They've recently started offering unique embed codes that appear like so: <script src=" But I'm not sure how to use this with wp_enqueue_style.
The full snippet would be this: wp_enqueue_script( 'prefix-font-awesome', ' );
stackexchange-wordpress
{ "answer_score": 2, "question_score": 3, "tags": "wp enqueue style, cdn" }
Pass arguments to function class with do_action() I'm trying to develop a "simple" script where i can create a filename with a timestamp of the last edit. For this I'm trying to code a class – but I'm having problems to pass an argument to add_action. I placed this script in functions.php to fire it on my will with do_action. class tme_form_filehash { public $args; public function __construct( $args ) { $this->args = $args add_action( 'init_tme_form_filehash', array($this, 'tme_form_filehash'), $args ); } public function tme_form_filehash( $args ) { echo $args; } } $tme_form_filehash = new tme_form_filehash( $args ); and somewhere in my theme I placed <?php do_action('init_tme_form_filehash','hello'); ?> but still there is no echo at my wished place...what I'm doing wrong here?
If you want to apply the add_action and do_action in combination with class object, you have to use a static function to access your class. Try this code with your own wording/variables: class My_Plugin { protected static $_instance = null; // Static function used to access this class public static function get_instance() { if ( self::$_instance == null ) { self::$_instance = new self(); } return self::$_instance; } public function __construct() { add_action('MY_HOOK_NAME', array($this, 'MY_HOOK_FUNCTION'), $args); } public function MY_HOOK_FUNCTION($args) { echo $args; } } Then initialize your class: My_Plugin::get_instance(); Finally you can use the do_action: do_action('MY_HOOK_NAME', 'hello my test')
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "functions, actions" }
tax_query not working for taxonomy slug i have one custom post type 'game' and one custom taxonomy 'console', which is shared by 'game' and 'post'. Now I created a new PHP 'taxonomy-console' and I want to separately display posts from 'post' on the left and posts from 'game' on the right. the code I am using is: <?php $slug = $term->slug; $query = new WP_Query(array( 'post_type' => 'post', 'order'=>'DESC', 'tax_query' => array( array( 'taxonomy' => 'console', 'field' => 'slug', 'terms' => $slug, ), ), ) ); if ($query->have_posts()) : while ($query->have_posts()) : $query->the_post(); ?> /* bla bla bla */ <?php endwhile; endif; ?> But neither this nor **'post_type' => 'game'** are displaying anything. The thing is, I am using the same exact code on another taxonomy page, the only difference is that it is registered with only one post_type and doesn't share two post types.
I can't comment so I have to provide an answer which I don't have a full answer. If I were you I would print_r($slug) and see what it gives you. The $slug variable is most likely not in a format that 'terms' can accept.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "wp query, custom taxonomy, tax query" }
Remove Visual Composer Tab from Dashboard Menu I have installed Visual Composer for a client and am now trying to remove the tab from the Dashboard menu. How can I do this? ![Remove Visual Composer tab from Dashboard menu]( function remove_menus(){ remove_menu_page( ‘js_composer.php’ ); } add_action( ‘admin_menu’, ‘remove_menus’ ); The code used above isn't working for me. It seems the path "js_composer.php" is not correct.
It is not easy to find it out, but it is pretty easy if you know how. Add this following code to your themes `functions.php`. function custom_menu_page_removing() { remove_menu_page('vc-welcome'); //vc } add_action( 'admin_init', 'custom_menu_page_removing' ); (Previously been `admin_menu`, now is `admin_init`) This is how to find out for the next time: If you want to hide a link from any plugin in the admin backend, simply use everything behind the `?page=` in this example case it's `vc-welcome` No need for an additional plugin to remove/hide the link.
stackexchange-wordpress
{ "answer_score": 7, "question_score": 5, "tags": "dashboard" }
Which Apache-modules must I enable? I'm running a VPS with `Ubuntu 14.04.4 x64` and Apache `2.4.7`, and would like to set-up a WordPress site on it. Which apache-modules _must_ I have enabled - and which _should_ I enable (eg. for cool WP-features)? Are there any modules I absolutely should _not_ enable?
Here is the list of minimum Apache modules which is required to run WordPress websites. mod_alias mod_authz_host mod_deflate mod_dir mod_expires mod_headers mod_mime mod_rewrite mod_log_config mod_autoindex mod_negotiation mod_setenvif
stackexchange-wordpress
{ "answer_score": 5, "question_score": 2, "tags": "apache, linux" }
Sharing one WordPress installation between several "sites"? I'm running a VPS with Ubuntu. I've installed the LAMP-stack, and would now like to make a couple of blogs/sites using WordPress. I'm thinking about creating new users for each blog and making a `public_html` directory for each user. This way each blog could be reached with ` Space is however at a bit of a premium, so I was wondering if it's possible to install WordPress only once (eg. under `/var/www/html/` or perhaps `/var/www/wordpress`), and let all blogs access WordPress from there? Of course they'd each also have a "private" directory in the `public_html` for each user, for individual configurations, uploads, and so on. Each blog/user would have their own MySQL database. Are there better ways of doing this - one WP installation, multiple blogs - that I'm missing? Also, is it possible to use only one shared MySQL-database for all blogs? (Not that I intend to do so, just curious...)
Am I missing a requirement, or will multisite suffice? < Multiple blogs, one install, one database...
stackexchange-wordpress
{ "answer_score": 2, "question_score": 1, "tags": "installation, options, linux" }
CartoDB embedding doesn't work I added some custom php to my site in order to be able to embed a leaflet map using an [iframe src=""] tag. This works. More recently I've wanted to embed a CartoDB map. e.g. [iframe src=" width="827" height="582"] I initially tried the above method but get a iframe box with no content, as per the image below. ![enter image description here]( After some searching I found that just pasting the `public_map` URL should **just work** as per here and here. No luck. Nothing happens in the visual editor, and the URL isn't being treated as a hyperlink either.
## 1 The [iframe] custom shortcut Turns out the content from CartoDB was being blocked by Privacy Badger a browser plugin that disables trackers and other malicious content. The solution was to allow content from `username.cartodb.com` as in the image below ![Privacy badger screenshot]( ## The Magic "Paste and it Just Works(tm)" Method This apparently only works in the `Visual Editor` and only works for blogs hosted on Wordpress.com, which was not the case for my site. Thanks to Tom Malone for pointing this out in the comments above.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "embed" }
How i can limit period of post publication? I need to limit period od post publication - admin type date, for example, 30.05.2016 in custom fields and then i need to hide custom posts with this date less, then today date How i can do this?
Have you looked into expire plugins ? < finally wordpress.org/plugins/post-expiring seems to have done the job.
stackexchange-wordpress
{ "answer_score": -1, "question_score": 1, "tags": "posts, query, date time" }
redirecting an entire WP site from one top level domain to another I think I know the best way to proceed doing this but just want to get some reassuring thumbs up before going ahead. Basically I want to move a .co.uk domain to the same name but .com The site runs on a plesk ubuntu VPS, that lets you change the names of existing domains you have configured, something I was surprised to see it lets you do but it does. So I plan to rename the domain I have setup from .co.uk to .com and then create a new 2nd domain on the VPS for the .co.uk. On this I would not need a copy of the WP site, just a blank site in effect with an htaccess that is setup as follows Redirect 301 / Would this command would redirect deep links like for like and are my other assumptions all correct ?
No, you'd want a rewrite rule that captures & redirects the _request_ : RewriteEngine On RewriteBase / RewriteRule ^(.*)$ [R=301,L]
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "redirect, htaccess" }
enqueue script on custom post type archive page How do I enqueue a script on the header if the user is on an archive page of a custom post type? The custom post type is called `limitedrun` and the page is called `archive-limitedrun.php`. I tried this and got no response: function opby_theme() { wp_register_script('responsive-img', get_template_directory_uri() .'/js/responsive-img.min.js', array('jquery')); wp_enqueue_script('responsive-img'); wp_enqueue_style( 'opby', get_stylesheet_uri() ); wp_register_style('googleFonts', ' wp_enqueue_style( 'googleFonts'); if (is_singular('limitedrun') ) { wp_register_style('ltd-run-font', ' wp_enqueue_style( 'ltd-run-font'); } } add_action( 'wp_enqueue_scripts', 'opby_theme' );
You can save your time and server load by not using `wp_register_script` and `wp_register_style` when you don't need them definitely. `wp_enqueue_style` and `wp_enqueue_script` do the same job themselves when not involving excessive functions. Here is easier and more readable code up to date with the accepted answer by @vancoder: <?php function opby_theme() { wp_enqueue_script( 'responsive-img', get_template_directory_uri() .'/js/responsive-img.min.js', array('jquery') ); wp_enqueue_style( 'opby', get_stylesheet_uri() ); wp_enqueue_style( 'googleFonts', ' ); if ( is_post_type_archive('limitedrun') ) { wp_enqueue_style( 'ltd-run-font', ' ); } } add_action( 'wp_enqueue_scripts', 'opby_theme' );
stackexchange-wordpress
{ "answer_score": 6, "question_score": 2, "tags": "customization, wp enqueue script" }
What controls responsiveness in Wordpress? I am testing a WP install along with a custom theme made by third parties. The theme per se is responsive, however in some situations, at particular resolutions, parts of the page will be blank although it looks like there would be enough space to fit objects. For instance take a look here (the 3 columns below the main slider) and using Chrome Dev Tools, you will see that switching to mobile view and shrinking the window, at 780px the browser will adjust page showing only one column on the left, leaving a large amount of blank space. I am wondering if there are some Wordpress-related settings or it is just a matter of CSS?
Wordpress has absolutely nothing to do with responsiveness, neither does themes or plugins. Responsiveness is controlled by media queries ( _CSS_ ) set in stylesheets and the particular browser the site is viewed in. It is here where screen sizes are determined and checked against available media query rules. Just one note, older browsers like IE6, 7 and 8 does not support media queries and are therefor not responsive.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "css, responsive" }
What is the difference between the .po .mo and .pot localization files? I'm translating a wordpress site and need more clarity around these terms. Can anyone please lend a hand with some definitions and differences between .po .mo and .pot files with wordpress localization?
These are not any kind of WP's own format but rather just gettext file types which WP implements. Translate Handbook has following definitions in its Glossary: > MO files: MO, or Machine Object is a binary data file that contains object data referenced by a program. It is typically used to translate program code, and may be loaded or imported into the GNU gettext program. > > PO files: PO files are the files which contain the actual translations. Each language will have its own PO file, for example, for French there would be a fr.po file, for german there would be a de.po, for American English there might be en-US.po. > > POT file: POT files are the template files for PO files. They will have all the translation strings left empty. A POT file is essentially an empty PO file without the translations, with just the original strings. The technical details of file formats can be found in gettext documentation: * The Format of PO Files * The Format of GNU MO Files
stackexchange-wordpress
{ "answer_score": 42, "question_score": 31, "tags": "localization, filesystem" }
wp_update_post deletes post meta in CPT I have a custom post type called 'directory' and it includes a few meta/custom fields. The script below is meant to just change the post status only when run. This isn't on the admin panel where you save the post. This is a stand alone script run by itself. require('../../../wp-blog-header.php'); global $wpdb; global $post; $directories = get_posts( $get_directories ); foreach ($directories as $directory){ wp_update_post(array('ID' => $directory->ID,'post_status' => 'draft')); }; The status is updated fine, but the custom meta data is deleted. I've seen other's with similar problems adding an update on the admin edit page, but this is its own file.
Not sure about the problem with `wp_update_post` but it is a simple enough SQL query: global $wpdb; $query = "UPDATE ".$wpdb->prefix."posts SET post_status='draft' WHERE ID = '".$directory->ID."'"; $wpdb->query($query);
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "plugin development, wp update post" }
Filter out comments with certain meta key/s in the admin backend Not long ago I learned how to add and filter comments on posts/pages with certain meta key/value and it works fine now. Now what I want is to do two things on the backend ( **/wp-admin** ): 1. Filter the **/wp-admin/edit-comments.php** so it will not display any comments which has the certain meta keys (e.g. meta1, meta2) in there. 2. Make a list in a custom menu page in the admin backend which will list comments like **/wp-admin/edit-comments.php** but will only show those comments that has the meta keys like above. I've been searching around for something like this but only found stuffs like filtering the backend comment list by current user, etc. and not by comment meta keys. I've also never done anything in the backend other than adding some menu/submenu with functions and options so I don't know where to start on these filters, though I have a feeling this has something to do wit WP_Query functions.
**1\. You can use`pre_get_comments` hook**: add_action('pre_get_comments', function($query) { global $pagenow; if ( is_admin() && ('your-custom-page' === $pagenow) ) { $query->query_vars['meta_query'] = [ 'relation' => 'AND', [ 'key' => 'key1', 'value' => 'meta1' ], [ 'key' => 'key2', 'value' => 'meta2' ] ]; } }); **2\. You need to learnhow to create an admin list table**. Also, take a look at: * class-wp-comment-list-table.php * edit-comments.php * comment.php
stackexchange-wordpress
{ "answer_score": 0, "question_score": 1, "tags": "filters, wp admin, comment meta" }
How to get custom post type taxonomy I have created a custom post type `portfolio_posts` using the CPT UI plugin. Using the same plugin, I have created a taxonomy `portfolio_category`. I have made multiple entries under this taxonomy. I want to list all the entries under `portfolio_category`, but all I'm getting is an empty array. Here's what I've tried: $args = array( 'taxonomy' => 'portfolio_category' ); $taxonomy = get_categories ($args); echo '<pre>'; print_r($taxonomy); exit; When I replace `portfolio_category` with `category` I am successfully getting all the entries under `category`. What am I missing here? Here is a screenshot of the entries under portfolio_category and below is an example of how they are saved in the `wp_term_taxonomy` table. ![How they are saved in wp_term_taxonomy table](
Here is how i did it $taxonomy = get_terms('portfolio_category', array( 'hide_empty' => 0 )); i am able get all the items under portfolio_category.
stackexchange-wordpress
{ "answer_score": 2, "question_score": 1, "tags": "custom taxonomy" }
Wordpress using get_term to retreive slug not working as expected Im using the below code to try and get the slug for the current category and the parent category. Ive managed to get as far as getting the currently cat slug but the parent displays in readable text and nut slug format. If anyone can point out where im going wrong and offer any advice i would be very greatful. Thanks <?php $term = get_term_by( 'slug', get_query_var( 'term' ), get_query_var( 'taxonomy' ) ); $parent = get_term($term->parent, get_query_var('taxonomy') );?> <?php echo do_shortcode("[ecs-list-events cat='{$term->slug}']"); ?> <?php echo $term->slug; echo $parent->name; ?>
I might be completely missing what you want here, but it sounds like you're saying you want the parent category's slug to echo out, rather than the parent category's human readable name. Rather than this: echo $parent->name; You just need this instead: echo $parent->slug; You can see a list of the properties here that are returned by the `get_term()` function. You can also always use PHP's `print_r()` function on the term object (so, `print_r( $parent );` in this case) to see all of the properties you have available to you.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "php, categories, woocommerce offtopic, slug, terms" }
Acessing WP functions in form submission handler I have a form which is embedded in a custom post type. The form action points to a PHP file that sits in my mu-plugins directory: <form action=" This works fine; upon 'submit', this PHP file is invoked. The problem I'm having is that `formprocess.php` doesn't seem to "see" core WP functions as in-scope. For example, calling `wp_verify_nonce()` is throwing an HTTP 500 error. I tried adding `require_once(ABSPATH .'wp-includes/pluggable.php');` and it is still not working. What else can I do to assure that core WP files are available to my form handler? Or, is there an entirely different approach I should be using?
Accessing files within WP installation directly is a bad practice. While you _can_ implement a custom core load routine, it is fragile and impossible to reliably ship in public plugins. There are different approaches to form submission in WP. On of the most appropriate ones (if slightly underknown) is sending form to `wp-admin/admin-post.php` and using hooks inside to attach processing logic.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "plugin development, forms" }
"JQMIGRATE: Migrate is Installed" How do I find the problem code? I have a site and since updating to 4.5 it has a very subtle display bug that seems jQuery related (full bleed images have a white border that snaps away into correctness when you resize window). The theme hasn't been updated since 2014. The only lead we have is this in the console: `JQMIGRATE: Migrate is installed, version 1.4.0` My understanding is that this indicates some of the jQuery in the plugins or theme is using old API's and this adds compatibility. Related question about silencing the message, NOT WHAT I NEED. **How can I figure out the code that's causing it?** I suspect that the display problem is related, and even if it isn't I figure I should start there either way. Thanks for any help!
Migrate message is merely informational. It isn't a warning or error. It is displayed unconditionally whenever respective script is loaded. In current WP version it is loaded whenever `jquery` handle is requested by anything, alongside `jquery-core`.
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "jquery, javascript" }
Create widget in dashboard displaying a custom user field? I'm trying to follow this tutorial but I can't get it to work. My best hypothesis is that because the code is 4 years old, some function in it might have been deprecated... And the code provided there needs some minor update. Anybody has any ideas? Here's the link I'm referring to: How to Make a Custom Dashboard Widget to Display Custom Notification from Admin? Thanks in advance!
I solved the issue. Here's a link where I explain how I solved it and how the final code looked like: <
stackexchange-wordpress
{ "answer_score": 0, "question_score": 1, "tags": "widgets, dashboard" }
I changed "Howdy" in the admin bar in the dashboard, but when I'm viewing the site it still says Howdy! I used the following code to replace "Howdy" in the admin bar. This is lovely. However, when I view the site while logged in, the word Howdy reappears. As long as I'm viewing the dashboard, no howdy. When I am viewing the site, howdy. //* Change the Dashboard Welcome Message add_filter('gettext', 'change_howdy', 10, 3); function change_howdy($translated, $text, $domain) { if (!is_admin() || 'default' != $domain) return $translated; if (false !== strpos($translated, 'Howdy')) return str_replace('Howdy', 'Explore the Possibilities', $translated); return $translated; } Anyone know how I make that change apply to both views of the admin bar?
I see a couple of problems here. This line if (!is_admin() || 'default' != $domain) return $translated; returns the Howdy right back unchanged if is_admin is false - which it is if you're not in the dashboard. Also, you're running your filter callback on gettext. This means it will be run every time some internationalized content is used, which is very inefficient. You'd be better off using a more appropriate filter, like below. function change_howdy( $wp_admin_bar ) { $my_account = $wp_admin_bar->get_node( 'my-account' ); $new_title = str_replace( 'Howdy', 'Explore the Possibilities', $my_account->title ); $wp_admin_bar->add_node( array( 'id' => 'my-account', 'title' => $new_title, ) ); } add_filter( 'admin_bar_menu', 'change_howdy', 25 );
stackexchange-wordpress
{ "answer_score": 5, "question_score": 2, "tags": "functions, dashboard, admin bar" }
Automatically include all php files in a child theme directory I'm currently using a custom child theme across multiple sites, and would like to modularise particular custom features (e.g. ecommerce) by separating them into individual php files, and including the relevant ones as needed (without making them into plugins), since otherwise it's difficult to keep track of the customisations in each file across multiple variations of the child theme. To do this, I'd like to be able to copy particular php files into a folder in the child theme, and for these to be included automatically. How would I achieve this?I've tried several solutions, but they don't seem to work in this context. Here's an example of a code I used: function include_all_php($folder){ foreach (glob("{$folder}/*.php") as $filename) { include $filename; } } include_all_php("includes"); // "includes" is the name of the folder in the child theme
I suspect `glob` needs the _current working directory_ to work, so you could try passing the full path of the file to the existing function you have... include_all_php(dirname(__FILE__).'/includes'); Or set the current working directory first: setcwd(dirname(__FILE__).'/'); include_all_php('includes'); Alternatively you could also use `scandir`: $filepath = dirname(__FILE__).'/includes/'; $files = scandir($filepath); foreach ($files as $file) { // match the file extension to .php if (substr($file,-4,4) == '.php') {include($filepath.$file);} }
stackexchange-wordpress
{ "answer_score": 0, "question_score": 1, "tags": "functions, child theme, include" }
How to get a post's content? I'd like to known what is the best solution for getting a sepecific post's content. By slug, tag, id or category ? Or template assigned to this post ? I don't like the way to find this post by its id because the id is not the same on others PC. Could you give me some advices ? Thanks !
"best" greatly depends on context. guid is probably (with some debate about it) the best way to uniquely identify a post, but not all import/export plugins leave it alone without changes. ID is a good identifier if you do not care about import and export. Slug is problematic because they might be changed by the user. The best thing to do if you need to know which post you should treat in a special way is to have an admin configuration for it that saves its ID. Then when you need to work with the same code in different environments you can just change the configuration without changing the code.
stackexchange-wordpress
{ "answer_score": 3, "question_score": 0, "tags": "posts, tags, slug, content, id" }
add class to term_description trying to filter the output of term_description to include a class < function add_class_to_term_description() { ?> <?php echo '<div class="cell">' . term_description() . '</div>'; ?> <?php } add_filter( 'term_description', 'add_class_to_term_description' ); ?> im getting and empty cell class returned hundreds of times which is exhausting the memory. what am i doing wrong?
this does the trick <?php function add_class_to_term_description($term_description) { echo '<div class="cell">' . $term_description. '</div>'; } add_filter( 'term_description', 'add_class_to_term_description' ); ?>
stackexchange-wordpress
{ "answer_score": 1, "question_score": 3, "tags": "filters" }
How to show phpinfo() only in a new tab? My problem is that I want to add a link to my plugin which should direct the admin user to a new blank page which shows phpinfo()? Can anyone direct me how to do this? I know WordFence has a feature like that under their Diagnosis page, I want my plugin to basically do the same thing.
If you are displaying the info in the front-end, hook into `wp` or `init`, otherwise `init` or `admin_init` will work on admin: add_action('wp', function() { if( current_user_can("manage_options") && ! is_feed() && isset( $_GET["my_plugin_show_phpinfo"] ) ) { ?> <!-- Output things --> <?php phpinfo(); ?> <?php exit; } }); Now if you go to ` it will display your custom content only. Hope that helps. Edit: Added conditional to limit the tab for admins only. Thanks TomC!
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "php, plugin development" }
get_post_field - Title without paragraph Normally I wouldn't insert a single post with a technique like this, but sadly this project requires it. I try to call the `post_title` with: echo apply_filters( 'the_content', get_post_field( 'post_title', $post_id ) ); The problem is, that this code will display the title inside a paragraph like: <p>Title</p> How can I block it out, or even replace it with an `h2`?
As per the discussion `the_content` is not a proper hook for filtering post titles while it filters the post content. `wpautop()` function is called with `the_content` so it adds the necessary paragraphs. To filter post titles use `the_title` instead, it won't add any markup tags by default: echo apply_filters('the_title', get_post_field('post_title', $post_id));
stackexchange-wordpress
{ "answer_score": 1, "question_score": 2, "tags": "posts, title" }
SEO - Media File Name Updating I've been asked to rename my images to better suit what they represent via keywords, for the purpose of SEO. However, I've noticed that modifying the media images name within WordPress doesn't in turn modify the actual stored image names generated by WordPress, which are used within the HTML. For example, I have a media jpg image titled "football". I need to rename this to "football-large-spotted". When I do this via the "football" media page, it doesn't change any jpg references on my page "about-footballs", which could be "football-320x320.jpg" when it should now be "football-large-spotted-320x320.jpg".
You would most likely need to use an plugin like `Media File Renamer` for that or change the image name before the upload.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "images, seo" }
Trying to establish connection to External Database I'm trying to get a connection to a separate external database from the database the wordpress site depends on. I have a PHP file inside the same location of my theme, it is basically a blank PHP it has the needed PHP tags. I'm trying to make a connection using what I found online this is what the **whole** file looks like: <?php $mydb = new wpdb('username','password','db_name','xxx.xxx.xxx'); ?> When I try to make a connection with the correct credentials I get an error in my WPEngine Live Site Log that says: `PHP Fatal error: Class 'wpdb' not found in /nas/content/live/...` How do I go about fixing this issue, so that I can connect to my external database?
My issue was resolved, not sure if the connection to the database will work, but the error with wpdb connection was fixed. It was quite easy fix once I found out what the file dependence was. This is what you need to do: In the file you are trying to use wpdb you need to add code before you can use the class: <?php require_once('../../../wp-load.php'); ?> Note* You may need to change how far back in the directory you go depending on your install or depending on the location of your php template/file. It should run wpdb without any errors.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "php, functions, database, wpdb" }
Change Page's <title> Tag Using functions.php File In my child theme's functions.php file, I'm trying to change a page's title tag: function custom_title() { return "Page Title"; } add_filter( 'wp_head', 'custom_title', 9999 ); The code above is not changing the page's default title. What am I doing wrong?
Check this out function custom_title($title_parts) { $title_parts['title'] = "Page Title"; return $title_parts; } add_filter( 'document_title_parts', 'custom_title' ); In `custom_title`, `$title_parts` contains 'title', 'page' (the pagination), 'tagline' (the slogan you specified) and 'site'. Set "title" the way you like.
stackexchange-wordpress
{ "answer_score": 4, "question_score": 5, "tags": "plugins, filters, api, wp head" }
What function to hook for changes made in status and visibility of a post I have a function to run every time a post is published or updated in anyway. Right now I am doing function myFunction(){ //Do Something } add_filter('publish_post','myFunction'); add_filter('wp_update_post','myFunction'); Now, when I do this the function is getting called on when I publish a post or make any changes to the `Status: Draft/Pending Review` (as shown in the attached image), the function is not called. What function to hook to run my function on `Status` change? ![enter image description here]( **Got it to work. Answer below**
What I was looking for was transition_post_status. The documentation can be found here. What I did was to add one more filter `add_filter('transition_post_status','myFunction');`
stackexchange-wordpress
{ "answer_score": 3, "question_score": 2, "tags": "plugin development, functions, theme development, hooks" }
Filtering comment permalinks when a condition is met I can't figure out how to filter the comment permalink on certain WP page that I use like this: if(condition is met) { (filter the comment url) } ...so that all the comment permalinks inside the page can be changed from this: to this: In short, I'm trying to change the url structure pointing out to the page permalink, excluding the **site_url** (front page url) and the **comment slug** (e.g. #comment-n) So far, I've tried the example in the comment_link filter and nothing happens here: function my_comment_link_filter( $link ) { $link = str_replace( get_permalink() , $new_permalink_structure , $link ); return $link; } add_filter( 'comment_link', 'my_comment_link_filter', 10, 3 ); I'm doing it wrong, it seems, and would certainly appreciate any help.
I found an exact solution I'm looking for. function my_comment_link_filter( $link ) { $link = str_replace( get_permalink() , $custom_permalink , $link ); return $link; }; add_filter( 'get_comment_link', 'my_comment_link_filter' ); It does exactly what I am looking for: It replaces the Page Permalink with the dynamic permalinks when I call the filter.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 3, "tags": "permalinks, filters, comments" }
How to Add 'Post Categories' to the Dashboard Sidebar I'm currently working with a company to make a few basic tweeks to their WordPress site and I noticed that they have this on their sidebar: ![enter image description here]( I am looking particularly at the "Clients", "Offers", "Portfolio" and "Slider Offer" sections, I have never seen these before and believe that they have not been added with a plugin. It appears that they are post categories, as they have the same pin icon as the "Posts" section. Can anyone explain what these are, how they work and how to add them? Thanks
WordPress Core post types are `post` and `page` that are visible in the admin menu. Other than these can be either a registered custom post type or a menu page. A menu page can be added with the `add_menu_page()` function, and a similar thing can be done using `register_post_type()`, where a registered post type gets its own menu item where the following arguments are `true`: <?php $args = array( 'show_ui' => true, 'show_in_menu' => true ); register_post_type( 'mycpt', $args ); Note that, `register_post_type()` is a plugin-territory function. But some themes include them into their `functions.php`. And in that case, it's also possible, a parent theme didn't include 'em, but a child theme did so into its `functions.php`. :)
stackexchange-wordpress
{ "answer_score": 1, "question_score": 2, "tags": "posts, categories" }
'username_exists' still returns an ID even after deleting record from the database? Is there some kind of MySQL query cache turned on by default or something? I am trying to work on a user import script and I am seeing some strange results from the `username_exists`function after I delete records from the `wp_users` table. After I delete the records when I call `username_exists` Wordpress is still returning the ID for the deleted user instead of `false`. Odd. What am I missing?
By default, WordPress uses `$wp_object_cache` which is an instance of `WP_Object_Cache` to save on trips to the database. Trace back `username_exists()` function, you will notice that `get_user_by()` uses `WP_User::get_data_by()` which return user data from `$wp_object_cache` immediately without checking if that user exists in database. Note that `$wp_object_cache` is stored in memory. It means that if you deleted an user record directly in your database without cleaning up user cache, user data is still available. That's the problem. So what you're missing? 1. Missing to delete user the right way. 2. Missing to clean user cache.
stackexchange-wordpress
{ "answer_score": 2, "question_score": 4, "tags": "users, mysql" }
How to change URL Custom Page? My Page Custom URL: **< How can I change this url to **< where `watch` is a custom page? My `functions.php` code: function create_new_url_querystring() { add_rewrite_rule( '^watch/([^/]*)$', 'index.php?page_id=3&name=$matches[1]', 'top' ); } add_action('init', 'create_new_url_querystring');
You're using the reserved public query variable `name` as your custom one. It can e.g. affect the _canonical redirect_ by setting `page_id` and `name` for a different page. Change it to something else to avoid possible name collision, like `kenan_video_slug`: add_rewrite_rule( '^watch/([^/]*)$', 'index.php?pagename=watch&kenan_video_slug=$matches[1]', 'top' ); Note that your rewrite will override the content pagination for the `watch` page. Remember to flush the rewrite rules.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 2, "tags": "customization, pages, urls, rewrite rules" }
How to get posts by multiple post slugs? i am trying to get posts by multiple posts slugs, i can do this by passing post ids but I do not want to pass post ids i am looking for posts slug Here is my code $option = array( 'posts_per_page' => -1, 'post_type' => 'post', 'name' => 'berlin, frankfurt, munich, augsburg' ); $new_query = new WP_Query($option); if ($new_query->have_posts()) { while ($new_query->have_posts()) { $new_query->the_post(); /* my html stuff */ } } but it does not display anything but when i pass only "berlin" then queyr gives me correct results. it mean i only need to use post ids to get selected multiple posts ?
Try to put your post slugs in an array for the `post_name__in` parameter: 'post_name__in' => [ 'berlin', 'frankfurt', 'munich', 'augsburg' ],
stackexchange-wordpress
{ "answer_score": 6, "question_score": 1, "tags": "posts, wp query, slug" }
How to determine if custom post type showing on archive templates Is there any way to determine if a particular custom post type will be displayed on default archive pages or search results? e.g. Given a post type named (badly) **books** , is there a way to tell **via code** any of the following: * If books show up on date archives * If books show up in search results * If books show up in author archives I know how to make custom post types show up in these, but I've been doing a bit of digging and can see no clean way to determine if a particular custom post type will show up in any of the above or not. The main reason I'm looking for this is that I'm creating custom breadcrumb bars for a theme... and it would be nice to be able to show an authors breadcrumb bar if the custom post being viewed supports author functionality **and** shows up in the author archive.
You can get the post type object and check its properties. For example: $post_type = get_post_type_object( 'books' ); if( $post_type->exclude_from_search ) { // The post type is not included in search results } if( $post_type->has_archive ) { // The post type has archive } As far I know, custom post types are not included in dates archives nor author archives if you don't code for it (using `pre_get_posts` for example). I mean, those options are not available while registering a post type. So, there is no way to check it from post type object.
stackexchange-wordpress
{ "answer_score": 3, "question_score": 1, "tags": "custom post types, breadcrumb" }
How to change Wordpress default strings? I want to change some (20-30) of the defaults strings on Wordpress back-end (not to translate). I know there is gettext filter but I think could lead to performance issues if we have a lot of strings. Another method I tried was to create and use an admin-en_US.po file. Which of the above methods are faster? Is there any better way? What do you suggest without affect performance?
Additionally to kaiser's answer, you can load customized .mo files that overrides the original file using `load_textdomain_mofile` filter. For example: add_filter( 'load_textdomain_mofile', 'cyb_filter_load_textdomain_mofile', 10, 2 ); function cyb_filter_load_textdomain_mofile( $mofile, $domain ) { if ( $domain == 'some-textdomain-to-override' ) { $mofile = WP_LANG_DIR . '/overrides/' . basename( $mofile ); } return $mofile; } It may be faster but you will be required to check for changes on every update in order to keep your .mo file syncrhonized with the original.
stackexchange-wordpress
{ "answer_score": 4, "question_score": 4, "tags": "admin" }
hide something in single page if current author has only one post I'm trying to hide a div in a single page if the current author of the post has only one post. Any ideas on how to achieve this? <?php hide or don't display if current author has only 1 post ?> <div>blah blah blah</div> <?php end ?>
`count_user_posts` will give you the number of posts for an author. `get_the_author_meta` gives you the user's ID. Note that this needs to be in The Loop to get the correct user. if( 1 < count_user_posts( get_the_author_meta( 'ID' ) , 'post' ) ) { echo '<div>blah blah blah</div>'; }
stackexchange-wordpress
{ "answer_score": 3, "question_score": 1, "tags": "author" }
OEmbed from Pinterest I'm looking for a way to show a certain pinterest pinboard in a post. I've found in the WordPress.com Documentation that you can simply post your pinboards URL there. This is not possible on a selfhosted Wordpress installation so I guess that is something specific to wordpress.com. What would be the easiest way to add a URL Handler that translates the pinterest URL into the needed embed code and include the pinterest js file?
I found that < actually has the needed functionality but doesn't mention it in the description. After installing and activating you can add a pinboard to a post by using the following shortcodes [pin_board url=" [pin_board url=" size="header"] [pin_board url=" size="custom" image_width="100" board_width="900" board_height="450"] more options can be found on the plugins "settings" page after installing.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 3, "tags": "plugins, plugin development, embed" }
Check if partial file is called from within header.php or footer.php I am including a partial file both in `header.php` and in `footer.php` with `get_template_part('content-form');` Is there an `if` clause I can use to check from where the file is being called? If it is called from within `footer.php`, then I would like to add a class name. <div class="default-class <?php if (called_from_footer) echo 'footer-class'; ?>"> </div> I could do this and style accordingly if there isn't a better solution, I am just curious: <div class=footer-container"> <?php get_template_part('content-form') ;?> </div>
This is not a _true_ solution to your problem (checking which template loaded another), but it will work to test if the footer has been loaded or not, and thus if it's loading your partial: if ( did_action( 'get_footer' ) ) echo 'footer-class';
stackexchange-wordpress
{ "answer_score": 5, "question_score": 6, "tags": "get template part" }
A snippet after every image folks. I need to put a piece of code after every post image (post attached image). it's something like this: <img class="alignnone size-full wp-image-3079" src="imgurl.jpg" alt="02" width="2592" height="1936"> <div>some piece of code here</div> It will be a share button to share the image instead the post, so every image will need a custom code to share the image url. There's a way to do this?
Try get_image_tag filter: add_filter('get_image_tag', function($html, $id, $alt, $title, $align, $size) { return $html . '<div>some piece of code here</div>'; }, 10, 6); **References** : * get_image_tag() * get_image_send_to_editor() * wp_ajax_send_attachment_to_editor()
stackexchange-wordpress
{ "answer_score": 3, "question_score": 2, "tags": "functions, loop" }
Customizing user data For a school, I'd like to add custom fields to users, such as department, curriculum, date & place of birth, education, phone number, social links.... How can I accomplish this? I see there are some plugins to create user metas however I'm not sure how reliable/supported they are....
ACF is a very good option, it has specific options to create user fields. There are tons of tutorials and practical examples out there, just google it and you will find them. It is one of the most popular WP plugins, so don't be afraid of compatibility problems, it's well maintained. You can check its documentation for practical examples about getting it work. Anyway, if you want to accomplish it coding by yourself, you should read about add_user_meta function. Cheers!
stackexchange-wordpress
{ "answer_score": 0, "question_score": 1, "tags": "custom field, users" }
How to mark articles as read? I have a normal Link: <a href="/article-1"><span class="visited-circle"></span>article 1</a> and when someone have visited this article so i changed the color in CSS: a:visited .visited-circle { background-color: green; } But I think that is not so perfect. I want that the visitor can mark this article as read. Has someone an idea how I can realize this?
For a truly full solution you need to have all the users to have an account (or create one when marking as read) and you associate in the DB the user with the posts that he read and then style each link appropriately. To implement this you can look for inspiration in plugins that add a review or other like/ranking functionality. The problem with this approach is that users need to have some other incentive to login otherwise they will probably not use the functionality. The less robust option (but easier to implement) is to store the list of the posts read in long term cookie, and style the links based on the values in the cookie. The problem with this approach is that the cookies are local to a specific device and a user might end up with fragmented "reading list" between all the devices that he uses
stackexchange-wordpress
{ "answer_score": 2, "question_score": 6, "tags": "posts, cookies" }
How to use the sunrise.php script for Multisite network domain mapping? Currently using the WP-mu-domain-mapping plugin on a multi-network installation. The domain mapping works fine with the provided sunrise.php file, however it breaks (sites no longer map correctly) when I move the plugin to our mu-plugins directory. I've tried the following, but it doesn't work. <?php $sunrises = array( "dm_sunrise" => dirname( __FILE__ ) . "/mu-plugins/domain-mapping/inc/sunrise.php" ); foreach( $sunrises as $sunrise ){ if( is_readable( $sunrise ) ){ include $sunrise; } }
As per the instructions for setting up WordPress MU Domain Mapping, `sunrise.php` needs to be placed directly in your `/wp-content` directory. It's not a plugin in the traditional sense, so can't be placed in `mu-plugins` (or even `plugins` for that matter). Setting up this plugin can take a bit of manual work so take care to follow the instructions carefully, including the modifications you need to make to `wp-config.php`. By the way, the current status of this plugin is somewhat unclear as - for new sites - it appears its functionality is now baked in to Wordpress core. It is (apparently) only now required for pre-existing Multisites which were converted some time ago. You can see various posts from the maintainer of the plugin in this support forum which confirm this.
stackexchange-wordpress
{ "answer_score": 5, "question_score": 3, "tags": "multisite, domain mapping" }
Set limit to media upload? I am searching online and all I can see is how to _increase_ file size for media upload, which I know how to do with `php.ini`, but what I need to do is limit the file size for media upload only. The client and his associates have trouble with understanding: Please do not upload images that are bigger than 1MB because your site will load forever. They keep uploading images that are over 8 MB in size, and the whole site takes over 30 sec to load. It's horrendous. So I was thinking - if it's possible to limit the image upload to 1 MB or so without affecting the general `upload_max_filesize` which will influence the ability to upload themes and plugins (and I don't want that to happen). Any idea if this can be done?
Yes, you can use the `wp_handle_upload_prefilter` that allows you to stop the uploading process if a specific condition is not accomplished. In your case, you could try this code snippet: function limit_upload_size( $file ) { // Set the desired file size limit $file_size_limit = 1024; // 1MB in KB // exclude admins if ( ! current_user_can( 'manage_options' ) ) { $current_size = $file['size']; $current_size = $current_size / 1024; //get size in KB if ( $current_size > $file_size_limit ) { $file['error'] = sprintf( __( 'ERROR: File size limit is %d KB.' ), $file_size_limit ); } } return $file; } add_filter ( 'wp_handle_upload_prefilter', 'limit_upload_size', 10, 1 ); Hope it helps!
stackexchange-wordpress
{ "answer_score": 10, "question_score": 8, "tags": "uploads, media" }
Rename UPLOADS folder with custom WP_CONTENT_DIR For version control purpose, our client has a WordPress app with directory structure like this: . |_____app | |_____themes | |_____plugins | |_____uploads |_____index.php |_____WordPress |_____wp-config.php In `wp-config.php`: define('WP_CONTENT_DIR', __DIR__ . '/app'); define('WP_CONTENT_URL', WP_HOME . '/app'); Now, she want to rename all default WordPress folders in app directory. With `plugins` and `themes` we can do it easily by using `WP_PLUGIN_DIR` and register_theme_directory(). But, somehow, it's not easy to rename `uploads` folder. I have tried many modifications with `UPLOADS` constant, but it can't help because custom uploads folder is always created inside `WordPress` directory. Are there any ways to workaround this problem?
After digging around, I ended up with using `upload_dir` filter. Here is what I tried in `functions.php` to change `uploads` to `media`. Hope it can help someone too :) add_filter('upload_dir', function($uploads) { $custom = []; foreach ($uploads as $key => $value) { if ( false !== strpos($value, '/app/uploads') ) { $custom[$key] = str_replace('/app/uploads', '/app/media', $value); } else { $custom[$key] = $value; } } return $custom; }); Many thanks to @gmazzap for the guidelines and the suggestion about `upload_dir` filter!
stackexchange-wordpress
{ "answer_score": 5, "question_score": 7, "tags": "customization, uploads, directory" }
page was loaded over HTTPS, but requested an insecure image when i install and apply SSL certificate on Bluehost webhosting, indeed my site entering secure channel however discovery page request image with http address but not https address even i upload photo to media library through secure channel. that is bug of wordpress?
Make sure that your wordpress url in the settings at your admin dashboard is starting with ` It is not enough to simply open the website with the https link. Wordpress has to know that your website is ssl secured.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 3, "tags": "wp query" }
show the most recent date of all posts to display on front end Is there any way to show the date that the last post (most recent) from my custom post type was created? I want to have my site show the last time a list of products was updated and i figured that it could be based on when the last post was created, or modified. is this possible?
Based on what you're asking and what I am understanding there is `the_modified_date()` or if you just want the value `get_the_modified_date()`. If you ever want the creation date you could use `post_date` and `post_date_gmt`. Several questions on this: * How to get post creation date? * What is considered the post's creation date for wp_insert_post? If you are asking for a complete solution I would encourage you to search under custom post type and `wp_query`. We have several questions that are on the topic. If can make an edit with code I do not mind trying to help you further.
stackexchange-wordpress
{ "answer_score": 3, "question_score": -2, "tags": "custom post types, posts, wp query" }
What should be disabled to run on an internal network with no access to the Internet? I am setting up a site on an airgapped (no connection to the Internet) internal network. It is quite slow in loading pages. I have already added `define('WP_HTTP_BLOCK_EXTERNAL', true);` and `define('AUTOMATIC_UPDATER_DISABLED', true)'` in my wp-config.php file. WordPress still appears to be trying to reach gravatar.com and fonts.googleapis.com. Is there something else that I need to disable in order to run WordPress without Internet access?
After more fruitless searching, I stumbled across this article from WP Tavern which mentioned a plugin then called "WP Local Dev Environment," now called Airplane Mode. The plugin blocks a long list of things that WordPress does which require checking something from the Internet. While it is intended to be toggled on or off depending on whether you have a connection, I can use it in perpetual "on" mode on my internal network sites. After enabling, pages that were taking 15-30 seconds to load now load almost instantaneously. BRILLIANT!
stackexchange-wordpress
{ "answer_score": 2, "question_score": 2, "tags": "performance, wp config, configuration" }
Filter blog archive by category in URL I've created a fairly basic form that allows users to filter post type archives by their taxonomies. On custom post types this is super simple to do by simply setting `?taxonomy_name=term_slug` in the URL. WP also supports an array of terms with `?taxonomy_name[]=term_slug1&taxonomy_name[]=term_slug2`. What's odd however is that on the archive for _non_ custom post types (ie the "post" post type) this stops working. Setting `?category=term_slug` does absolutely nothing. How can I, preferably without using `pre_get_posts` or anything else more advanced, filter the regular posts by their taxonomies (`category` and `post_tag`)?
Even if default posts are stored in same table but they have different behavior and different characteristics. CPT has post type archive but default post type archived is called as blog and the taxonomy filter is called as tag/category archive. You can access the category/tag archive using For categories: /?cat={category_id} //e.g. ?/cat=5 For tags: /?tag={tag_slug} //e.g. ?/tag=my_tag_slug If you are willing to use `pre_get_posts` you can customize this in the way you want ( _That is what I love in WordPress <3_) else stick with default way. Another note: I recommend to leave the default posts for blog never use them for building something custom with those types instead use CPT as many as you want to expend your site from blog to CMS :)
stackexchange-wordpress
{ "answer_score": 0, "question_score": 3, "tags": "taxonomy, archives" }
Plugin update warning Is it possible to show a warning message for a certain plugin update? For example from version 0.3 or lower to 0.4 or higher? EDIT: I need something like upgrade notice (wich doesn't work correctly at the moment) i found a interesting article here.
Not possible unless you plan in advance in your plugin for such a possibility. And even if it was somehow possible you are still not likely to have any user read the message and actually understand it. A more realistic approach is to do a two steps upgrade, in the first vesion of your plugin to maintain appropriate backward compatibility and only later you remove it from your code, giving both you the option to give proper notification, and the user time to adjust whatever he needs.
stackexchange-wordpress
{ "answer_score": 1, "question_score": -2, "tags": "plugins, updates" }
Does the customizer support multiple templates? I only started using the WordPress theme customizer lately and was wondering if it can be used for more than editing the front page. Is it possible to add a template (or page/post) selector to the left-hand sidebar? Otherwise, can I disable the auto-refresh, so I could still browse the site to see my changes? Needless to say, that I already tried the WordPress Codex.
Yes, this is possible. Just add a callback to those mods that you want to appear on specific pages, like this: $wp_customize->add_control( 'my_page_control', array( ... 'active_callback' => 'is_page', ... )); You will see this control in the customizer only if you are viewing a page. Don't forget to adapt the css produced by this mod in such a way that it only applies to pages as well. More about contextual controls.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 2, "tags": "theme customizer" }
Removing pre existing menu item I want to remove the following items from the customizer menu: ![]( However, I already tried a few codes from other Stack questions but with no luck! Is it even possible to remove those?
Here you go: $wp_customize->remove_section('colors'); $wp_customize->remove_section('nav_menus'); $wp_customize->remove_section('static_front_page'); EDIT AFTER DISCUSSION After testing I found that this doesn't work for `nav_menus`. You have to set a higher priority on the hook, like this: `add_action( 'customize_register', 'remove_nav_menu_section', 20 );` This gives a php warning from WP but otherwise does the job.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 2, "tags": "theme customizer" }
Add rewrite rule to permalink structure I have a Custom Structure setup for posts in Settings > Permalinks as: `/%category%/%post_id%-%postname%` This works great for most of my posts, but there is one category that I want to remove the post_id from so it looks like this: `/%category%/%postname%` So if the category is MOUSE and the post-id is 123 and postname(slug) is my-great-mouse-post, then the permalink correctly looks like this: `mydomain.com/mouse/123-my-great-mouse-post` But if the category is DOG then I do not want the post-id, so it should look like this: `mydomain.com/dog/my-great-dog-post` I understand how to use actions and filters in my functions.php and in a plugin and I think I want to use add_rewrite_rule but am honestly confused as how to write the rule as regex is complicated and I do not understand it.
### 1\. Add a new rewrite rule: add_action('init', function() { add_rewrite_rule('^dog/([^/]+)/?$', 'index.php?cat=dog&name=$matches[1]', 'top'); }, 10, 0); ### 2\. Filter the post link: add_filter('post_link', function($post_link, $post, $leave_name = false, $sample = false) { if ( is_object_in_term($post->ID, 'category', 'DOG') ) { $post_link = str_replace($post->ID . '-', '', $post_link); } return $post_link; }, 10, 4); Try it in your `functions.php`. Hope it works for you!
stackexchange-wordpress
{ "answer_score": 4, "question_score": 5, "tags": "plugins, plugin development, url rewriting, rewrite rules" }
Does flush_rewrite_rules() remove all rules added by other plugins as well as mine? I am developing a plugin, and am using add_rewrite_rule followed by flush_rewrite_rules during plugin activation. On plugin deactivation I am using just flush_rewrite_rules to remove the rule that I had added. Now let's assume another plugin had also added a rewrite rule. Would calling flush_rewrite_rules not remove this other plugins rewrite rule as well, even though the other plugin is still active? EDIT: Some notes to remember: * `flush_rules()` does the same as `flush_rewrite_rules()`. See Milo's comments below his accepted answer. * There is an issue in bug tracker < that shows the best practice, but also shows the problem of having to use INIT to conitinually add your rule.
This is why you need to add rewrite rules on the `init` action on every request, as well as on plugin activation. When your plugin deactivation hook is run, other plugin `init` hooks have already run, so their rules exist in the global variable that stores them for the life of each request. Flushing rewrite rules empties the option that stores the rules long-term, and then repopulates it with whatever is in that global variable.
stackexchange-wordpress
{ "answer_score": 2, "question_score": 1, "tags": "plugins, plugin development, url rewriting, rewrite rules" }
Place max_execution_time in plugin I have a client who has a php script execution timeout problem on a locally installed wordpress. I dont have an access to machine to do the test, so here is my question. There is a custom plugin on that site that has all the php custom code in it. Can I just place: ini_set('max_execution_time',0); on top of plugin file and be sure it will work for entire front and back end?
yes you can, but this will be applied to all the requests to the site which might actually bring it down if you have some infinite loop somewhere. A better way to do it is to find an action that is being used specifically in the upload process and call it only for that action.
stackexchange-wordpress
{ "answer_score": 1, "question_score": -1, "tags": "plugins, php" }
Where to put custom page templates in theme? I am building a theme (parent theme) and I was advised to put custom page templates in theme root folder. I am copying theme twenty fourteen and found this theme using a separate directory called **`page-templates`** for keeping custom page templates but it does not work with my theme? Can i know why twenty fourteen doing this and how ? Do I need to do the same because this is WordPress theme and I think they do everything thing in a proper way.
> Where to put custom page templates in theme? Custom page templates in `page-templates` folder are automatically recognized by WordPress.This folder is recommended for global or multi-purpose page-templates. You can check more organizing theme files on theme development handbook. > but it does not work with my theme? Are you sure you have template files with the correct header ?
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "theme development, page template, template hierarchy" }
How to extend Customizer payload sent when 'Save & Publish' is triggered By default, customized sent the below payload when the `Save & Publish` button is clicked. wp_customize:on theme:twentysixteen customized:{"header_color[primary]":"345"} nonce:d2a36386d3 action:customize_save Is there a way i can extend the payload to include custom data to be posted? Refereence: <
You can monkeypatch the `wp.customize.previewer.query` method: add_action( 'customize_controls_enqueue_scripts', function () { wp_add_inline_script( 'customize-controls', '(function ( api ) { api.bind( "ready", function () { var _query = api.previewer.query; api.previewer.query = function () { var query = _query.call( this ); query.foo = "bar"; return query; }; }); })( wp.customize );' ); }); This will ensure the script runs immediately after `customize-controls.js` in the markup - note that `wp_add_inline_script` will wrap your JS within `<script />` tags, no need to do it yourself.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 2, "tags": "theme customizer" }
Disable plugin per user role I must disable a discount plugin for certain user role, I have wrote this and put in the child-theme `functions.php` global $woocommerce; get_currentuserinfo(); global $current_user; if ($current_user->ID) { $user_roles = $current_user->roles; $user_role = array_shift($user_roles); if ($user_role == 'B2B') { deactivate_plugins('/httpdocs/wp-content/plugins/woocommerce-payment-discounts/woocommerce-payment-discounts.php', false); } } But this doesn't work, why? Is it correct? and the deactivation is only for the user session?
You should use the `wc_payment_discounts_apply_discount filter`. Try something like the following: function remove_privato_discounts() { global $woocommerce; get_currentuserinfo(); global $current_user; if ($current_user->ID) { $user_roles = $current_user->roles; $user_role = array_shift($user_roles); if ( $user_role !== 'b2b') { $discount = 0; $woocommerce->cart->discount_total = $discount; return true; // Do not apply discount to privato } } return false; } add_filter( 'wc_payment_discounts_apply_discount', 'remove_privato_discounts');
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "plugins, user roles" }
Using Add_image_size when adding image in post I have put `add_image_size('image_horizontal', 750, 300, false);` in functions.php file but it doesn't appear as selection when publishing new post and adding image in the post, all I see is thumbnail, large and full size. I don't want to change default image sizes, just add this one with others. I did regenerate thumbnails using a plugin after. Does putting a custom image size in selection needs different code?
You also need to add it to image size chooser.You can do so using the filter image_size_names_choose. add_filter( 'image_size_names_choose', 'wpse_228675_custom_size' ); function wpse_228675_custom_size( $sizes ) { return array_merge( $sizes, array( 'image_horizontal' => __('Custom image size'), ) ); }
stackexchange-wordpress
{ "answer_score": 2, "question_score": 1, "tags": "images" }
Can't use pagination with custom taxonomy I have a problem with custom taxonomies & post types URLs. My post type slug is `videos`, it has an archive and it works fine: < The pagination on the bottom of the page works like a charm. My taxonomy slug is `video_type`, but I rewrite the slug to be `videos`, than all the taxonomy archives look like this: < and work fine. But the pagination is completely broken (shows 404 on the second page). Why is that? To register taxonomy I use this code: $args = array( 'labels' => array(), //* Not important. 'public' => true, 'show_admin_column' => true, 'hierarchical' => true, 'description' => '', //* Not important. 'rewrite' => array( 'slug' => 'videos', ), ); register_taxonomy( 'video_type', 'videos', $args ); All the permalink rules are flushed. What should I do?
You're using the same slug for both your `videos` custom post type and `video_type` taxonomy. Then, when querying post, WordPress don't know what to select from database. Change your `videos` post type to `video` or something differs from `videos` taxonomy slug will solve your problem.
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "custom post types, custom taxonomy, permalinks, pagination" }
Showing featured image of page's child's children page so i have a page that has children pages acting as categories, that each have children pages themselves (parent > children > children of children). How would I go about showing the featured images of just the children's children on the parent page? This is important because on the second level i.e. parent > children I am using featured images as banners, but do not want them to reflect on the parent page. My existing script shows all children featured images: <?php $projects = get_pages( array('sort_column' => 'menu_order', 'sort_order' => 'ASC', 'child_of' => $post->ID) ); if ($projects) { foreach( $projects as $project ) { ?> <div> <?php echo get_the_post_thumbnail($project->ID); ?> </div> <?php } } ?>
I created a solution through trial and error, unfortunately having to resort to custom fields. I added a custom field to every child element i wanted to display and used the code: <?php $args = array( 'post_type' => 'page', 'meta_key' => 'xxxx', 'meta_value' => 'xxxx' ); $myPages = new WP_Query($args); while ($myPages->have_posts()) : $myPages->the_post(); echo "$post->post_title"; echo the_post_thumbnail(); endwhile; wp_reset_postdata(); ?> This was done by navigating to the specific pages I want to display and creating a custom field, which adds meta data to the page.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "php, post thumbnails" }
Use Timber/Twig to pull an image by image ID Is it possible to use Twig to pull an image by ID, or only to pull the `post.thumbnail`? The Twig docs don't seem to cover any other image need and I'd like to specify a backup image in case no `post.thumbnail` is found. I think what I need is something like `wp_get_attachment_image_src(1234,'medium_16x9')` but in Twig's language. <a href="{{post.link}}"> {% if post.thumbnail %} <img src="{{ post.thumbnail.src('medium_16x9') }}"> {% else %} <img src="{{ wp_get_attachment_image_src(1234,'medium_16x9') }}"> {% endif %} </a> I suppose I could set this up in the PHP by adding the backup image URL to a variable, but this means I'd have to add that code to every PHP file that calls this twig. It's better to grab the image in the twig, no?
`{{ post.thumbnail.ID }}` will get you the image ID, but to answer what you're after.... <img src="{{ post.thumbnail.src('medium_16x9') | default( Image(1234).src('medium_16x9') ) }}"> Reference
stackexchange-wordpress
{ "answer_score": 4, "question_score": 2, "tags": "php, templates, attachments, images" }
Save all custom field data into one "master" custom field Let's say we have three custom fields: * Pirates * Robots * Ninjas Maybe we're saving information about different people who are related to a post in each of those professions. What I'm trying to figure out is how to save that all into one custom field, let's call it Professions, when the page is Updated or Published (ie, when the page is saved in some way). Bonus would be to add the content to that field to. Why? This makes it a lot easier to include this stuff in default WP search results. Any ideas?
This is assuming each of the fields is a single value and you want to create a list for display... add_action('edit_post','custom_combine_fields'); function custom_combine_fields($post_id) { $pirates = get_post_meta($post_id,'pirates',true); $robots = get_post_meta($post_id,'robots',true); $ninjas = get_post_meta($post_id,'ninjas',true); $professions = array(); if ($pirates) {$professions[] = $pirates;} if ($robots) {$professions[] = $robots;} if ($ninjas) {$professions[] = $ninjas;} if (count($professions) > 0) { $professions = implode(', ',$professions); update_post_meta($post_id,'professions',$professions); } } I don't see much great advantage to doing this on save rather than in a display template but if you really want to that should do it.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "custom field" }
Return value of get_background_color I want to return the value of `get_background_color` but that value isn't showing up. <?php echo get_background_color(); ?> I have `colors` enabled in my customizer, and there is the option 'background color', so I'm kinda confused about this option. * * * And also, how can I add a colorpicker option in the customizer so I can remove the `colors` section? I have tried: $wp_customize->add_setting('bgcolor'); $wp_customize->add_control('bgcolor', array( 'label' => 'Background color', 'section' => 'themeoptions', 'type' => 'color-picker', )); and $wp_customize->add_setting('bgcolor'); $wp_customize->add_control('bgcolor', array( 'label' => 'Background color', 'section' => 'themeoptions', 'type' => 'color', )); but with the above example the customizer goes blank. Thanks in advance.
To add custom background support in your theme you need to register the default custom background support. Example:- add_action('after_setup_theme', function(){ add_theme_support( 'custom-background', array( 'default-color' => 'black' //Default color )); }); Now you will see a new section _Background Image_ in customizer and in _Color_ you will see a new option _Background color_ Once you will save the settings you can use `echo get_background_color();`
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "theme customizer, custom background" }
custom field (video/audio url) and embed functionality I was wondering if there is any way to combine a custom field (in custom post type) with an embed shortcode? Long story short - a user type into a field called videox and an url for a video (youtube, vimeo) or audio (e.g. soundcloud). When I render this field, of course it displays as it was in the field. How do I convert such input into an embeded audio / video? I've tried to echo that input between embed (as `do_shortcode('[embed]' . $adresgoeshere . '[/embed]');`) yet without success.
As you are using URLs from oEmbed provides (YouTube, Vimeo, Soundcloud, etc), I would use `wp_oembed_get()` function. This function uses oEmbed and tries to get the embed HTML of the provided URL. $embed = wp_oembed_get( $some_url ); if( $embed ) { echo $embed; } else { // The embed HTML couldn't be fetched }
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "custom field, shortcode, embed" }
Get latest posts from multiple categories So I am using the code below to retrieve the latest 5 posts from 5 different categories. The problem is that it outputs the latest 5 posts from only the first category in the array, even if there are newer posts in the other 4 categories. If I remove the first category from the array, then it simply outputs the latest 5 posts from the next category in the array. It never gets to the remaining categories. What I wanted to do was to output the newest 5 posts from _all_ the 5 categories _combined_. What can I do to fix that? <?php $args = array( 'posts_per_page' => 5, 'category' => 15,16,17,18,19); $myposts = get_posts( $args ); ?> <?php foreach ( $myposts as $post ) : setup_postdata( $post ); ?> <?php the_title(); ?> <?php the_content(); ?> <?php endforeach; wp_reset_postdata();?>
2 choices here, you either need to set the category as an array e.g. $args = array( 'posts_per_page' => 5, 'category' => array(15,16,17,18,19) ); You can't just add the numbers in a list but I can't find any documentation that the category element allows multiples (as the name is category) The other option is to use wp_query and category__in $query = new WP_Query( array( 'category__in' => array(15,16,17,18,19), 'posts_per_page' => 5, 'post_type' => 'post', ) ); if ( $query->have_posts() ) { while ( $query->have_posts() ) { $query->the_post(); // do something } } wp_reset_postdata(); These will get the 5 last posts from any of those categories, if you want to get a post from each of them then the query needs to be a lot different
stackexchange-wordpress
{ "answer_score": 4, "question_score": 1, "tags": "get posts" }
Using Conditionals when homepage is a page and blog is /blog I am setting up a blog with a static front page (name: Front Page, slug: front-page) and the blog on a page named "Blog" with the slug "blog". What I want to do is have my site title be inside and h1 element when the page is post listing such as /blog, but then be inside and h6 element when it it is a page, single post, etc. Right now my condition looks as follows: <?php if ( is_page( 'blog' ) ) : ?> <h1>POST LISTING</h1> <?php else : ?> <h1>NOT POST LISTING</h1> <?php endif; ?> When I pull the sit up, everything displays the NOT POST LISTING text, even /blog. What am I missing?
`is_home` is the check you need to use if the page is set to be the blog page in settings > reading <?php if(is_home()) { // do something } else { // do something } ?>
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "php" }
API to filter new user registration $POST data? Is there an `add_filter` where you can see/modify all the `$_POST` data submitted for a new user registration before the user is created? Thanks
Well once I looked into it, it is quite simple. `$_POST` is global variable and contains all the POSTed data that was sent from the form. For example, to email yourself all the posted data submitted in the form, you you could use something like this: function email_me_post_data() { global $_POST; $msg = print_r($_POST, true); mail('[email protected]', 'Example POST data', $msg); } add_action( 'user_register', 'email_me_post_data' ); Note that user_register action occurs AFTER the new user is created. Not sure you can get to the post data before user is created, although you could still modify data and re-save the changes.
stackexchange-wordpress
{ "answer_score": 2, "question_score": 2, "tags": "plugins, plugin development" }
Custom post type clean shortlink In a multisite installation I want to change the shortlink for custom post types from this ` to this ` I saw that if I set the permalinks settings to `/%post_id%/` it's working fine. Is this an official acceptable way or just a hack?
Yes this is correct. You can choose custom permalink the way you want. But it is limited to these official tags only. And `%post_id%` is one of those tags so you can use it. Just a note here you need to end the custom structure with post ID or name as codex says > Make sure to end your structure with either `%post_id%` or `%postname%` (e.g. `/%year%/%monthnum%/%day%/%postname%/`) so that each permalink points to an individual post.
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "permalinks" }
show hide image script after 4 seconds On my homepage I need a javascript/jQuery script to show our site logo image and close it after 5 seconds. Only when user visits the first time our site. No mouseover or clicks needed. Complete automatic. Seen several parts of scripts here on stackexchange, but not what I described here above. Also not included with a certain image. This is the image: rdp_banner.jpg Maybe there is someone who can help me, I hope. Regards
If you had for example, <img src="rdp_banner.jpg" id="logoimage"> You could just do... add_action('init','checkvisitcookie'); function checkvisitcookie() { if (isset($_COOKIE['firsttimevisit'])) {return;} setCookie('firsttimevisit','1',100*365*24*60*60); add_action('wp_footer','fadelogoout'); } function fadelogoout() { echo "<script> jQuery(document).ready(function() { setTimeout(function() { jQuery('#logoimage').fadeOut(); }, 5000); }); </script>"; } Just to make it almost relevant to WordPress ;-)
stackexchange-wordpress
{ "answer_score": 1, "question_score": -8, "tags": "images, jquery, javascript" }
Add class to menu ul with active child I'm trying to add the class `is-active` to the ul when the ul has an active child. This is because Foundation requires that (i'm using FoundationPress as a base theme) This is the markup i'm after: <ul class="vertical menu" data-multi-open="false" data-accordion-menu> <li><a href="/home/">Home</a> <ul class="vertical nested menu is-active"> <li class="active"> <a href="/sample-page/distribution/">Distribution</a> </li> <li><a href="/sample-page/">Sample Page</a></li> <li><a href="/sample-page/production/">Production</a></li> </ul> </li> <li><a href="/about/">About</a></li> </ul> Is it possible to hook in to `nav_menu_css_class` or do i have to make a custom walker or how should i go about to achieve this?
You certainly could build a custom walker, but perhaps the easiest way out is jquery: $("li.active").parent().addClass("is-active");
stackexchange-wordpress
{ "answer_score": 2, "question_score": 2, "tags": "menus, jquery, navigation" }
Check if sidebar is active on page with id How can i check if a certain sidebar is active on a certain page from functions.php using page id or some other page meta data?
You mean like this: if (is_active_sidebar($sidebar-name) && is_page($page-id)) {do your thing} ?
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "pages, sidebar" }
Make a PHP file with a function I want to use the breadcrumb function as listed here: < Putting the code in functions.php works for me, but I would rather have it in a separate PHP file. How can I make a separate file with the code and load/call the code in template?
You really shouldn't be doing this. Functions belong in the functions file. Period. (Or perhaps in a separate functions file which you include in the main one) However, if you insist, you can drop functions in any template file you want, because PHP doesn't care. Actually you will need to include it in every template file where you want to call `dimox_breadcrumbs()`. In which case you would have to be careful not to include it twice in one page. So, only insist if you can handle the hassle.
stackexchange-wordpress
{ "answer_score": 2, "question_score": -2, "tags": "functions, templates, get template part, breadcrumb" }
Bootstrap navbar-fixed-top issues I am using a Bootstrap navbar-fixed-top and I have added this css to drop it below the admin bar: @media screen and ( max-width: 782px ) { .logged-in .navbar-fixed-top { margin-top: 46px; } } @media screen and ( min-width: 782px ) { .logged-in .navbar-fixed-top { top: 32px; } } This is working fine for everything above 600px, but once it drops below that the admin bar is no longer fixed (which is fine) and there is a gap above the navbar where it used to be. What can I do to fix this?
In `admin-bar.min.css` at 600px, `#wpadminbar` is changed from `position:fixed` to `position:absolute`. The reason the adminbar scrolls at mobile sizes is because a fixed-height, fixed-position element causes major problems when you tap/pinch-to-zoom in mobile browsers. So, you can fix this by overriding WP's native css on `#wpadminbar`, but then the behaviour is deliberate.
stackexchange-wordpress
{ "answer_score": 0, "question_score": -1, "tags": "css, twitter bootstrap, admin bar" }
Consolidating two websites into one, but migrated images not appearing in Image Library I am consolidating two websites (which are on the same server) into one. I copied the images from one website's directory to the other using rsync. `rsync -av /srv/www/site1/wp-content/uploads/ /srv/www/site2/wp-content/uploads/` The images appear in the target directory and file permissions and ownerships are fine. But the images are not appearing in the Media Library and there is no way to link to these images as Featured Images in Jigoshop product items. Why are these migrated images not appearing in the Media Library? Is there a way to force WordPress to search the library for new images?
By default, when you upload an image via the admin, it's metadata is added to the database, and that's how you can search through them in the media library etc. If you upload images via ftp then they won't appear in the DB so won't show up in the admin area. Use a plugin such as < which will let you loop through every image and add them to the DB if they don't exist already.
stackexchange-wordpress
{ "answer_score": 2, "question_score": 1, "tags": "images, media library, migration" }
Condition within single.php to send an email to the post author I have this piece of code (below) that checks if the post was modified within the past 7 days. I'd like another piece of code that I can insert where "Needs Updating" is that will send a basic email to the post author that says "Someone was looking at your post and wants it updated" every time the post is viewed (yes, every time). <?php $timelimit=1 * 604800; //1 week * seconds per day $post_age = date('U') - get_post_time('U'); ?> <?php if ($post_age < $timelimit) : ?> Current <?php elseif ($post_age > $timelimit) : ?> Needs Updating <?php endif; ?>
You can use the function get_the_author_meta() to get the emailaddress of the author of the current post and the wp_mail()function to send an e-mail <?php $timelimit=1 * 604800; //1 week * seconds per day $post_age = date('U') - get_post_time('U'); if ($post_age < $timelimit) : ?> // Current <?php elseif ($post_age > $timelimit) : $email = get_the_author_meta( 'user_email' ); wp_mail( $email, $subject, $message ); endif;
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "author, conditional content, wp mail" }
Putting a resized image into media library with wp_get_image_editor( I'm using `wp_get_image_editor()` to resize and save an image that is being uploaded to the Media Library. $image = wp_get_image_editor( $newattachment_url ); if ( ! is_wp_error( $image ) ) { $image->rotate( 0 ); $image->resize( 300, 300, false ); $image->save('resizedimage.jpg'); } This is working fine however it is saving to the root of WordPress. How can I instead upload this file to the media library? I want to have the orignal image and the resized image in the media library. `$newattachment_url` is the URL of the orignally uploaded image.
You need the `generate_filename` method of the image editor class. Like this: $filename = $img->generate_filename( 'resized', ABSPATH.'wp-content/uploads/resized-images/'); $image->save($filename); This will save the image, renamed `originalname-resized`, in the `resized-images` directory of the upload folder. This does not mean WordPress knows it is there. That depends on the context in which you are calling `wp_get_image_editor()`.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 1, "tags": "plugin development, images" }
Trying to edit the single page from a Custom Post I have a custom post type where I can create pages in.("article.php") It automatically uses the template "single.php" when I create a page, although I want to change some things in it without effecting some other pages on the website. I tried making a single-article.php file, but it is still using the single.php template page. Based on the documentation it should work. What could I've done wrong?
**If you want to change the single page** `page-{page-slug}` is a good choice if you want the page template for specific page only and not multiple pages. Check out his custom page template for specific page **If you are talking about custom post type** We can use `single-$posttype.php` , here `$posttype` is your custom post type slug. WordPress template Hierarchy for single post page's custom post is in the order of : single-$posttype.php ==> single.php ==> singular.php(WP 4.3+) So if a custom post single page is requested, WP first looks for `single-$posttype` file if it's available it uses that file else it goes to `single.php` and so on as the above order. Refer to Template Hierarchy for more details.
stackexchange-wordpress
{ "answer_score": 2, "question_score": 1, "tags": "custom post types, posts, pages, templates" }
remove the wrapping of text widget or <div class=“textwidget”></div> When I write a quote in the text widget and displayed the text is wrapped as "My text...". I would like to remove the div and put simply "My text...". without using jquery. For Example: Current output <div class="container"> <div class=“textwidget”> My text... </div> </div> Required output: <div class="container"> My text... </div> This is the actual code: <div class="container"> <?php dynamic_sidebar('text_show');?> </div>
More than likely this is an issue with the `register_sidebar()` call in `functions.php`. Look for `before_widget` and `after_widget`. The code below is the default usage. 'before_widget' => '<li id="%1$s" class="widget %2$s">', 'after_widget' => '</li>', **Note:** This will alter all of the widgets within the sidebar, not just the TextWidget.
stackexchange-wordpress
{ "answer_score": 2, "question_score": 3, "tags": "functions, widgets" }
Trying To Get Child Categories To Show, Issue With foreach Loop I made 6 sub-categories, all children of my "Resources" category, and I'm trying get them to display on a page, but at the moment it's only displaying the first category (leading me to believe my error is in the `foreach` loop). **My PHP:** $categoryslug = get_category_by_slug( 'resources' ); $categories = wp_list_categories( 'title_li=0&child_of=' . $categoryslug->term_id ); foreach ( $categories as $category ) { echo '<h4><a>cat_ID).'">' . $category->cat_name . ', </a></h4>'; }
Do the categories all have posts, change line 2 to: $categories = wp_list_categories('hide_empty=0&title_li=0&child_of='.$categoryslug->term_id'); This sets it to display all categories even if empty If that doesn't work then you need to echo each part and find the cause of the "error" so echo each element e.g. echo $categoryslug; if that works then change to echo $categoryslug->term_id; If that works then print the array of categories e.g. print_r($categories); Echoing each element individually will lead you to the culprit and then you can find the root cause
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "php, categories" }