qid
int64
4
8.14M
question
stringlengths
20
48.3k
answers
list
date
stringlengths
10
10
metadata
list
input
stringlengths
12
45k
output
stringlengths
2
31.8k
309,219
<p>new here and to wordpress plugins development, go easy on me :D</p> <p>Anyway, I am trying to create a new plugin and I am getting a 500 error. I changed <code>WP_DEBUG</code> in config.php to true in order to see what is causing the 500 error and got this message:</p> <p><code>Fatal error: Uncaught Error: Call to undefined function is_woocommerce() in...</code></p> <p>This is my code currently:</p> <pre><code>&lt;?php /** * Plugin Name: * Plugin URI: * Description: * Author: * Author URI: * Version: 1.0 * Text Domain: * * Copyright: (c) 2018 * * License: * License URI: * * @author * @copyright Copyright (c) 2018 * @license * */ // defined( 'ABSPATH' ) or exit; if (function_exists(is_woocommerce())) { echo "test: ".is_woocommerce(); } else { echo "test: Function does not exists!"; } </code></pre> <p>If you need any more information, tell me and I'll edit the question. Help will be appreciated, thanks!</p>
[ { "answer_id": 309239, "author": "Futuritous", "author_id": 122392, "author_profile": "https://wordpress.stackexchange.com/users/122392", "pm_score": 2, "selected": false, "text": "<p>If you want to check one Plugin's Function / Class etc. from another Plugin, then it's best to use a hoo...
2018/07/22
[ "https://wordpress.stackexchange.com/questions/309219", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/147331/" ]
new here and to wordpress plugins development, go easy on me :D Anyway, I am trying to create a new plugin and I am getting a 500 error. I changed `WP_DEBUG` in config.php to true in order to see what is causing the 500 error and got this message: `Fatal error: Uncaught Error: Call to undefined function is_woocommerce() in...` This is my code currently: ``` <?php /** * Plugin Name: * Plugin URI: * Description: * Author: * Author URI: * Version: 1.0 * Text Domain: * * Copyright: (c) 2018 * * License: * License URI: * * @author * @copyright Copyright (c) 2018 * @license * */ // defined( 'ABSPATH' ) or exit; if (function_exists(is_woocommerce())) { echo "test: ".is_woocommerce(); } else { echo "test: Function does not exists!"; } ``` If you need any more information, tell me and I'll edit the question. Help will be appreciated, thanks!
If you want to check one Plugin's Function / Class etc. from another Plugin, then it's best to use a hook like [`plugins_loaded`](https://codex.wordpress.org/Plugin_API/Action_Reference/plugins_loaded). Based on this, your Plugin CODE will look like: ``` <?php /* Plugin Name: YOUR PLUGIN NAME */ defined( 'ABSPATH' ) or exit; add_action( 'plugins_loaded', 'plugin_prefix_woocommerce_check' ); function plugin_prefix_woocommerce_check() { if( function_exists( 'is_woocommerce' ) ) { add_action( "wp_footer", "wpse_woocommerce_exists" ); } else { add_action( "wp_footer", "wpse_woocommerce_doesnt_exist" ); } } function wpse_woocommerce_exists() { echo "<h1>WooCommerce Exists!</h1>"; } function wpse_woocommerce_doesnt_exist() { echo "<h1>WooCommerce Doesn't Exists!</h1>"; } ``` Directly checking other plugin functions will often lead to error, since WordPress may not be done loading other plugins by the time your CODE executes. However, when WordPress is done, it'll fire the `plugins_loaded` hook. Check [Plugin Development Guide](https://developer.wordpress.org/plugins/) for more information on how to develop a WordPress Plugin.
309,222
<p>My website is a product review website. I'm using woocomerce in order to store all products and let user be able to search them by category and attributes.</p> <p>Due this, I would like to remove some unnecessary options from my wordpress admin like inventory and shipping.</p> <p>.<a href="https://i.stack.imgur.com/woW1A.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/woW1A.png" alt="enter image description here"></a></p> <p>How can I disable those functions from my wordpress??</p>
[ { "answer_id": 309281, "author": "Sitezilla", "author_id": 143362, "author_profile": "https://wordpress.stackexchange.com/users/143362", "pm_score": 0, "selected": false, "text": "<p>Do you give users access to the backpanel? Shipping and inventory are not attributes that really distract...
2018/07/22
[ "https://wordpress.stackexchange.com/questions/309222", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/97543/" ]
My website is a product review website. I'm using woocomerce in order to store all products and let user be able to search them by category and attributes. Due this, I would like to remove some unnecessary options from my wordpress admin like inventory and shipping. .[![enter image description here](https://i.stack.imgur.com/woW1A.png)](https://i.stack.imgur.com/woW1A.png) How can I disable those functions from my wordpress??
Just add below function in your function file ``` /*For remove tab from product tab*/ function remove_linked_products($tabs){ unset($tabs['inventory']); unset($tabs['shipping']); return($tabs); } add_filter('woocommerce_product_data_tabs', 'remove_linked_products', 10, 1); /*Remove Virtual and Downloadeble checkbox*/ function remove_product_type_options( $options ) { unset( $options['virtual'] ); unset( $options['downloadable'] ); return $options; } add_filter( 'product_type_options', 'remove_product_type_options' ); ```
309,223
<p>I have created a code through which the current user can add other users to his project. These users are only shown on the project page. They will not have any right to modify the project.</p> <p>Once these users are inserted to database it sends an email to them. I want to restrict sending mail to the current user. How can I do that?</p> <pre><code>$member_details-&gt;user_email = array_map( 'sanitize_text_field', $_POST['user_email'] ); $member_details-&gt;user_role = array_map( 'sanitize_text_field', $_POST['user_role'] ); $member_details-&gt;status = array_map( 'sanitize_text_field', $_POST['status'] ); $member_details_encode = wp_json_encode( $member_details ); global $wpdb; $member_result = $wpdb-&gt;insert( 'wpxa_project_members', array( 'project_id' =&gt; $_SESSION['project_id'], 'author_id' =&gt; $post_author, 'member_details' =&gt; $member_details_encode ), array( '%d', '%d', '%s' ) ); $user_email = $member_details-&gt;user_email; $subject = "Congrats! You are added to the Project - " . "'" . $project_title . "'"; $message = 'If you are not the member of project plz contact us to remove at info@gmail.com'; wp_mail( $user_email, $subject, $message ); </code></pre>
[ { "answer_id": 309306, "author": "Andrea Somovigo", "author_id": 64435, "author_profile": "https://wordpress.stackexchange.com/users/64435", "pm_score": 1, "selected": false, "text": "<p>Try this:</p>\n\n<pre><code>//after $wpdb-&gt;insert function\n\n$current_user = wp_get_current_user...
2018/07/22
[ "https://wordpress.stackexchange.com/questions/309223", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/124069/" ]
I have created a code through which the current user can add other users to his project. These users are only shown on the project page. They will not have any right to modify the project. Once these users are inserted to database it sends an email to them. I want to restrict sending mail to the current user. How can I do that? ``` $member_details->user_email = array_map( 'sanitize_text_field', $_POST['user_email'] ); $member_details->user_role = array_map( 'sanitize_text_field', $_POST['user_role'] ); $member_details->status = array_map( 'sanitize_text_field', $_POST['status'] ); $member_details_encode = wp_json_encode( $member_details ); global $wpdb; $member_result = $wpdb->insert( 'wpxa_project_members', array( 'project_id' => $_SESSION['project_id'], 'author_id' => $post_author, 'member_details' => $member_details_encode ), array( '%d', '%d', '%s' ) ); $user_email = $member_details->user_email; $subject = "Congrats! You are added to the Project - " . "'" . $project_title . "'"; $message = 'If you are not the member of project plz contact us to remove at info@gmail.com'; wp_mail( $user_email, $subject, $message ); ```
I have found the answer. Here it is: ``` if ( ! empty( $member_result ) ) { $user_emails = $member_details->user_email; for ($i=1; $i < count($user_emails); $i++) { $user_email[] = $user_emails[$i]; } $to = $user_email; $subject = "Congrats! You are added to the Project - " . "'" . $project_title . "'"; $message = 'If you are not the member of project plz contact us to remove at mineshrai@gmail.com'; wp_mail( $to, $subject, $message ); } ```
309,240
<p>I've cloned the production site at example.com to my own dev server, calling it example.mydomain.com. It displays OK, as long as I use port 8080 (bypassing my varnish server).</p> <p>I can successfully log in to the <code>wp-admin</code> page at <strong>example.com</strong>, but I can't reach the page at <strong>example.mydomain.com/wp-admin</strong> - it redirects to the homepage of <strong>example.com</strong>. </p> <p>Suspecting my varnish set up might be at fault, I visited <strong>example.mydomain.com:8080/wp-admin</strong> and was presented with a login form.</p> <p>However, entering the credentials there logs me into and redirects me to, <strong>example.com/wp-admin/</strong> - the production site. I've even looked at the query string that appears thus: <strong><a href="http://example.myserver.com:8080/wp-login.php?redirect_to=http%3A%2F%2Fexample.myserver.com%3A8080%2Fwp-admin%2F&amp;reauth=1" rel="nofollow noreferrer">http://example.myserver.com:8080/wp-login.php?redirect_to=http%3A%2F%2Fexample.myserver.com%3A8080%2Fwp-admin%2F&amp;reauth=1</a></strong> - which looks like it'll do the right thing, but no joy.</p> <p>I've done a full text search of the codebase, looking for places where the server name might be hard coded, and found nothing obvious (except some image links in the CSS).</p> <p>So I'm thinking maybe there's some config settings stored in the database. But I have no idea where to look.</p>
[ { "answer_id": 309241, "author": "Castiblanco", "author_id": 44370, "author_profile": "https://wordpress.stackexchange.com/users/44370", "pm_score": 2, "selected": true, "text": "<p>Check for <code>wp-config.php</code> file.</p>\n\n<p>Find these two lines to your <code>wp-config.php</cod...
2018/07/22
[ "https://wordpress.stackexchange.com/questions/309240", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/147347/" ]
I've cloned the production site at example.com to my own dev server, calling it example.mydomain.com. It displays OK, as long as I use port 8080 (bypassing my varnish server). I can successfully log in to the `wp-admin` page at **example.com**, but I can't reach the page at **example.mydomain.com/wp-admin** - it redirects to the homepage of **example.com**. Suspecting my varnish set up might be at fault, I visited **example.mydomain.com:8080/wp-admin** and was presented with a login form. However, entering the credentials there logs me into and redirects me to, **example.com/wp-admin/** - the production site. I've even looked at the query string that appears thus: **<http://example.myserver.com:8080/wp-login.php?redirect_to=http%3A%2F%2Fexample.myserver.com%3A8080%2Fwp-admin%2F&reauth=1>** - which looks like it'll do the right thing, but no joy. I've done a full text search of the codebase, looking for places where the server name might be hard coded, and found nothing obvious (except some image links in the CSS). So I'm thinking maybe there's some config settings stored in the database. But I have no idea where to look.
Check for `wp-config.php` file. Find these two lines to your `wp-config.php`, and make sure "example.com" is the correct location of your site. ``` define('WP_HOME','http://example.com'); define('WP_SITEURL','http://example.com'); ``` Also on the database, check for table `wp_options`, check these two **option\_name**; `siteurl` and `home`.
309,310
<p>used this code and that did not worked for me.</p> <pre><code>echo str_replace( "&lt;br&gt;", "", wp_list_categories(array('title_li' =&gt; false, 'style' =&gt; false))); </code></pre> <p>what did I missed?</p>
[ { "answer_id": 309312, "author": "Trilok", "author_id": 145962, "author_profile": "https://wordpress.stackexchange.com/users/145962", "pm_score": 1, "selected": false, "text": "<pre><code>Please use below code it will help you\n $args = [\n 'style' =&gt; 'none',\n 'separator' =...
2018/07/23
[ "https://wordpress.stackexchange.com/questions/309310", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/147385/" ]
used this code and that did not worked for me. ``` echo str_replace( "<br>", "", wp_list_categories(array('title_li' => false, 'style' => false))); ``` what did I missed?
You can replace '<br>' with '' by setting **separator** value ``` echo wp_list_categories(array('title_li' => false, 'style' => false, 'separator' => '')); ```
309,331
<p>I create a table in the footer.</p> <p>I would like to show some statistics, like total posts, weekly posts, total posts of the specific category.</p> <p>I just echo total posts with <code>wp_count_posts()-&gt;publish;</code></p> <p>What can I do for the other one?</p>
[ { "answer_id": 309333, "author": "idpokute", "author_id": 87895, "author_profile": "https://wordpress.stackexchange.com/users/87895", "pm_score": 1, "selected": false, "text": "<p>Wordpress query supports <a href=\"https://codex.wordpress.org/Class_Reference/WP_Query#Date_Parameters\" re...
2018/07/23
[ "https://wordpress.stackexchange.com/questions/309331", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/141105/" ]
I create a table in the footer. I would like to show some statistics, like total posts, weekly posts, total posts of the specific category. I just echo total posts with `wp_count_posts()->publish;` What can I do for the other one?
You already have the total post, so in order to get the total post within the last week, it's better if you do this on your `functions.php` file: ``` function get_posts_count_from_last_week($post_type ='post') { global $wpdb; $numposts = $wpdb->get_var( $wpdb->prepare( "SELECT COUNT(ID) ". "FROM {$wpdb->posts} ". "WHERE ". "post_status='publish' ". "AND post_type= %s ". "AND post_date> %s", $post_type, date('Y-m-d H:i:s', strtotime('-168 hours')) ) ); return $numposts; } ``` And then use it in the footer. ``` <?php echo get_posts_count_from_last_week(); ?> ``` To work with categories we could use [WP\_Query](http://codex.wordpress.org/Class_Reference/WP_Query): ``` $args = array( 'cat' => 4, 'post_type' => 'videos' ); $the_query = new WP_Query( $args ); echo $the_query->found_posts; ```
309,395
<p>Is it possible to add custom meta boxes to the default blocks in Gutenberg? I would need to add a user-defined data-attribute to each block. This data-attribute then would be printed on the frontend to the wrapper element. I havent been able to find any documentation on how to do this.</p> <p>An image to illustrate what I mean. <a href="https://i.stack.imgur.com/jevKz.jpg" rel="noreferrer"><img src="https://i.stack.imgur.com/jevKz.jpg" alt="enter image description here"></a></p>
[ { "answer_id": 309401, "author": "Harsh", "author_id": 131853, "author_profile": "https://wordpress.stackexchange.com/users/131853", "pm_score": -1, "selected": false, "text": "<p>For custom meta boxes usees in Gutenberg, please check the following link.\n<a href=\"https://wordpress.org/...
2018/07/24
[ "https://wordpress.stackexchange.com/questions/309395", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/97361/" ]
Is it possible to add custom meta boxes to the default blocks in Gutenberg? I would need to add a user-defined data-attribute to each block. This data-attribute then would be printed on the frontend to the wrapper element. I havent been able to find any documentation on how to do this. An image to illustrate what I mean. [![enter image description here](https://i.stack.imgur.com/jevKz.jpg)](https://i.stack.imgur.com/jevKz.jpg)
Using [filters](https://wordpress.org/gutenberg/handbook/designers-developers/developers/filters/block-filters/) we can modify the props and attributes of blocks. First we extend the attributes to include the new attribute: ``` const { addFilter } = wp.hooks; // Register/add the new attribute. const addExtraAttribute = props => { const attributes = { ...props.attributes, extra_attribute: { type: "string", default: "default_value" } }; return { ...props, attributes }; }; addFilter( "blocks.registerBlockType", "my-plugin/extra-attribute", addExtraAttribute ); ``` Then we extend the edit function of the block to include a control to modify the attribute: ``` const { addFilter } = wp.hooks; const { createHigherOrderComponent } = wp.compose; const { Fragment } = wp.element; const { InspectorControls } = wp.editor; const { PanelBody, TextControl } = wp.components; const addTextControl = createHigherOrderComponent(BlockEdit => { return props => { const { attributes, setAttributes } = props; return ( <Fragment> <BlockEdit {...props} /> <InspectorControls> <PanelBody> <TextControl value={attributes.extra_attribute} onChange={value => { setAttributes({ extra_attribute: value }); }} /> </PanelBody> </InspectorControls> </Fragment> ); }; }, "withInspectorControl"); addFilter("editor.BlockEdit", "my-plugin/extra-attribute", addTextControl); ``` Finally we extend the props assigned to the save function and include the [data attribute](https://developer.mozilla.org/en-US/docs/Learn/HTML/Howto/Use_data_attributes) with the added attribute value: ``` const { addFilter } = wp.hooks; // Add extra props. Here we assign an html // data-attribute with the extra_attribute value. const addExtraData = (props, block_type, attributes) => { return { ...props, "data-extra": attributes.extra_attribute } }; addFilter( "blocks.getSaveContent.extraProps", "my-plugin/extra-attribute", addExtraData ); ```
309,403
<p>I have created an Add / Remove Dynamic input fields. I am using <code>wp_mail();</code> to send mails. I have restricted the first user from receiving mail. I want to send mail to other users. Everything is working properly. The only problem is that every user is getting double emails. <code>wp_mail();</code> creates it twice at same time.</p> <p>Means when I submits the form each user receives same email twice. I want each user should receive one email only. Following is my code :</p> <pre><code>&lt;?php get_header(); ?&gt; &lt;?php $member_details-&gt;user_email = array_map( 'sanitize_text_field', $_POST['user_email'] ); $member_details-&gt;user_role = array_map( 'sanitize_text_field', $_POST['user_role'] ); $member_details-&gt;status = array_map( 'sanitize_text_field', $_POST['status'] ); if ( isset( $_POST['project_prev'] ) ) { $user_emails = $member_details-&gt;user_email; $user_statuses = $member_details-&gt;status; for ($i=1; $i &lt; count($user_emails); $i++) { $user_email1[] = $user_emails[$i]; } for ($a=1; $a &lt; count($user_statuses); $a++) { $user_status = $user_statuses[$a]; if ( $user_status == 'Unverified' ) { $to = $user_email1; $subject = "Congrats! You are added to the Project - " . "'" . $project_title . "'"; $message = 'If you are not the member of project plz contact us to remove at mineshrai@gmail.com'; wp_mail( $to, $subject, $message ); } } } ?&gt; &lt;form method="POST"&gt; &lt;div class="panel panel-default"&gt; &lt;div class="panel-heading"&gt;&lt;center&gt;&lt;b&gt;Team Members&lt;/b&gt;&lt;/center&gt;&lt;/div&gt; &lt;div class="panel-body"&gt; &lt;div class="row"&gt; &lt;div class="col-md-5"&gt;&lt;label&gt;Member's Registered Email&lt;/label&gt;&lt;/div&gt; &lt;div class="col-md-5"&gt;&lt;label&gt;Role in Project&lt;/label&gt;&lt;/div&gt; &lt;div class="col-md-2"&gt;&lt;/div&gt; &lt;/div&gt; &lt;div class="row"&gt; &lt;div class="col-md-5"&gt; &lt;div class="form-group"&gt; &lt;input type="text" class="form-control" name="user_email[]" value="&lt;?php $current_user = wp_get_current_user(); if ( !($current_user instanceof WP_User) ) return; echo $current_user-&gt;user_email; ?&gt;" placeholder="" readonly="readonly"&gt; &lt;/div&gt; &lt;/div&gt; &lt;div class="col-md-5"&gt; &lt;div class="form-group"&gt; &lt;input type="text" class="form-control" name="user_role[]" placeholder=""&gt; &lt;input type="hidden" class="form-control" name="status[]" value="Verified" placeholder=""&gt; &lt;/div&gt; &lt;/div&gt; &lt;div class="col-md-2"&gt; &lt;button type="button" class="btn btn-success" id="add-member-fields"&gt;&lt;span class="glyphicon glyphicon-plus" aria-hidden="true"&gt;&lt;/span&gt; Add&lt;/button&gt; &lt;/div&gt; &lt;/div&gt; &lt;div id="member-fields"&gt; &lt;/div&gt; &lt;p class="help-block"&gt;&lt;i&gt;To add member please register new User, if already not registered.&lt;/i&gt;&lt;/p&gt; &lt;/div&gt; &lt;/div&gt; &lt;input class="btn btn-info btn-block" type="submit" name="project_prev" value="Preview" style="border-radius: 0px;"&gt; &lt;/form&gt; &lt;?php $user = wp_get_current_user(); $args = array( 'role' =&gt; 'backer', 'exclude' =&gt; array( $user-&gt;ID ), ); $users = get_users( $args ); $get_user_emails = wp_list_pluck( $users, 'user_email' ); ?&gt; &lt;script type='text/javascript'&gt; jQuery(document).ready(function($) { var wrapper = $("#member-fields"); var add_button = $("#add-member-fields"); var x = 1; var availableAttributes = &lt;?php echo json_encode($get_user_emails); ?&gt;; var previousValue=""; add_button.click(function(e) { e.preventDefault(); x++; var element = $('&lt;div id="user-fields"&gt;&lt;div class="row"&gt;&lt;div class="col-md-5"&gt;&lt;div class="form-group"&gt;&lt;input type="text" class="form-control" id="user_email" name="user_email[]" placeholder=""&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class="col-md-5"&gt;&lt;div class="form-group"&gt;&lt;input type="text" class="form-control" name="user_role[]" placeholder=""&gt;&lt;input type="hidden" class="form-control" name="status[]" value="Unverified" placeholder=""&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class="col-md-2"&gt;&lt;button type="button" class="btn btn-danger" id="remove_member_field"&gt;&lt;span class="glyphicon glyphicon-remove" aria-hidden="true"&gt;&lt;/span&gt; Remove&lt;/button&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class="clear"&gt;&lt;/div&gt;&lt;/div&gt;'); element.fadeIn("slow").find("input[name^='user_email']").autocomplete({ autoFocus: true, source: availableAttributes, }); wrapper.append(element); }); wrapper.on("keyup","#user_email",function() { var isValid = false; for (i in availableAttributes) { if (availableAttributes[i].toLowerCase().match(this.value.toLowerCase())) { isValid = true; } } if (!isValid) { this.value = previousValue } else { previousValue = this.value; } }); wrapper.on("click", "#remove_member_field", function(e) { e.preventDefault(); $(this).parent().fadeOut(300, function() { $(this).closest('#user-fields').remove(); x--; }); }); }); &lt;/script&gt; &lt;?php get_footer(); ?&gt; </code></pre>
[ { "answer_id": 309406, "author": "WebElaine", "author_id": 102815, "author_profile": "https://wordpress.stackexchange.com/users/102815", "pm_score": 0, "selected": false, "text": "<p>The problem here is, you first create an array of all the email addresses, and then in your second \"for\...
2018/07/24
[ "https://wordpress.stackexchange.com/questions/309403", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/124069/" ]
I have created an Add / Remove Dynamic input fields. I am using `wp_mail();` to send mails. I have restricted the first user from receiving mail. I want to send mail to other users. Everything is working properly. The only problem is that every user is getting double emails. `wp_mail();` creates it twice at same time. Means when I submits the form each user receives same email twice. I want each user should receive one email only. Following is my code : ``` <?php get_header(); ?> <?php $member_details->user_email = array_map( 'sanitize_text_field', $_POST['user_email'] ); $member_details->user_role = array_map( 'sanitize_text_field', $_POST['user_role'] ); $member_details->status = array_map( 'sanitize_text_field', $_POST['status'] ); if ( isset( $_POST['project_prev'] ) ) { $user_emails = $member_details->user_email; $user_statuses = $member_details->status; for ($i=1; $i < count($user_emails); $i++) { $user_email1[] = $user_emails[$i]; } for ($a=1; $a < count($user_statuses); $a++) { $user_status = $user_statuses[$a]; if ( $user_status == 'Unverified' ) { $to = $user_email1; $subject = "Congrats! You are added to the Project - " . "'" . $project_title . "'"; $message = 'If you are not the member of project plz contact us to remove at mineshrai@gmail.com'; wp_mail( $to, $subject, $message ); } } } ?> <form method="POST"> <div class="panel panel-default"> <div class="panel-heading"><center><b>Team Members</b></center></div> <div class="panel-body"> <div class="row"> <div class="col-md-5"><label>Member's Registered Email</label></div> <div class="col-md-5"><label>Role in Project</label></div> <div class="col-md-2"></div> </div> <div class="row"> <div class="col-md-5"> <div class="form-group"> <input type="text" class="form-control" name="user_email[]" value="<?php $current_user = wp_get_current_user(); if ( !($current_user instanceof WP_User) ) return; echo $current_user->user_email; ?>" placeholder="" readonly="readonly"> </div> </div> <div class="col-md-5"> <div class="form-group"> <input type="text" class="form-control" name="user_role[]" placeholder=""> <input type="hidden" class="form-control" name="status[]" value="Verified" placeholder=""> </div> </div> <div class="col-md-2"> <button type="button" class="btn btn-success" id="add-member-fields"><span class="glyphicon glyphicon-plus" aria-hidden="true"></span> Add</button> </div> </div> <div id="member-fields"> </div> <p class="help-block"><i>To add member please register new User, if already not registered.</i></p> </div> </div> <input class="btn btn-info btn-block" type="submit" name="project_prev" value="Preview" style="border-radius: 0px;"> </form> <?php $user = wp_get_current_user(); $args = array( 'role' => 'backer', 'exclude' => array( $user->ID ), ); $users = get_users( $args ); $get_user_emails = wp_list_pluck( $users, 'user_email' ); ?> <script type='text/javascript'> jQuery(document).ready(function($) { var wrapper = $("#member-fields"); var add_button = $("#add-member-fields"); var x = 1; var availableAttributes = <?php echo json_encode($get_user_emails); ?>; var previousValue=""; add_button.click(function(e) { e.preventDefault(); x++; var element = $('<div id="user-fields"><div class="row"><div class="col-md-5"><div class="form-group"><input type="text" class="form-control" id="user_email" name="user_email[]" placeholder=""></div></div><div class="col-md-5"><div class="form-group"><input type="text" class="form-control" name="user_role[]" placeholder=""><input type="hidden" class="form-control" name="status[]" value="Unverified" placeholder=""></div></div><div class="col-md-2"><button type="button" class="btn btn-danger" id="remove_member_field"><span class="glyphicon glyphicon-remove" aria-hidden="true"></span> Remove</button></div></div><div class="clear"></div></div>'); element.fadeIn("slow").find("input[name^='user_email']").autocomplete({ autoFocus: true, source: availableAttributes, }); wrapper.append(element); }); wrapper.on("keyup","#user_email",function() { var isValid = false; for (i in availableAttributes) { if (availableAttributes[i].toLowerCase().match(this.value.toLowerCase())) { isValid = true; } } if (!isValid) { this.value = previousValue } else { previousValue = this.value; } }); wrapper.on("click", "#remove_member_field", function(e) { e.preventDefault(); $(this).parent().fadeOut(300, function() { $(this).closest('#user-fields').remove(); x--; }); }); }); </script> <?php get_footer(); ?> ```
These `POST` variables: `$_POST['user_email']`, `$_POST['user_role']`, and `$_POST['status']` (which each is an `array`) are connected to each other by their index, hence you can loop through just one of them and use the *same index* (or iterator) to access the items in the *other* arrays. This should help you understand it: ``` for ( $i = 0; $i < count( $member_details->user_email ); $i++ ) { $user_email = $member_details->user_email[ $i ]; $user_role = $member_details->user_role[ $i ]; $status = $member_details->status[ $i ]; ... } ``` So this part/code: ``` if ( isset( $_POST['project_prev'] ) ) { $user_emails = $member_details->user_email; $user_statuses = $member_details->status; ... } ``` I coded it like this: (*Note that I re-indented it for clarity.*) ``` if ( isset( $_POST['project_prev'] ) ) { // Starts with the first user (index 1). for ( $i = 1; $i < count( $member_details->user_email ); $i++ ) { $user_status = $member_details->status[ $i ]; if ( $user_status === 'Unverified' ) { $to = $member_details->user_email[ $i ]; $project_title = '??'; // This wasn't defined anywhere in the file/code. $subject = "Congrats! You are added to the Project - " . "'" . $project_title . "'"; $message = 'If you are not the member of project plz contact us to remove at mineshrai@gmail.com'; wp_mail( $to, $subject, $message ); } } } ```
309,430
<p>Could someone please help me to add category id with in this query so this will return posts from a certain category? Thanks in advance.</p> <pre><code>&lt;?php foreach(_get($wp_query-&gt;posts? : array()) as $n =&gt; $post){ setup_postdata($post); ?&gt; // HTML and post Tags &lt;?php } ?&gt; </code></pre>
[ { "answer_id": 309481, "author": "Suraj Rathod", "author_id": 141555, "author_profile": "https://wordpress.stackexchange.com/users/141555", "pm_score": 1, "selected": true, "text": "<p>Please follow proper wordpress method not follow someone's code or copy paste code.</p>\n\n<pre><code> ...
2018/07/24
[ "https://wordpress.stackexchange.com/questions/309430", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/147385/" ]
Could someone please help me to add category id with in this query so this will return posts from a certain category? Thanks in advance. ``` <?php foreach(_get($wp_query->posts? : array()) as $n => $post){ setup_postdata($post); ?> // HTML and post Tags <?php } ?> ```
Please follow proper wordpress method not follow someone's code or copy paste code. ``` /* * CODEX: http://codex.wordpress.org/Class_Reference/WP_Query#Parameters * Source: https://core.trac.wordpress.org/browser/tags/3.9/src/wp- includes/query.php */ $args = array( //////Category Parameters - Show posts associated with certain categories. //http://codex.wordpress.org/Class_Reference/WP_Query#Category_Parameters //all categories parameter 'cat' => 5,//(int) - use category id. 'category_name' => 'staff, news', //(string) - Display posts that have these categories, using category slug. 'category_name' => 'staff+news', //(string) - Display posts that have "all" of these categories, using category slug. 'category__and' => array( 2, 6 ), //(array) - use category id. 'category__in' => array( 2, 6 ), //(array) - use category id. 'category__not_in' => array( 2, 6 ), //(array) - use category id. 'post_type' => 'post', //post or you can use your custom post type 'post_status' => 'publish', 'order' => 'DESC', 'orderby' => 'date'); $the_query = new WP_Query( $args ); if ( $the_query->have_posts() ) { while ( $the_query->have_posts() ) { $the_query->the_post(); // Do Stuff } // end while } // endif // Reset Post Data wp_reset_postdata(); ```
309,462
<p>I migrated my site from localhost (LAMP) to Namecheap and it is broken in that the images it is supposed to load from <code>/wp-content</code> return a 404 error. </p> <p>I can login to wp-admin and I can see the pages which load menus and text correctly. But I can't seem to get the images to load, I have tried:</p> <ul> <li>flushing permalinks</li> <li>some <code>.htaccess</code> and wp-config changes</li> </ul> <p>For example: The logo does not load when you're on the <code>/about</code> page:</p> <pre><code>https://example.com/site_dir/about </code></pre> <p>If you go to the wp-content folder the image is there but the site is not looking for it in the right directory (wp-content is in a subdirectory):</p> <pre><code>https://example.com/site_dir/wp-content/uploads/2018/05/site_dir_logo_light_textfull.png </code></pre> <p>Any help is very much appreciated!</p>
[ { "answer_id": 309465, "author": "juggler", "author_id": 147502, "author_profile": "https://wordpress.stackexchange.com/users/147502", "pm_score": 1, "selected": false, "text": "<p>It looks like your localhost site had WordPress installed in the root directory but your production site is...
2018/07/25
[ "https://wordpress.stackexchange.com/questions/309462", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/118088/" ]
I migrated my site from localhost (LAMP) to Namecheap and it is broken in that the images it is supposed to load from `/wp-content` return a 404 error. I can login to wp-admin and I can see the pages which load menus and text correctly. But I can't seem to get the images to load, I have tried: * flushing permalinks * some `.htaccess` and wp-config changes For example: The logo does not load when you're on the `/about` page: ``` https://example.com/site_dir/about ``` If you go to the wp-content folder the image is there but the site is not looking for it in the right directory (wp-content is in a subdirectory): ``` https://example.com/site_dir/wp-content/uploads/2018/05/site_dir_logo_light_textfull.png ``` Any help is very much appreciated!
It looks like your localhost site had WordPress installed in the root directory but your production site is in a sub-directory. You should review the instructions in the the WordPress Codex for [Moving WordPress](https://codex.wordpress.org/Moving_WordPress "Moving WordPress") to see if you missed any steps. It describes both moving a WordPress installation from one server to another, and moving it from one directory to another. It seems like you did both, so all those instructions would apply.
309,535
<pre><code>&lt;?php $args = array( 'post_type'=&gt;'weather_today', 'orderby'=&gt;'ID', 'order'=&gt;'ASC', 'posts_per_page'=&gt;1 ); $query = new WP_Query($args); if ($query-&gt;have_posts()) { while ( have_posts() ) : the_post(); the_content(); endwhile; } wp_reset_postdata(); ?&gt; </code></pre> <p>Outputs a post content (<code>the_content()</code>) that is not of a <code>weather_today</code> type. Why is this? I checked my SQL, in <code>wp_posts</code> I only have <em>one</em> post of <code>post_type = "weather_today"</code> and it's not the one being outputted. This query is up in my header... and I believe above any other custom queries. Furthermore, it seems the other params are respected, the post I am getting is only <code>1</code> and is that last <em>regular post</em> by <code>ID</code>. </p> <p>So why is the <code>post_type</code>, the most important param in this query, being ignored?</p>
[ { "answer_id": 309538, "author": "Community", "author_id": -1, "author_profile": "https://wordpress.stackexchange.com/users/-1", "pm_score": 3, "selected": true, "text": "<p>Try this </p>\n\n<pre><code>&lt;?php\n $args = array(\n 'post_type'=&gt;'weather_today',\n 'order...
2018/07/25
[ "https://wordpress.stackexchange.com/questions/309535", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/77764/" ]
``` <?php $args = array( 'post_type'=>'weather_today', 'orderby'=>'ID', 'order'=>'ASC', 'posts_per_page'=>1 ); $query = new WP_Query($args); if ($query->have_posts()) { while ( have_posts() ) : the_post(); the_content(); endwhile; } wp_reset_postdata(); ?> ``` Outputs a post content (`the_content()`) that is not of a `weather_today` type. Why is this? I checked my SQL, in `wp_posts` I only have *one* post of `post_type = "weather_today"` and it's not the one being outputted. This query is up in my header... and I believe above any other custom queries. Furthermore, it seems the other params are respected, the post I am getting is only `1` and is that last *regular post* by `ID`. So why is the `post_type`, the most important param in this query, being ignored?
Try this ``` <?php $args = array( 'post_type'=>'weather_today', 'orderby'=>'ID', 'order'=>'ASC', 'posts_per_page'=>1 ); $query = new WP_Query( $args ); while ( $query->have_posts() ) : $query->the_post(); //loop endwhile; wp_reset_postdata(); ?> ```
309,548
<p>I am using wordpress 4.9.7 and would like to add a custom taxonomy to my post-type.</p> <p>I have packed my code in a <code>mu-plugins</code> folder so that it is required by wordpress. Find below my code:</p> <pre><code>&lt;?php function computerBoxBuilder_post_types() { // Computer Hardware Post Type register_post_type('Computer-Hardware', array( 'supports' =&gt; array('title', 'editor', 'thumbnail', 'custom-fields'), 'public' =&gt; true, // 'exclude_from_search' =&gt; true, 'publicly_queryable' =&gt; true, 'show_ui' =&gt; true, 'labels' =&gt; array( 'name' =&gt; 'Computer-Hardware', 'add_new_item' =&gt; 'Add New Computer-Hardware', 'edit_item' =&gt; 'Edit Computer-Hardware', 'all_items' =&gt; 'All Computer-Hardware', 'singular_name' =&gt; 'Computer-Hardware', ), 'menu_icon' =&gt; 'dashicons-dashboard', 'taxonomies' =&gt; array( 'category' ), )); } // Register Custom Taxonomy function custom_taxonomy() { $labels = array( 'name' =&gt; _x( 'Hardware-Creators', 'Taxonomy General Name', 'text_domain' ), 'singular_name' =&gt; _x( 'Hardware-Creator', 'Taxonomy Singular Name', 'text_domain' ), 'menu_name' =&gt; __( 'Taxonomy', 'text_domain' ), 'all_items' =&gt; __( 'All Items', 'text_domain' ), 'parent_item' =&gt; __( 'Parent Item', 'text_domain' ), 'parent_item_colon' =&gt; __( 'Parent Item:', 'text_domain' ), 'new_item_name' =&gt; __( 'New Item Name', 'text_domain' ), 'add_new_item' =&gt; __( 'Add New Item', 'text_domain' ), 'edit_item' =&gt; __( 'Edit Item', 'text_domain' ), 'update_item' =&gt; __( 'Update Item', 'text_domain' ), 'view_item' =&gt; __( 'View Item', 'text_domain' ), 'separate_items_with_commas' =&gt; __( 'Separate items with commas', 'text_domain' ), 'add_or_remove_items' =&gt; __( 'Add or remove items', 'text_domain' ), 'choose_from_most_used' =&gt; __( 'Choose from the most used', 'text_domain' ), 'popular_items' =&gt; __( 'Popular Items', 'text_domain' ), 'search_items' =&gt; __( 'Search Items', 'text_domain' ), 'not_found' =&gt; __( 'Not Found', 'text_domain' ), 'no_terms' =&gt; __( 'No items', 'text_domain' ), 'items_list' =&gt; __( 'Items list', 'text_domain' ), 'items_list_navigation' =&gt; __( 'Items list navigation', 'text_domain' ), ); $args = array( 'labels' =&gt; $labels, 'hierarchical' =&gt; true, 'public' =&gt; true, 'show_ui' =&gt; true, 'show_admin_column' =&gt; true, 'show_in_nav_menus' =&gt; true, 'show_tagcloud' =&gt; true, ); register_taxonomy( 'Hardware-Creator', array( 'Computer-Hardware' ), $args ); } add_action('init', 'computerBoxBuilder_post_types'); add_action( 'init', 'custom_taxonomy', 2 ); </code></pre> <p>As you can see the taxonomy is not shown:</p> <p><a href="https://i.stack.imgur.com/KUQ0Y.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/KUQ0Y.png" alt="enter image description here" /></a></p> <p>Any suggestion what I am doing wrong?</p> <p>Appreciate your reply!</p>
[ { "answer_id": 309554, "author": "nmr", "author_id": 147428, "author_profile": "https://wordpress.stackexchange.com/users/147428", "pm_score": 1, "selected": false, "text": "<p>Try to change order of <code>add_action</code>:</p>\n\n<p><code>add_action( 'init', 'computerBoxBuilder_post_ty...
2018/07/25
[ "https://wordpress.stackexchange.com/questions/309548", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/48703/" ]
I am using wordpress 4.9.7 and would like to add a custom taxonomy to my post-type. I have packed my code in a `mu-plugins` folder so that it is required by wordpress. Find below my code: ``` <?php function computerBoxBuilder_post_types() { // Computer Hardware Post Type register_post_type('Computer-Hardware', array( 'supports' => array('title', 'editor', 'thumbnail', 'custom-fields'), 'public' => true, // 'exclude_from_search' => true, 'publicly_queryable' => true, 'show_ui' => true, 'labels' => array( 'name' => 'Computer-Hardware', 'add_new_item' => 'Add New Computer-Hardware', 'edit_item' => 'Edit Computer-Hardware', 'all_items' => 'All Computer-Hardware', 'singular_name' => 'Computer-Hardware', ), 'menu_icon' => 'dashicons-dashboard', 'taxonomies' => array( 'category' ), )); } // Register Custom Taxonomy function custom_taxonomy() { $labels = array( 'name' => _x( 'Hardware-Creators', 'Taxonomy General Name', 'text_domain' ), 'singular_name' => _x( 'Hardware-Creator', 'Taxonomy Singular Name', 'text_domain' ), 'menu_name' => __( 'Taxonomy', 'text_domain' ), 'all_items' => __( 'All Items', 'text_domain' ), 'parent_item' => __( 'Parent Item', 'text_domain' ), 'parent_item_colon' => __( 'Parent Item:', 'text_domain' ), 'new_item_name' => __( 'New Item Name', 'text_domain' ), 'add_new_item' => __( 'Add New Item', 'text_domain' ), 'edit_item' => __( 'Edit Item', 'text_domain' ), 'update_item' => __( 'Update Item', 'text_domain' ), 'view_item' => __( 'View Item', 'text_domain' ), 'separate_items_with_commas' => __( 'Separate items with commas', 'text_domain' ), 'add_or_remove_items' => __( 'Add or remove items', 'text_domain' ), 'choose_from_most_used' => __( 'Choose from the most used', 'text_domain' ), 'popular_items' => __( 'Popular Items', 'text_domain' ), 'search_items' => __( 'Search Items', 'text_domain' ), 'not_found' => __( 'Not Found', 'text_domain' ), 'no_terms' => __( 'No items', 'text_domain' ), 'items_list' => __( 'Items list', 'text_domain' ), 'items_list_navigation' => __( 'Items list navigation', 'text_domain' ), ); $args = array( 'labels' => $labels, 'hierarchical' => true, 'public' => true, 'show_ui' => true, 'show_admin_column' => true, 'show_in_nav_menus' => true, 'show_tagcloud' => true, ); register_taxonomy( 'Hardware-Creator', array( 'Computer-Hardware' ), $args ); } add_action('init', 'computerBoxBuilder_post_types'); add_action( 'init', 'custom_taxonomy', 2 ); ``` As you can see the taxonomy is not shown: [![enter image description here](https://i.stack.imgur.com/KUQ0Y.png)](https://i.stack.imgur.com/KUQ0Y.png) Any suggestion what I am doing wrong? Appreciate your reply!
Just change this line, it will display in admin ``` register_taxonomy( 'Hardware-Creator', array( 'Computer-Hardware' ), $args ); ``` to ``` register_taxonomy( 'Hardware-Creator', array( 'computer-hardware' ), $args ); ```
309,550
<p>I tried to make mysite.com/category page where I want to see list of categories. How to show list of categories I know. I can not make a link 'category'. I have tried to call this file 'archive-category.php', but site response 404. If I tried to call this file 'category.php' , then site route url mysite.com/category/info through template category.php, but url /category return me again 404. Please help me.</p>
[ { "answer_id": 309554, "author": "nmr", "author_id": 147428, "author_profile": "https://wordpress.stackexchange.com/users/147428", "pm_score": 1, "selected": false, "text": "<p>Try to change order of <code>add_action</code>:</p>\n\n<p><code>add_action( 'init', 'computerBoxBuilder_post_ty...
2018/07/25
[ "https://wordpress.stackexchange.com/questions/309550", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/147561/" ]
I tried to make mysite.com/category page where I want to see list of categories. How to show list of categories I know. I can not make a link 'category'. I have tried to call this file 'archive-category.php', but site response 404. If I tried to call this file 'category.php' , then site route url mysite.com/category/info through template category.php, but url /category return me again 404. Please help me.
Just change this line, it will display in admin ``` register_taxonomy( 'Hardware-Creator', array( 'Computer-Hardware' ), $args ); ``` to ``` register_taxonomy( 'Hardware-Creator', array( 'computer-hardware' ), $args ); ```
309,564
<p>I appreciate all help in advance. I am building a fairly customised website using Avada theme and BNE Flyouts.</p> <p>I need to be able to enable the Avada's Fusion Builder when editing flyouts, so it can be edited in drag and drop mode.</p> <p>I have tried enabling both for custom post types, but still when I go to edit the flyout, none of the wysiwyg editors show: <a href="https://www.screencast.com/t/5dQ5hdDew3a" rel="nofollow noreferrer">https://www.screencast.com/t/5dQ5hdDew3a</a></p> <p>I checked in the database and I am certain that flyouts are actually stored as posts: <a href="https://www.screencast.com/t/OMDsavM5o" rel="nofollow noreferrer">https://www.screencast.com/t/OMDsavM5o</a></p> <p>Question: - Is there a way to enable fusion builder on every editor window that I open, whatever is the post type - Can I force particular post type to open fusion builder on certain post type? How do I determine the post type name for functions.php?</p>
[ { "answer_id": 309554, "author": "nmr", "author_id": 147428, "author_profile": "https://wordpress.stackexchange.com/users/147428", "pm_score": 1, "selected": false, "text": "<p>Try to change order of <code>add_action</code>:</p>\n\n<p><code>add_action( 'init', 'computerBoxBuilder_post_ty...
2018/07/26
[ "https://wordpress.stackexchange.com/questions/309564", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/143166/" ]
I appreciate all help in advance. I am building a fairly customised website using Avada theme and BNE Flyouts. I need to be able to enable the Avada's Fusion Builder when editing flyouts, so it can be edited in drag and drop mode. I have tried enabling both for custom post types, but still when I go to edit the flyout, none of the wysiwyg editors show: <https://www.screencast.com/t/5dQ5hdDew3a> I checked in the database and I am certain that flyouts are actually stored as posts: <https://www.screencast.com/t/OMDsavM5o> Question: - Is there a way to enable fusion builder on every editor window that I open, whatever is the post type - Can I force particular post type to open fusion builder on certain post type? How do I determine the post type name for functions.php?
Just change this line, it will display in admin ``` register_taxonomy( 'Hardware-Creator', array( 'Computer-Hardware' ), $args ); ``` to ``` register_taxonomy( 'Hardware-Creator', array( 'computer-hardware' ), $args ); ```
309,610
<p>I created a custom template. It contains 3 columns, and the middle column should only display the post thumbnail. But no matter what size attribute I'm setting, it's not changing the size the way I want. I'd like the image to take over most of the space from that column.</p> <pre><code> &lt;div class="col-lg-4"&gt; .. first column with some content &lt;/div&gt;&lt;!-- col-lg-4 --&gt; &lt;div class="col-lg-4"&gt; &lt;?php //post_thumbnail if (!empty(get_the_post_thumbnail())) : ?&gt; &lt;?php the_post_thumbnail(array(360,466), array( 'class' =&gt; 'aligncenter')); endif; ?&gt; &lt;/div&gt;&lt;!-- col-lg-4 --&gt; &lt;div class="col-lg-4"&gt; third column with some content.. &lt;/div&gt;&lt;!-- col-lg-4 --&gt; </code></pre> <p>No matter what I put as a size (i also tried 'medium', 'full' etc.) it's remaining the same size as in the picture below: <a href="https://i.stack.imgur.com/4QDEU.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/4QDEU.png" alt="enter image description here"></a></p> <p>any ideas where my problem is?</p> <p><strong>EDIT</strong></p> <p>the same thing happens when I simply add </p> <pre><code>if (!empty(get_the_post_thumbnail())) : ?&gt; &lt;?php the_post_thumbnail(); endif; ?&gt; </code></pre> <p>or add any size (thumbnail, middle, large). It doesn't change anything..</p>
[ { "answer_id": 309554, "author": "nmr", "author_id": 147428, "author_profile": "https://wordpress.stackexchange.com/users/147428", "pm_score": 1, "selected": false, "text": "<p>Try to change order of <code>add_action</code>:</p>\n\n<p><code>add_action( 'init', 'computerBoxBuilder_post_ty...
2018/07/26
[ "https://wordpress.stackexchange.com/questions/309610", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/137532/" ]
I created a custom template. It contains 3 columns, and the middle column should only display the post thumbnail. But no matter what size attribute I'm setting, it's not changing the size the way I want. I'd like the image to take over most of the space from that column. ``` <div class="col-lg-4"> .. first column with some content </div><!-- col-lg-4 --> <div class="col-lg-4"> <?php //post_thumbnail if (!empty(get_the_post_thumbnail())) : ?> <?php the_post_thumbnail(array(360,466), array( 'class' => 'aligncenter')); endif; ?> </div><!-- col-lg-4 --> <div class="col-lg-4"> third column with some content.. </div><!-- col-lg-4 --> ``` No matter what I put as a size (i also tried 'medium', 'full' etc.) it's remaining the same size as in the picture below: [![enter image description here](https://i.stack.imgur.com/4QDEU.png)](https://i.stack.imgur.com/4QDEU.png) any ideas where my problem is? **EDIT** the same thing happens when I simply add ``` if (!empty(get_the_post_thumbnail())) : ?> <?php the_post_thumbnail(); endif; ?> ``` or add any size (thumbnail, middle, large). It doesn't change anything..
Just change this line, it will display in admin ``` register_taxonomy( 'Hardware-Creator', array( 'Computer-Hardware' ), $args ); ``` to ``` register_taxonomy( 'Hardware-Creator', array( 'computer-hardware' ), $args ); ```
309,647
<p>I want to add a filter to a form submission <a href="https://gravitywp.com/capitalize-fields-in-gravity-forms/" rel="nofollow noreferrer">like it is done here</a>.</p> <pre><code>add_action('gform_pre_submission_6', 'capitalize_fields_6'); function capitalize_fields_6($form){ // Code here } </code></pre> <p>My question is, how do you get the form ID on the WP admin side? Where is the number 6 coming from to access the form in the action? </p>
[ { "answer_id": 309648, "author": "Jacob Peattie", "author_id": 39152, "author_profile": "https://wordpress.stackexchange.com/users/39152", "pm_score": 3, "selected": true, "text": "<p>If you look at the list of Forms (Forms > Forms) in the back end there's a column that tells you the ID....
2018/07/26
[ "https://wordpress.stackexchange.com/questions/309647", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/145214/" ]
I want to add a filter to a form submission [like it is done here](https://gravitywp.com/capitalize-fields-in-gravity-forms/). ``` add_action('gform_pre_submission_6', 'capitalize_fields_6'); function capitalize_fields_6($form){ // Code here } ``` My question is, how do you get the form ID on the WP admin side? Where is the number 6 coming from to access the form in the action?
If you look at the list of Forms (Forms > Forms) in the back end there's a column that tells you the ID. You can also get it from the top of the screen when editing a form. Next to the form's Title there's an orange box that says "ID: 6".
309,652
<p>I'm trying to cutomise the TinyMce editor within WordPress and I took this code from an older WP site I did, but the buttons I have set don't seem to be working, for example, this is what I have:</p> <pre><code>add_filter( 'tiny_mce_before_init', 'blm_format_tiny_mce' ); function blm_format_tiny_mce( $in ) { $in['remove_linebreaks'] = true; $in['convert_newlines_to_brs'] = false; $in['keep_styles'] = true; $in['tabfocus_elements'] = 'major-publishing-actions'; $in['paste_remove_styles'] = false; $in['paste_remove_spans'] = true; $in['paste_strip_class_attributes'] = 'mso'; $in['paste_text_linebreaktype'] = 'combined'; $in['plugins'] = 'tabfocus,paste,media,fullscreen,wordpress,wpeditimage,wpgallery,wplink,wpdialogs'; $in['theme_advanced_buttons1'] = 'formatselect,forecolor,|,bold,italic,underline,|,bullist,numlist,blockquote,|,justifyleft,justifycenter,justifyright,justifyfull,|,link,unlink,|,wp_adv'; $in['theme_advanced_buttons2'] = 'pastetext,pasteword,selectall,removeformat,|,charmap,|,outdent,indent,|,undo,redo'; $in['theme_advanced_buttons3'] = ''; $in['theme_advanced_buttons4'] = ''; //$in['valid_children'] = '+div[p]'; return $in; } </code></pre> <p>Now, even though I have <code>bullist,numlist</code> listed, I don't see them on the editor; however I see <code>strikethrough</code> even though it's not listed.</p> <p>The only two other ones missing are <code>horizontal line</code> and <code>special character</code>; on top of that they don't show up in the order I put them, the order seems somewhat random.</p> <p>I'm happy to just not set the buttons, as with this site it's ok if everything is available, but I thought I needed to use it to insert the plugin buttons such as <code>pastetext,pasteword,selectall</code>?</p> <p>What am I doing wrong here?</p>
[ { "answer_id": 309648, "author": "Jacob Peattie", "author_id": 39152, "author_profile": "https://wordpress.stackexchange.com/users/39152", "pm_score": 3, "selected": true, "text": "<p>If you look at the list of Forms (Forms > Forms) in the back end there's a column that tells you the ID....
2018/07/26
[ "https://wordpress.stackexchange.com/questions/309652", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/1839/" ]
I'm trying to cutomise the TinyMce editor within WordPress and I took this code from an older WP site I did, but the buttons I have set don't seem to be working, for example, this is what I have: ``` add_filter( 'tiny_mce_before_init', 'blm_format_tiny_mce' ); function blm_format_tiny_mce( $in ) { $in['remove_linebreaks'] = true; $in['convert_newlines_to_brs'] = false; $in['keep_styles'] = true; $in['tabfocus_elements'] = 'major-publishing-actions'; $in['paste_remove_styles'] = false; $in['paste_remove_spans'] = true; $in['paste_strip_class_attributes'] = 'mso'; $in['paste_text_linebreaktype'] = 'combined'; $in['plugins'] = 'tabfocus,paste,media,fullscreen,wordpress,wpeditimage,wpgallery,wplink,wpdialogs'; $in['theme_advanced_buttons1'] = 'formatselect,forecolor,|,bold,italic,underline,|,bullist,numlist,blockquote,|,justifyleft,justifycenter,justifyright,justifyfull,|,link,unlink,|,wp_adv'; $in['theme_advanced_buttons2'] = 'pastetext,pasteword,selectall,removeformat,|,charmap,|,outdent,indent,|,undo,redo'; $in['theme_advanced_buttons3'] = ''; $in['theme_advanced_buttons4'] = ''; //$in['valid_children'] = '+div[p]'; return $in; } ``` Now, even though I have `bullist,numlist` listed, I don't see them on the editor; however I see `strikethrough` even though it's not listed. The only two other ones missing are `horizontal line` and `special character`; on top of that they don't show up in the order I put them, the order seems somewhat random. I'm happy to just not set the buttons, as with this site it's ok if everything is available, but I thought I needed to use it to insert the plugin buttons such as `pastetext,pasteword,selectall`? What am I doing wrong here?
If you look at the list of Forms (Forms > Forms) in the back end there's a column that tells you the ID. You can also get it from the top of the screen when editing a form. Next to the form's Title there's an orange box that says "ID: 6".
309,670
<p>When I add a new WP_Query, everything works, but if I add a 'tax_query' with a taxonomy, it doesn't pull the posts. post_count would always be 0.</p> <pre><code> $products = new WP_Query([ 'post_type' =&gt; 'post', 'tax_query' =&gt; [ [ 'taxonomy' =&gt; 'show_product_on_only_premium', 'field' =&gt; 'slug', 'terms' =&gt; 'yes', 'operator' =&gt; 'AND', ] ] ]); echo var_dump($products); </code></pre> <p>I've played with the tax_query with different values and I've had no luck. This works on production but not locally and I can't figure out why. edit> my database has the taxonomy </p> <p>Please help! Thank you in advance!</p>
[ { "answer_id": 309669, "author": "Tom J Nowell", "author_id": 736, "author_profile": "https://wordpress.stackexchange.com/users/736", "pm_score": 1, "selected": false, "text": "<p>Such a link does exist and is already in the admin menu:</p>\n\n<p><a href=\"https://i.stack.imgur.com/lSXwd...
2018/07/26
[ "https://wordpress.stackexchange.com/questions/309670", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/147639/" ]
When I add a new WP\_Query, everything works, but if I add a 'tax\_query' with a taxonomy, it doesn't pull the posts. post\_count would always be 0. ``` $products = new WP_Query([ 'post_type' => 'post', 'tax_query' => [ [ 'taxonomy' => 'show_product_on_only_premium', 'field' => 'slug', 'terms' => 'yes', 'operator' => 'AND', ] ] ]); echo var_dump($products); ``` I've played with the tax\_query with different values and I've had no luck. This works on production but not locally and I can't figure out why. edit> my database has the taxonomy Please help! Thank you in advance!
You can use this function `<?php get_edit_user_link( $user_id ) ?>` Read more: <https://codex.wordpress.org/Function_Reference/get_edit_user_link> Best regards,
309,697
<p>I've created a custom post type &amp; taxonomy, however when I go to my taxonomy page it throws a 404 error and I can't understand why.</p> <pre><code>// Register Custom Post Type function portfolio_post_type() { register_taxonomy_for_object_type('category','portfolio'); register_post_type( 'portfolio', array( 'labels' =&gt; array( 'name' =&gt; __('Portfolio'), 'singular_name' =&gt; __('Portfolio'), 'add_new' =&gt; __('Add new item'), 'add_new_item' =&gt; __('Add new item'), 'edit' =&gt; __('Edit'), 'edit_item' =&gt; __('Edit item'), 'new_item' =&gt; __('New item'), 'view' =&gt; __('View item'), 'view_item' =&gt; __('View item'), 'search_items' =&gt; __('Search portfolio'), 'not_found' =&gt; __('No portfolio items found'), 'not_found_in_trash' =&gt; __('No portfolio items found in trash'), ), 'public' =&gt; true, 'rewrite' =&gt; array('slug' =&gt; 'portfolio'), 'publicly_queryable' =&gt; true, 'hierarchical' =&gt; false, 'has_archive' =&gt; true, 'menu_icon' =&gt; 'dashicons-art', 'supports' =&gt; array('title', 'editor', 'excerpt', 'thumbnail', 'revisions','author'), 'can_export' =&gt; true, 'taxonomies' =&gt; array('portfolio-category'), ) ); } add_action( 'init', 'portfolio_post_type', 0 ); function portfolio_create_taxonomy() { register_taxonomy( 'portfolio-category', 'portfolio', array( 'label' =&gt; __( 'Category' ), 'rewrite' =&gt; array( 'slug' =&gt; 'category' ), 'hierarchical' =&gt; true, ) ); } add_action( 'init', 'portfolio_create_taxonomy' ); </code></pre> <p>When I click to view a taxonomy it takes me to <code>http://domain.local/category/all/</code></p> <p>However it throws the 404 page template.</p>
[ { "answer_id": 309669, "author": "Tom J Nowell", "author_id": 736, "author_profile": "https://wordpress.stackexchange.com/users/736", "pm_score": 1, "selected": false, "text": "<p>Such a link does exist and is already in the admin menu:</p>\n\n<p><a href=\"https://i.stack.imgur.com/lSXwd...
2018/07/27
[ "https://wordpress.stackexchange.com/questions/309697", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/115473/" ]
I've created a custom post type & taxonomy, however when I go to my taxonomy page it throws a 404 error and I can't understand why. ``` // Register Custom Post Type function portfolio_post_type() { register_taxonomy_for_object_type('category','portfolio'); register_post_type( 'portfolio', array( 'labels' => array( 'name' => __('Portfolio'), 'singular_name' => __('Portfolio'), 'add_new' => __('Add new item'), 'add_new_item' => __('Add new item'), 'edit' => __('Edit'), 'edit_item' => __('Edit item'), 'new_item' => __('New item'), 'view' => __('View item'), 'view_item' => __('View item'), 'search_items' => __('Search portfolio'), 'not_found' => __('No portfolio items found'), 'not_found_in_trash' => __('No portfolio items found in trash'), ), 'public' => true, 'rewrite' => array('slug' => 'portfolio'), 'publicly_queryable' => true, 'hierarchical' => false, 'has_archive' => true, 'menu_icon' => 'dashicons-art', 'supports' => array('title', 'editor', 'excerpt', 'thumbnail', 'revisions','author'), 'can_export' => true, 'taxonomies' => array('portfolio-category'), ) ); } add_action( 'init', 'portfolio_post_type', 0 ); function portfolio_create_taxonomy() { register_taxonomy( 'portfolio-category', 'portfolio', array( 'label' => __( 'Category' ), 'rewrite' => array( 'slug' => 'category' ), 'hierarchical' => true, ) ); } add_action( 'init', 'portfolio_create_taxonomy' ); ``` When I click to view a taxonomy it takes me to `http://domain.local/category/all/` However it throws the 404 page template.
You can use this function `<?php get_edit_user_link( $user_id ) ?>` Read more: <https://codex.wordpress.org/Function_Reference/get_edit_user_link> Best regards,
309,700
<p>Each field of the default Woocommerce form checkout has this markup: </p> <pre><code>&lt;p class="form-row form-row-first validate-required" id="billing_first_name_field" data-priority="10"&gt; &lt;label for="billing_first_name" class=""&gt;Name&amp;nbsp; &lt;abbr class="required" title="required"&gt;*&lt;/abbr&gt; &lt;/label&gt; &lt;span class="woocommerce-input-wrapper"&gt; &lt;input type="text" class="input-text " name="billing_first_name" id="billing_first_name" placeholder="" value="" autocomplete="given-name"&gt; &lt;/span&gt; &lt;/p&gt; </code></pre> <p>Now, I want:</p> <ol> <li>Wrap each field in a wrapper like <code>&lt;div class="single-field-wrapper"&gt;&lt;p [...] &lt;/div&gt;</code></li> <li>Wrap the first two fields, 'billing_first_name' and 'billing_last_name' in a wrapper like <code>&lt;div class="first-and-second-field-wrapper"&gt; [...] &lt;/div&gt;</code></li> </ol> <p>To achieve this, I've tried to use the filter hooks made available by <code>function woocommerce_form_field( $key, $args, $value = null )</code> called in <code>form-billing.php</code> template in this way:</p> <pre><code>&lt;?php $fields = $checkout-&gt;get_checkout_fields( 'billing' ); foreach ( $fields as $key =&gt; $field ) { if ( isset( $field['country_field'], $fields[ $field['country_field'] ] ) ) { $field['country'] = $checkout-&gt;get_value( $field['country_field'] ); } woocommerce_form_field( $key, $field, $checkout-&gt;get_value( $key ) ); } ?&gt; </code></pre> <p>So in <code>functions.php</code> I wrote:</p> <pre><code>function change_woocommerce_field_markup($field, $key, $args, $value){ $field = '&lt;div class="single-field-wrapper"&gt;'.$field.'&lt;/div&gt;'; if($key === 'billing_first_name') { $field = '&lt;div class="first-and-second-field-wrapper"&gt;'.$field; } else if ($key === 'billing_last_name') { $field = $field.'&lt;/div&gt;'; } else { $field = $field; } return $field; } add_filter("woocommerce_form_field","change_woocommerce_field_markup", 10, 4); </code></pre> <p>Unexpectedly, I get this markup:</p> <pre><code>&lt;div class="first-and-second-field-wrapper"&gt; &lt;div class="single-field-wrapper"&gt; &lt;div class="single-field-wrapper"&gt; [here there are all the fields, one under the other ] &lt;/div&gt; &lt;div class="single-field-wrapper"&gt;&lt;/div&gt; &lt;div class="single-field-wrapper"&gt;&lt;/div&gt; &lt;div class="single-field-wrapper"&gt;&lt;/div&gt; &lt;div class="single-field-wrapper"&gt;&lt;/div&gt; &lt;div class="single-field-wrapper"&gt;&lt;/div&gt; &lt;div class="single-field-wrapper"&gt;&lt;/div&gt; &lt;div class="single-field-wrapper"&gt;&lt;/div&gt; &lt;div class="single-field-wrapper"&gt;&lt;/div&gt; &lt;/div&gt; </code></pre> <p>Anyone can explain why this unexpected behavior?</p>
[ { "answer_id": 309788, "author": "nmr", "author_id": 147428, "author_profile": "https://wordpress.stackexchange.com/users/147428", "pm_score": 4, "selected": true, "text": "<p>There is no hook <code>woocommerce_form_field</code>, there is hook <code>woocommerce_form_field_{$args[type]}</...
2018/07/27
[ "https://wordpress.stackexchange.com/questions/309700", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/100514/" ]
Each field of the default Woocommerce form checkout has this markup: ``` <p class="form-row form-row-first validate-required" id="billing_first_name_field" data-priority="10"> <label for="billing_first_name" class="">Name&nbsp; <abbr class="required" title="required">*</abbr> </label> <span class="woocommerce-input-wrapper"> <input type="text" class="input-text " name="billing_first_name" id="billing_first_name" placeholder="" value="" autocomplete="given-name"> </span> </p> ``` Now, I want: 1. Wrap each field in a wrapper like `<div class="single-field-wrapper"><p [...] </div>` 2. Wrap the first two fields, 'billing\_first\_name' and 'billing\_last\_name' in a wrapper like `<div class="first-and-second-field-wrapper"> [...] </div>` To achieve this, I've tried to use the filter hooks made available by `function woocommerce_form_field( $key, $args, $value = null )` called in `form-billing.php` template in this way: ``` <?php $fields = $checkout->get_checkout_fields( 'billing' ); foreach ( $fields as $key => $field ) { if ( isset( $field['country_field'], $fields[ $field['country_field'] ] ) ) { $field['country'] = $checkout->get_value( $field['country_field'] ); } woocommerce_form_field( $key, $field, $checkout->get_value( $key ) ); } ?> ``` So in `functions.php` I wrote: ``` function change_woocommerce_field_markup($field, $key, $args, $value){ $field = '<div class="single-field-wrapper">'.$field.'</div>'; if($key === 'billing_first_name') { $field = '<div class="first-and-second-field-wrapper">'.$field; } else if ($key === 'billing_last_name') { $field = $field.'</div>'; } else { $field = $field; } return $field; } add_filter("woocommerce_form_field","change_woocommerce_field_markup", 10, 4); ``` Unexpectedly, I get this markup: ``` <div class="first-and-second-field-wrapper"> <div class="single-field-wrapper"> <div class="single-field-wrapper"> [here there are all the fields, one under the other ] </div> <div class="single-field-wrapper"></div> <div class="single-field-wrapper"></div> <div class="single-field-wrapper"></div> <div class="single-field-wrapper"></div> <div class="single-field-wrapper"></div> <div class="single-field-wrapper"></div> <div class="single-field-wrapper"></div> <div class="single-field-wrapper"></div> </div> ``` Anyone can explain why this unexpected behavior?
There is no hook `woocommerce_form_field`, there is hook `woocommerce_form_field_{$args[type]}` [(doc)](https://docs.woocommerce.com/wc-apidocs/hook-docs.html). `$args[type]` can be (look [here](https://docs.woocommerce.com/wc-apidocs/source-function-woocommerce_form_field.html#2147) for available options): * text, * checkbox, * country, * ... Code below will wrap '*billing\_first\_name*' and '*billing\_last\_name*' fields in a wrapper like `<div class="first-and-second-field-wrapper"> [...] </div>`. ``` function change_woocommerce_field_markup($field, $key, $args, $value) { $field = '<div class="single-field-wrapper">'.$field.'</div>'; if($key === 'billing_first_name') $field = '<div class="first-and-second-field-wrapper">'.$field; else if ($key === 'billing_last_name') $field = $field.'</div>'; return $field; } add_filter("woocommerce_form_field_text","change_woocommerce_field_markup", 10, 4); ``` It will also wrap `text` type fields with `<div class="single-field-wrapper">...</div>`. **BUT** some text fields that have own type (like state or email) require additional hooks, for example: ``` add_filter("woocommerce_form_field_country","change_woocommerce_field_markup", 10, 4); add_filter("woocommerce_form_field_email","change_woocommerce_field_markup", 10, 4); ``` --- **UPDATE #1** Above code works in WC-v3.3.7. In WC-v3.4.xx you get this: ``` <div class="first-and-second-field-wrapper"> <div class="single-field-wrapper"> <div class="single-field-wrapper"> [here there are all the fields, one under the other ] </div> <div class="single-field-wrapper"></div> <div class="single-field-wrapper"></div> <div class="single-field-wrapper"></div> .... <div class="single-field-wrapper"></div> </div> ``` because javascript sorts form rows inside `.woocommerce-billing-fields__field-wrapper`. Look at the file `woocommerce/assets/js/frontend/address-i18n.js`, from line 99. JS finds all HTML tags with ".form-row" class inside wrapper, takes parent of **first** item (tag with class `.form-row`), sort items by priority and insert them into **previously selected parent element**. For the test, change in file `address-i18.js`, in line 99 `var fieldsets = $('.woocommerce-billing-fields__field-wrapper, ...` to `var fieldsets = $('.woocommerce-billing-fields__field-wrapper2, ...` and upload as `address-i18.min.js`. **Removing JS sorting is not a solution, it is just a test.** Whithout sorting by JS you will get this: ``` <div class="first-and-second-field-wrapper"> <div class="single-field-wrapper"> <p class="form-row ..." id="billing_first_name_field"> <label for="billing_first_name"> ... </p> </div> <div class="single-field-wrapper"> <p class="form-row ..." id="billing_last_name_field"> <label for="billing_last_name">... </p> </div> </div> <div class="single-field-wrapper"> <p class="form-row ..." id="billing_company_field"> <label for="billing_company">... </p> </div> ```
309,706
<p>I have moved my wordpress from one hosting to other but it gives database error </p> <pre><code>Warning: mysqli_real_connect(): (28000/1045): Access denied for user 'user'@'localhost' (using password: YES) in /home/########/public_html/fvas/wp-includes/wp-db.php on line 1531 </code></pre> <p>I have change the database name in wp-config.php and user and password too but its always giving this error what should i try?</p>
[ { "answer_id": 309788, "author": "nmr", "author_id": 147428, "author_profile": "https://wordpress.stackexchange.com/users/147428", "pm_score": 4, "selected": true, "text": "<p>There is no hook <code>woocommerce_form_field</code>, there is hook <code>woocommerce_form_field_{$args[type]}</...
2018/07/27
[ "https://wordpress.stackexchange.com/questions/309706", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/140035/" ]
I have moved my wordpress from one hosting to other but it gives database error ``` Warning: mysqli_real_connect(): (28000/1045): Access denied for user 'user'@'localhost' (using password: YES) in /home/########/public_html/fvas/wp-includes/wp-db.php on line 1531 ``` I have change the database name in wp-config.php and user and password too but its always giving this error what should i try?
There is no hook `woocommerce_form_field`, there is hook `woocommerce_form_field_{$args[type]}` [(doc)](https://docs.woocommerce.com/wc-apidocs/hook-docs.html). `$args[type]` can be (look [here](https://docs.woocommerce.com/wc-apidocs/source-function-woocommerce_form_field.html#2147) for available options): * text, * checkbox, * country, * ... Code below will wrap '*billing\_first\_name*' and '*billing\_last\_name*' fields in a wrapper like `<div class="first-and-second-field-wrapper"> [...] </div>`. ``` function change_woocommerce_field_markup($field, $key, $args, $value) { $field = '<div class="single-field-wrapper">'.$field.'</div>'; if($key === 'billing_first_name') $field = '<div class="first-and-second-field-wrapper">'.$field; else if ($key === 'billing_last_name') $field = $field.'</div>'; return $field; } add_filter("woocommerce_form_field_text","change_woocommerce_field_markup", 10, 4); ``` It will also wrap `text` type fields with `<div class="single-field-wrapper">...</div>`. **BUT** some text fields that have own type (like state or email) require additional hooks, for example: ``` add_filter("woocommerce_form_field_country","change_woocommerce_field_markup", 10, 4); add_filter("woocommerce_form_field_email","change_woocommerce_field_markup", 10, 4); ``` --- **UPDATE #1** Above code works in WC-v3.3.7. In WC-v3.4.xx you get this: ``` <div class="first-and-second-field-wrapper"> <div class="single-field-wrapper"> <div class="single-field-wrapper"> [here there are all the fields, one under the other ] </div> <div class="single-field-wrapper"></div> <div class="single-field-wrapper"></div> <div class="single-field-wrapper"></div> .... <div class="single-field-wrapper"></div> </div> ``` because javascript sorts form rows inside `.woocommerce-billing-fields__field-wrapper`. Look at the file `woocommerce/assets/js/frontend/address-i18n.js`, from line 99. JS finds all HTML tags with ".form-row" class inside wrapper, takes parent of **first** item (tag with class `.form-row`), sort items by priority and insert them into **previously selected parent element**. For the test, change in file `address-i18.js`, in line 99 `var fieldsets = $('.woocommerce-billing-fields__field-wrapper, ...` to `var fieldsets = $('.woocommerce-billing-fields__field-wrapper2, ...` and upload as `address-i18.min.js`. **Removing JS sorting is not a solution, it is just a test.** Whithout sorting by JS you will get this: ``` <div class="first-and-second-field-wrapper"> <div class="single-field-wrapper"> <p class="form-row ..." id="billing_first_name_field"> <label for="billing_first_name"> ... </p> </div> <div class="single-field-wrapper"> <p class="form-row ..." id="billing_last_name_field"> <label for="billing_last_name">... </p> </div> </div> <div class="single-field-wrapper"> <p class="form-row ..." id="billing_company_field"> <label for="billing_company">... </p> </div> ```
309,727
<p>Here is the code which gives me only day and month.</p> <p>I want to show all: year, month, day, hour and minutes.</p> <p>How can I do this?</p> <pre><code>print '&lt;time class="entry-date updated" datetime="' . esc_attr( get_the_date( 'c' ) ) . '"&gt;' . esc_html( the_date('F j, Y','G:i')) . '&lt;/time&gt;'; </code></pre>
[ { "answer_id": 309728, "author": "Fayaz", "author_id": 110572, "author_profile": "https://wordpress.stackexchange.com/users/110572", "pm_score": 2, "selected": false, "text": "<h2>PHP Date Format in WordPress function:</h2>\n\n<p>You'll have to use the proper <a href=\"http://www.php.net...
2018/07/27
[ "https://wordpress.stackexchange.com/questions/309727", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/147675/" ]
Here is the code which gives me only day and month. I want to show all: year, month, day, hour and minutes. How can I do this? ``` print '<time class="entry-date updated" datetime="' . esc_attr( get_the_date( 'c' ) ) . '">' . esc_html( the_date('F j, Y','G:i')) . '</time>'; ```
PHP Date Format in WordPress function: -------------------------------------- You'll have to use the proper [`date format string`](http://www.php.net/manual/en/function.date.php) (as used in PHP `date` function) in the WordPress [`get_the_date()`](https://developer.wordpress.org/reference/functions/get_the_date/) function's first parameter. For example, to get the Date & Time in the format like `2018-07-23 23:59` (i.e. YYYY-MM-DD HH:MM, where hour is in 24 hour format), you need CODE like: ``` get_the_date('Y-m-d H:i'); ``` Or, to get the Date & Time in the format like `23-07-2018 11:59 PM` (i.e. YYYY-MM-DD HH:MM AM/PM, where hour is in 12 hour format with AM or PM), you need CODE like: ``` get_the_date('d-m-Y h:i A'); ``` So your full example CODE will be: ``` print '<time class="entry-date updated" datetime="' . esc_attr( get_the_date( 'c' ) ) . '">' . esc_html( get_the_date( 'd-m-Y h:i A' ) ) . '</time>'; ``` Mistakes in your CODE: ---------------------- The ***idea*** in your CODE is not entirely wrong, only the CODE has two mistakes: 1. You've used the `the_date` function, instead of `get_the_date` function. The way you've concatenated the string, `the_date` will not work as it prints the date immediately, doesn't return as the `get_the_date` function does. 2. You've used `'F j, Y', 'G:i'` as two parameters, where as, it should be just one parameter: `'F j, Y G:i'`. So if you correct these two mistakes, the proper CODE will be: ``` print '<time class="entry-date updated" datetime="' . esc_attr( get_the_date( 'c' ) ) . '">' . esc_html( get_the_date( 'F j, Y G:i' ) ) . '</time>'; ``` --- Further Reading: ---------------- There are many other possibilities and all are in the `Date Format` string as described in [PHP `date` function documentation](http://www.php.net/manual/en/function.date.php). There are some useful examples in [WordPress Codex](https://codex.wordpress.org/Formatting_Date_and_Time) as well.
309,735
<p>I have created a WP loop to display Services from 'Services' Custom Post Type: </p> <p><strong>Here is the code:</strong></p> <pre><code>&lt;?php $services_loop = new WP_Query( array( 'post_type' =&gt; 'service', 'posts_per_page' =&gt; -1 ) ); if ( $services_loop-&gt;have_posts() ) : while ( $services_loop-&gt;have_posts() ) : $services_loop-&gt;the_post(); ?&gt; &lt;section class="single-service"&gt; &lt;div class="container"&gt; &lt;div class="row"&gt; &lt;div class="col-md-6"&gt; &lt;?php the_post_thumbnail('full', array('class' =&gt; 'img-fluid w-100', 'alt' =&gt; get_the_title(), 'title' =&gt; get_the_title())); ?&gt; &lt;/div&gt; &lt;div class="col-md-6"&gt; &lt;h3&gt;&lt;?php the_title(); ?&gt;&lt;/h3&gt; &lt;?php the_content(); ?&gt;&lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;/section&gt; &lt;?php endwhile; endif; wp_reset_postdata(); ?&gt; </code></pre> <p>It display the list of services. But what I want is, I want to have a custom section within middle of the loop and I am not finding any solution for this. Here I will visualize my problem. </p> <p><a href="https://i.stack.imgur.com/DXbw5.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/DXbw5.png" alt="enter image description here"></a></p>
[ { "answer_id": 309728, "author": "Fayaz", "author_id": 110572, "author_profile": "https://wordpress.stackexchange.com/users/110572", "pm_score": 2, "selected": false, "text": "<h2>PHP Date Format in WordPress function:</h2>\n\n<p>You'll have to use the proper <a href=\"http://www.php.net...
2018/07/27
[ "https://wordpress.stackexchange.com/questions/309735", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/137372/" ]
I have created a WP loop to display Services from 'Services' Custom Post Type: **Here is the code:** ``` <?php $services_loop = new WP_Query( array( 'post_type' => 'service', 'posts_per_page' => -1 ) ); if ( $services_loop->have_posts() ) : while ( $services_loop->have_posts() ) : $services_loop->the_post(); ?> <section class="single-service"> <div class="container"> <div class="row"> <div class="col-md-6"> <?php the_post_thumbnail('full', array('class' => 'img-fluid w-100', 'alt' => get_the_title(), 'title' => get_the_title())); ?> </div> <div class="col-md-6"> <h3><?php the_title(); ?></h3> <?php the_content(); ?></div> </div> </div> </div> </section> <?php endwhile; endif; wp_reset_postdata(); ?> ``` It display the list of services. But what I want is, I want to have a custom section within middle of the loop and I am not finding any solution for this. Here I will visualize my problem. [![enter image description here](https://i.stack.imgur.com/DXbw5.png)](https://i.stack.imgur.com/DXbw5.png)
PHP Date Format in WordPress function: -------------------------------------- You'll have to use the proper [`date format string`](http://www.php.net/manual/en/function.date.php) (as used in PHP `date` function) in the WordPress [`get_the_date()`](https://developer.wordpress.org/reference/functions/get_the_date/) function's first parameter. For example, to get the Date & Time in the format like `2018-07-23 23:59` (i.e. YYYY-MM-DD HH:MM, where hour is in 24 hour format), you need CODE like: ``` get_the_date('Y-m-d H:i'); ``` Or, to get the Date & Time in the format like `23-07-2018 11:59 PM` (i.e. YYYY-MM-DD HH:MM AM/PM, where hour is in 12 hour format with AM or PM), you need CODE like: ``` get_the_date('d-m-Y h:i A'); ``` So your full example CODE will be: ``` print '<time class="entry-date updated" datetime="' . esc_attr( get_the_date( 'c' ) ) . '">' . esc_html( get_the_date( 'd-m-Y h:i A' ) ) . '</time>'; ``` Mistakes in your CODE: ---------------------- The ***idea*** in your CODE is not entirely wrong, only the CODE has two mistakes: 1. You've used the `the_date` function, instead of `get_the_date` function. The way you've concatenated the string, `the_date` will not work as it prints the date immediately, doesn't return as the `get_the_date` function does. 2. You've used `'F j, Y', 'G:i'` as two parameters, where as, it should be just one parameter: `'F j, Y G:i'`. So if you correct these two mistakes, the proper CODE will be: ``` print '<time class="entry-date updated" datetime="' . esc_attr( get_the_date( 'c' ) ) . '">' . esc_html( get_the_date( 'F j, Y G:i' ) ) . '</time>'; ``` --- Further Reading: ---------------- There are many other possibilities and all are in the `Date Format` string as described in [PHP `date` function documentation](http://www.php.net/manual/en/function.date.php). There are some useful examples in [WordPress Codex](https://codex.wordpress.org/Formatting_Date_and_Time) as well.
309,736
<p>I have a div and inside I wish display by random a post from category-a or a product from category-b. I'm looking for a query to do that.</p> <p>I tried this: </p> <pre><code> &lt;?php $args = array( 'post_type' =&gt; array('product', 'post'), 'posts_per_page' =&gt; 1, 'cat' =&gt; 1,2, 'orderby' =&gt; 'RAND' ); $loop = new WP_Query( $args ); while ( $loop-&gt;have_posts() ) : $loop-&gt;the_post(); global $product; ?&gt; &lt;article class="promo"&gt; &lt;div class="image"&gt; &lt;?php if (is_singular('product')){ echo 'Product'; }else{ echo 'Post'; }?&gt; &lt;/div&gt; &lt;/article&gt; &lt;?php endwhile; ?&gt; </code></pre> <p>Someone knows how to do that ? thank you :)</p> <p><strong>EDIT CODE</strong> </p> <pre><code> &lt;?php $args = [ 'post_type' =&gt; ['product','post'], 'posts_per_page' =&gt; -1, 'fields' =&gt; 'ids', 'post_type' =&gt; ['product','post'], 'posts_per_page' =&gt; 2, 'fields' =&gt; 'ids', 'tax_query' =&gt; [ 'relation' =&gt; 'OR', 'taxonomy' =&gt; 'category', 'field' =&gt; 'slug', 'terms' =&gt; ['promo-distributeur', 'actu-distrib'], 'include_children' =&gt; false, ] ] ]; $posts_ids = get_posts($args); $total = count($posts_ids); if ($total &gt; 0) { $rnd = mt_rand(0, $total); $pid = $posts_ids[$rnd]; $post = get_post( $pid); while ( $post-&gt;have_posts() ) : $post&gt;the_post(); global $product; ?&gt; &lt;article class="promo"&gt; &lt;div class="image"&gt; &lt;?php if (is_singular('product')){ echo 'Product'; }else{ echo 'Post'; }?&gt; &lt;/div&gt; &lt;/article&gt; &lt;?php endwhile; } ?&gt; </code></pre>
[ { "answer_id": 309747, "author": "Andrea Somovigo", "author_id": 64435, "author_profile": "https://wordpress.stackexchange.com/users/64435", "pm_score": -1, "selected": false, "text": "<p>you don't need global $product, and is_singular() is a template function, not usable in the loop, al...
2018/07/27
[ "https://wordpress.stackexchange.com/questions/309736", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/141407/" ]
I have a div and inside I wish display by random a post from category-a or a product from category-b. I'm looking for a query to do that. I tried this: ``` <?php $args = array( 'post_type' => array('product', 'post'), 'posts_per_page' => 1, 'cat' => 1,2, 'orderby' => 'RAND' ); $loop = new WP_Query( $args ); while ( $loop->have_posts() ) : $loop->the_post(); global $product; ?> <article class="promo"> <div class="image"> <?php if (is_singular('product')){ echo 'Product'; }else{ echo 'Post'; }?> </div> </article> <?php endwhile; ?> ``` Someone knows how to do that ? thank you :) **EDIT CODE** ``` <?php $args = [ 'post_type' => ['product','post'], 'posts_per_page' => -1, 'fields' => 'ids', 'post_type' => ['product','post'], 'posts_per_page' => 2, 'fields' => 'ids', 'tax_query' => [ 'relation' => 'OR', 'taxonomy' => 'category', 'field' => 'slug', 'terms' => ['promo-distributeur', 'actu-distrib'], 'include_children' => false, ] ] ]; $posts_ids = get_posts($args); $total = count($posts_ids); if ($total > 0) { $rnd = mt_rand(0, $total); $pid = $posts_ids[$rnd]; $post = get_post( $pid); while ( $post->have_posts() ) : $post>the_post(); global $product; ?> <article class="promo"> <div class="image"> <?php if (is_singular('product')){ echo 'Product'; }else{ echo 'Post'; }?> </div> </article> <?php endwhile; } ?> ```
The following code selects IDs of all posts type `product` and `post`, which belong to terms `category-a` or `category-b`, with `taxonomy_01` and `taxonomy_02`, respectively. ``` $args = [ 'post_type' => ['product','post'], 'posts_per_page' => -1, 'fields' => 'ids', 'tax_query' => [ 'relation' => 'OR', [ 'taxonomy' => 'taxonomy_01', 'field' => 'slug', 'terms' => 'category-a', 'include_children' => false, ], [ 'taxonomy' => 'taxonomy_02', 'field' => 'slug', 'terms' => 'category-b', // OR by id //'field' => 'term_id', // default value //'terms' => 2, 'include_children' => false, ], ] ]; $posts_ids = get_posts($args); $total = count($posts_ids); if ($total > 0) { $rnd = mt_rand(0, $total - 1); $pid = $posts_ids[$rnd]; $my_post = get_post( $pid); // display post } ``` I assume that the terms `category-a`, `category-b` belongs to different taxonomies. If not, then the `tax_query` should be: ``` 'tax_query' => [ [ 'taxonomy' => 'taxonomy_01', 'field' => 'slug', 'terms' => ['category-a', 'category-b'], 'include_children' => false, ], ] ``` **UPDATE** I changed variable in the above code from `$post` to `my_post`. Your code: ``` $args = [ 'post_type' => ['product','post'], 'posts_per_page' => -1, 'fields' => 'ids', 'tax_query' => [ 'relation' => 'OR', [ 'taxonomy' => 'taxonomy_01', 'field' => 'slug', 'terms' => 'category-a', 'include_children' => false, ], [ 'taxonomy' => 'taxonomy_02', 'field' => 'slug', 'terms' => 'category-b', // OR by id //'field' => 'term_id', // default value //'terms' => 2, 'include_children' => false, ], ] ]; $posts_ids = get_posts($args); $total = count($posts_ids); if ($total > 0) { // get random post_ID $rnd = mt_rand(0, $total - 1); $pid = $posts_ids[$rnd]; $my_post = get_post( $pid); // display post if ( !empty($my_post) ) : ?> <article class="promo"> <div class="image"> <?php if ( $my_post->post_type == 'product' ) echo 'Product'; else echo 'Post'; ?> </div> </article> <?php endif; } ```
309,748
<p>In my contact form I need a drop down for order quantities. On selection of "other", I want to display a number field for input. Below is my code but it's not working. Can anyone help? Thanks in advance.</p> <pre><code>&lt;script language="javascript" type="text/javascript"&gt; document.getElementById("OrderQuantity").addEventListener("change", displayNumberField); function displayNumberField() { var dropDownText = document.getElementById("OrderQuantity").value; if (dropDownText == "Other") { document.getElementById("EnterOtherQuantity").style.display = 'block'; } else { document.getElementById("EnterOtherQuantity").style.display = 'none'; } } &lt;/script&gt; &lt;label&gt; Order Quantity [select* drop-down-menu id=OrderQuantity "Select Quantity" "10" "20" "30" "40" "Other"] &lt;/label&gt; &lt;label id="EnterOtherQuantity" style="display:none;"&gt; Please Specify Your Order Quantity [number other-order-quantity min:41] &lt;/label&gt; </code></pre>
[ { "answer_id": 309769, "author": "Andrea Somovigo", "author_id": 64435, "author_profile": "https://wordpress.stackexchange.com/users/64435", "pm_score": 0, "selected": false, "text": "<p>Note that <strong>[select* drop-down-menu id=\"OrderQuantity\"]</strong> CF7 shortcode will not outpu...
2018/07/27
[ "https://wordpress.stackexchange.com/questions/309748", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/147684/" ]
In my contact form I need a drop down for order quantities. On selection of "other", I want to display a number field for input. Below is my code but it's not working. Can anyone help? Thanks in advance. ``` <script language="javascript" type="text/javascript"> document.getElementById("OrderQuantity").addEventListener("change", displayNumberField); function displayNumberField() { var dropDownText = document.getElementById("OrderQuantity").value; if (dropDownText == "Other") { document.getElementById("EnterOtherQuantity").style.display = 'block'; } else { document.getElementById("EnterOtherQuantity").style.display = 'none'; } } </script> <label> Order Quantity [select* drop-down-menu id=OrderQuantity "Select Quantity" "10" "20" "30" "40" "Other"] </label> <label id="EnterOtherQuantity" style="display:none;"> Please Specify Your Order Quantity [number other-order-quantity min:41] </label> ```
You can try this add-on to make conditional fields. <https://nl.wordpress.org/plugins/cf7-conditional-fields/>
309,754
<p>With the latest version of WordPress, how can we publish revisions of a post, in addition to showing the latest post? </p> <p>I want my front end users to see multiple versions of the same post. The same post is going to change "some" of its content every friday. All weekly versions will then be compared by non-administrators (ie managers and directors) at some point every month. </p> <p>My goal is to make it as easy as possible for a public user to review revisions.</p> <p>There doesn't appear to be a plugin concept for this. Can I modify the internal revisions tool to accomplish something like this?</p> <p>Many thanks!</p>
[ { "answer_id": 309761, "author": "Martin Jarvis", "author_id": 147693, "author_profile": "https://wordpress.stackexchange.com/users/147693", "pm_score": 0, "selected": false, "text": "<p>That's an interesting idea. There are, of course, manual ways to do it - e.g. cloning the post, makin...
2018/07/27
[ "https://wordpress.stackexchange.com/questions/309754", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/98671/" ]
With the latest version of WordPress, how can we publish revisions of a post, in addition to showing the latest post? I want my front end users to see multiple versions of the same post. The same post is going to change "some" of its content every friday. All weekly versions will then be compared by non-administrators (ie managers and directors) at some point every month. My goal is to make it as easy as possible for a public user to review revisions. There doesn't appear to be a plugin concept for this. Can I modify the internal revisions tool to accomplish something like this? Many thanks!
**I suggest you look at** <https://codex.wordpress.org/Function_Reference/wp_get_post_revisions> ``` <?php // Lets get the revisions of the given $post we are accessing by ID ( you are probably going to want to limit your internal revision count for this $revisions = wp_get_post_revisions($post->ID); // lets just do some formatting here ( your post html content is going to display normally but lets get the var_dump to look decent echo '<pre>'; // print the $revisions variable to look at the internals var_dump($revisions); echo '</pre>'; // from here i would dig into iterating over the revisions array. ?> ``` using the above code inside your loop should get your started to see what kind of data you can return from wp\_get\_post\_revisions(). You are going to need to do some searching on the post\_date portion or look at the array key and sort by the integer and push to a custom array where key matches count() to return only the most recent post revision. This query will be huge so i sincerely suggest you limit your wordpress installs revision count.
309,780
<p>I'm having a problem with a custom function. This function counts the post and assigns a number to that post. It then saves the number to a custom field and then updates the permalink to the post.</p> <p>My problems are:</p> <p>1). When a post is saved, it saves a post twice (Shows up as 2 revisions). I'm trying to find a way so that it saves it once.</p> <p>2). I'm also trying to find a way for the function to work only once. I'm noticing that previous posts are getting edited and while they are staying the same, they do show up with lots of revisions. For example: If I have 5 posts, the first post will show up with 10 revisions.</p> <p>Here's my code:</p> <pre><code>// opens a function function updateNumbers( $post_id ){ // sets global global $pagenow; // if current page is a new post and in the post CPT if ($pagenow == 'post.php' &amp;&amp; 'post' == get_post_type()) { // counts all posts global $wpdb; $querystr = "SELECT $wpdb-&gt;posts.* FROM $wpdb-&gt;posts WHERE $wpdb-&gt;posts.post_status = 'publish' AND $wpdb-&gt;posts.post_type = 'post' "; $pageposts = $wpdb-&gt;get_results($querystr, OBJECT); $counts = 0 ; if ($pageposts): foreach ($pageposts as $post): $counts++; // saves the number to a custom field add_post_meta($post-&gt;ID, 'incr_number', $counts, true); remove_action('save_post', 'updateNumbers'); wp_update_post(array('ID' =&gt; $post-&gt;ID,'post_name' =&gt; get_post_meta($post-&gt;ID,'incr_number', true))); endforeach; endif; }} // close the function and save add_action('save_post', 'updateNumbers'); </code></pre>
[ { "answer_id": 309786, "author": "Andrius Vlasovas", "author_id": 147625, "author_profile": "https://wordpress.stackexchange.com/users/147625", "pm_score": 2, "selected": false, "text": "<p>Always lean back on WordPress Codex.</p>\n\n<p>In this case, you are using 'save_post' action hook...
2018/07/28
[ "https://wordpress.stackexchange.com/questions/309780", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/8049/" ]
I'm having a problem with a custom function. This function counts the post and assigns a number to that post. It then saves the number to a custom field and then updates the permalink to the post. My problems are: 1). When a post is saved, it saves a post twice (Shows up as 2 revisions). I'm trying to find a way so that it saves it once. 2). I'm also trying to find a way for the function to work only once. I'm noticing that previous posts are getting edited and while they are staying the same, they do show up with lots of revisions. For example: If I have 5 posts, the first post will show up with 10 revisions. Here's my code: ``` // opens a function function updateNumbers( $post_id ){ // sets global global $pagenow; // if current page is a new post and in the post CPT if ($pagenow == 'post.php' && 'post' == get_post_type()) { // counts all posts global $wpdb; $querystr = "SELECT $wpdb->posts.* FROM $wpdb->posts WHERE $wpdb->posts.post_status = 'publish' AND $wpdb->posts.post_type = 'post' "; $pageposts = $wpdb->get_results($querystr, OBJECT); $counts = 0 ; if ($pageposts): foreach ($pageposts as $post): $counts++; // saves the number to a custom field add_post_meta($post->ID, 'incr_number', $counts, true); remove_action('save_post', 'updateNumbers'); wp_update_post(array('ID' => $post->ID,'post_name' => get_post_meta($post->ID,'incr_number', true))); endforeach; endif; }} // close the function and save add_action('save_post', 'updateNumbers'); ```
It duplicate because when you run the `wp_update_post()`, it will use the `wp_insert_post()` function and the action `save_post` will run again. please use the filter `wp_insert_post_data` to filter the value before save. <https://codex.wordpress.org/Plugin_API/Filter_Reference/wp_insert_post_data> Example: ``` function wpse309780_filter_post_data($data , $postarr) { $data['post_name'] = wp_count_posts( 'post' )->publish; return $data; } add_filter( 'wp_insert_post_data', 'wpse309780_filter_post_data' ); ```
309,806
<p>I'm trying to disable all functionality related to pingbacks/trackbacks in WordPress and so far I have this:</p> <pre><code>add_action( 'pre_ping', 'disable_pingback' ); function disable_pingback( &amp;$links ) { foreach ( $links as $l =&gt; $link ) { if ( 0 === strpos( $link, get_option( 'home' ) ) ) { unset( $links[ $l ] ); } } } </code></pre> <p>However when I open up the page options and enable <em>discussion</em>, I still see this:</p> <p><a href="https://i.stack.imgur.com/CLug6.png" rel="noreferrer"><img src="https://i.stack.imgur.com/CLug6.png" alt="enter image description here"></a></p> <p>I found this <a href="https://wordpress.stackexchange.com/a/103511/1839">answer</a> (method 2), but it is over 5 years old now and I wasn't sure if totally replacing the whole section was the best way to do things compatibility wise, so I am asking again...</p> <p>Is there a <em>cleaner</em> way to accomplish this?</p>
[ { "answer_id": 309809, "author": "Rick Hellewell", "author_id": 29416, "author_profile": "https://wordpress.stackexchange.com/users/29416", "pm_score": 0, "selected": false, "text": "<p>Your code is correct, AFAIK. It will disable the ability to do trackback/pings. It doesn't remove that...
2018/07/28
[ "https://wordpress.stackexchange.com/questions/309806", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/1839/" ]
I'm trying to disable all functionality related to pingbacks/trackbacks in WordPress and so far I have this: ``` add_action( 'pre_ping', 'disable_pingback' ); function disable_pingback( &$links ) { foreach ( $links as $l => $link ) { if ( 0 === strpos( $link, get_option( 'home' ) ) ) { unset( $links[ $l ] ); } } } ``` However when I open up the page options and enable *discussion*, I still see this: [![enter image description here](https://i.stack.imgur.com/CLug6.png)](https://i.stack.imgur.com/CLug6.png) I found this [answer](https://wordpress.stackexchange.com/a/103511/1839) (method 2), but it is over 5 years old now and I wasn't sure if totally replacing the whole section was the best way to do things compatibility wise, so I am asking again... Is there a *cleaner* way to accomplish this?
The WordPress Codex solutions weren't working for me regardless of what parameters I used or the priorities set, probably because my setup is pretty complex or as others have commented. The first chunk of code may work for you but I don't have a default environment at the moment to test. The second chunk of code definitely worked for me. The last chunk of code removes the option from the post's quick edit as well. You will still need to disable the functionality as you have done. Wordpress Codex solution, *(hooks into add\_meta\_boxes so it fires last, but you can use admin\_menu or do\_meta\_boxes instead).* Documentation [Here](https://codex.wordpress.org/Function_Reference/remove_meta_box) ``` function remove_trackbacks_pingbacks() { remove_meta_box('trackbacksdiv', 'post', 'normal'); } add_action('add_meta_boxes', 'remove_trackbacks_pingbacks'); ``` This may be overkill, but this is what actually worked for me. Note that it will remove the option in the box from displaying everywhere, including pages too. It also allows you to customize the HTML as well just in case you wanted to add a note to tell the user that Pingbacks and Trackbacks have been disabled. *(this may or may not suit your needs, but here it is anyway).* Documentation [Here](https://gist.github.com/eteubert/1327291) ``` function remove_trackbacks_pingbacks ($post_type, $post) { global $wp_meta_boxes, $current_screen; # Remove "ping_status" from `commentstatusdiv`: $wp_meta_boxes[$current_screen->id]['normal']['core']['commentstatusdiv']['callback'] = function($post) { ?> <input name="advanced_view" type="hidden" value="1"> <p class="meta-options"> <label for="comment_status" class="selectit"> <input id="comment_status" name="comment_status" type="checkbox" value="open" <?php checked($post->comment_status, 'open'); ?>> Allow comments? </label> <?php do_action('post_comment_status_meta_box-options', $post); ?> </p> <?php }; } add_action('add_meta_boxes', 'remove_trackbacks_pingbacks', 10, 2); ``` Lastly, since you want to remove the option from your edit screen, I assume you may want to remove from the quick edit screen as well. There are no hooks or classes to hook into that I know of, so a pure jQuery solution is in order. Insert into functions.php Modified from this solution [Here](https://wordpress.stackexchange.com/questions/59871/remove-specific-items-from-quick-edit-menu-of-a-custom-post-type) ``` add_action( 'admin_head-edit.php', 'remove_pings_quickedit' ); function remove_pings_quickedit() { global $current_screen; if( 'edit-post' != $current_screen->id ) return; ?> <script type="text/javascript"> jQuery(document).ready( function($) { $('span:contains("Allow Pings")').each(function (i) { $(this).remove(); }); $('input[name=ping_status]').each(function (i) { $(this).remove(); }); }); </script> <?php } ```
309,828
<p>Question regarding template structure: </p> <p>In a custom loop, I inserted a get_template_part('resources', 'layout') which contains the following markup:</p> <pre><code>&lt;div class="custom-content"&gt; &lt;?php if ( get_post_type() === 'videos' ) { ?&gt; &lt;div class="video-popup"&gt; &lt;?php the_field('video_popup'); ?&gt; &lt;/div&gt; &lt;?php } else { ?&gt; &lt;div class="featured-image"&gt; &lt;?php the_post_thumbnail('full'); ?&gt; &lt;?php if ( get_post_type() === 'articles' ) { ?&gt; &lt;p class="custom-content-btn"&gt; &lt;a href="&lt;?php the_field( 'article_link' )?&gt;" class="btn btn-primary" target="_blank"&gt;&lt;?php echo __('READ'); ?&gt;&lt;/a&gt; &lt;/p&gt; &lt;?php } ?&gt; &lt;/div&gt; &lt;?php if ( get_post_type() === 'audio' ) { ?&gt; &lt;div class="audio-content"&gt; &lt;?php the_field('audio_clip'); ?&gt; &lt;/div&gt; &lt;?php } ?&gt; &lt;?php } ?&gt; &lt;/div&gt; </code></pre> <p>I have 3 CPT (videos, audio and articles). However I'm not sure if this is the best way to conditionally display the contents; seems a bit messy. I guess the tricky part is that there's some markup that appears for all CPT, that's sitting inbetween those conditional markups.</p> <p>What would be considered the 'best practice' to tackle this? Appreciate any input!</p>
[ { "answer_id": 309809, "author": "Rick Hellewell", "author_id": 29416, "author_profile": "https://wordpress.stackexchange.com/users/29416", "pm_score": 0, "selected": false, "text": "<p>Your code is correct, AFAIK. It will disable the ability to do trackback/pings. It doesn't remove that...
2018/07/29
[ "https://wordpress.stackexchange.com/questions/309828", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/146256/" ]
Question regarding template structure: In a custom loop, I inserted a get\_template\_part('resources', 'layout') which contains the following markup: ``` <div class="custom-content"> <?php if ( get_post_type() === 'videos' ) { ?> <div class="video-popup"> <?php the_field('video_popup'); ?> </div> <?php } else { ?> <div class="featured-image"> <?php the_post_thumbnail('full'); ?> <?php if ( get_post_type() === 'articles' ) { ?> <p class="custom-content-btn"> <a href="<?php the_field( 'article_link' )?>" class="btn btn-primary" target="_blank"><?php echo __('READ'); ?></a> </p> <?php } ?> </div> <?php if ( get_post_type() === 'audio' ) { ?> <div class="audio-content"> <?php the_field('audio_clip'); ?> </div> <?php } ?> <?php } ?> </div> ``` I have 3 CPT (videos, audio and articles). However I'm not sure if this is the best way to conditionally display the contents; seems a bit messy. I guess the tricky part is that there's some markup that appears for all CPT, that's sitting inbetween those conditional markups. What would be considered the 'best practice' to tackle this? Appreciate any input!
The WordPress Codex solutions weren't working for me regardless of what parameters I used or the priorities set, probably because my setup is pretty complex or as others have commented. The first chunk of code may work for you but I don't have a default environment at the moment to test. The second chunk of code definitely worked for me. The last chunk of code removes the option from the post's quick edit as well. You will still need to disable the functionality as you have done. Wordpress Codex solution, *(hooks into add\_meta\_boxes so it fires last, but you can use admin\_menu or do\_meta\_boxes instead).* Documentation [Here](https://codex.wordpress.org/Function_Reference/remove_meta_box) ``` function remove_trackbacks_pingbacks() { remove_meta_box('trackbacksdiv', 'post', 'normal'); } add_action('add_meta_boxes', 'remove_trackbacks_pingbacks'); ``` This may be overkill, but this is what actually worked for me. Note that it will remove the option in the box from displaying everywhere, including pages too. It also allows you to customize the HTML as well just in case you wanted to add a note to tell the user that Pingbacks and Trackbacks have been disabled. *(this may or may not suit your needs, but here it is anyway).* Documentation [Here](https://gist.github.com/eteubert/1327291) ``` function remove_trackbacks_pingbacks ($post_type, $post) { global $wp_meta_boxes, $current_screen; # Remove "ping_status" from `commentstatusdiv`: $wp_meta_boxes[$current_screen->id]['normal']['core']['commentstatusdiv']['callback'] = function($post) { ?> <input name="advanced_view" type="hidden" value="1"> <p class="meta-options"> <label for="comment_status" class="selectit"> <input id="comment_status" name="comment_status" type="checkbox" value="open" <?php checked($post->comment_status, 'open'); ?>> Allow comments? </label> <?php do_action('post_comment_status_meta_box-options', $post); ?> </p> <?php }; } add_action('add_meta_boxes', 'remove_trackbacks_pingbacks', 10, 2); ``` Lastly, since you want to remove the option from your edit screen, I assume you may want to remove from the quick edit screen as well. There are no hooks or classes to hook into that I know of, so a pure jQuery solution is in order. Insert into functions.php Modified from this solution [Here](https://wordpress.stackexchange.com/questions/59871/remove-specific-items-from-quick-edit-menu-of-a-custom-post-type) ``` add_action( 'admin_head-edit.php', 'remove_pings_quickedit' ); function remove_pings_quickedit() { global $current_screen; if( 'edit-post' != $current_screen->id ) return; ?> <script type="text/javascript"> jQuery(document).ready( function($) { $('span:contains("Allow Pings")').each(function (i) { $(this).remove(); }); $('input[name=ping_status]').each(function (i) { $(this).remove(); }); }); </script> <?php } ```
309,840
<p>Hope someone can help, am looking for some suggestions on how to override/replace some functions that are loading in a parent theme and move them into the child theme so we can make alterations to the files themselves in the child theme.</p> <p>We will "duplicate" the structure and files into the child theme, but can't yet find a way to "unload" the original parent theme files and then load the child theme files we want to alter instead.</p> <p>Essentially it's all the "require" files listed below that we will duplicate and alter in the child theme, but need to find some way to override the parents functions.php.</p> <p>We have tried multiple ways to do this but just can't seem to get it to work so far.</p> <p>THIS IS THE CURRENT PARENT FUNCTIONS.PHP:</p> <hr> <pre><code>&lt;?php /** * moto functions and definitions * * @package moto */ if ( ! function_exists( 'moto_setup' ) ) : /** * Sets up theme defaults and registers support for various WordPress features. * * Note that this function is hooked into the after_setup_theme hook, which * runs before the init hook. The init hook is too late for some features, such * as indicating support for post thumbnails. */ function moto_setup() { /* * Make theme available for translation. * Translations can be filed in the /languages/ directory. * If you're building a theme based on moto, use a find and replace * to change 'moto' to the name of your theme in all the template files */ load_theme_textdomain( 'moto', get_template_directory() . '/languages' ); // Add default posts and comments RSS feed links to head. add_theme_support( 'automatic-feed-links' ); /* * Let WordPress manage the document title. * By adding theme support, we declare that this theme does not use a * hard-coded &lt;title&gt; tag in the document head, and expect WordPress to * provide it for us. */ add_theme_support( 'title-tag' ); /* * Enable support for Post Thumbnails on posts and pages. * * @link http://codex.wordpress.org/Function_Reference/add_theme_support#Post_Thumbnails */ add_theme_support( 'post-thumbnails' ); // This theme uses wp_nav_menu() in one location. register_nav_menus( array( 'primary' =&gt; esc_html__( 'MOTO Main Menu', 'moto' ), 'pre_header' =&gt; esc_html__( 'Preheader Menu(You have to enable Preheader from MOTO Options panel to view this menu.)', 'moto' ) ) ); /* * Switch default core markup for search form, comment form, and comments * to output valid HTML5. */ add_theme_support( 'html5', array( 'search-form', 'comment-form', 'comment-list', 'gallery', 'caption', ) ); /* * Enable support for Post Formats. * See http://codex.wordpress.org/Post_Formats */ add_theme_support( 'post-formats', array( 'aside', 'image', 'video', 'quote', 'link', ) ); // Set up the WordPress core custom background feature. add_theme_support( 'custom-background', apply_filters( 'moto_custom_background_args', array( 'default-color' =&gt; 'ffffff', 'default-image' =&gt; '', ) ) ); add_theme_support( 'woocommerce' ); global $pagenow; if ( is_admin() &amp;&amp; 'themes.php' == $pagenow &amp;&amp; isset( $_GET['activated'] ) ) { wp_redirect(admin_url("options-general.php?page=moto-system-status")); // Your admin page URL exit(); } } endif; // moto_setup add_action( 'after_setup_theme', 'moto_setup' ); /** * Set the content width in pixels, based on the theme's design and stylesheet. * * Priority 0 to make it available to lower priority callbacks. * * @global int $content_width */ function moto_content_width() { $GLOBALS['content_width'] = apply_filters( 'moto_content_width', 640 ); } add_action( 'after_setup_theme', 'moto_content_width', 0 ); /** * Register widget area. * * @link http://codex.wordpress.org/Function_Reference/register_sidebar */ function moto_widgets_init() { register_sidebar( array( 'name' =&gt; esc_html__( 'Sidebar', 'moto' ), 'id' =&gt; 'sidebar-1', 'description' =&gt; esc_html__( 'Defualt Sidebar', 'moto' ), 'before_widget' =&gt; '&lt;div id="%1$s" class="row no-margin widget %2$s"&gt;', 'after_widget' =&gt; '&lt;/div&gt;', 'before_title' =&gt; '&lt;hr&gt;&lt;h4&gt;', 'after_title' =&gt; '&lt;/h4&gt;', ) ); register_sidebar( array( 'name' =&gt; esc_html__( 'Shop Sidebar', 'moto' ), 'id' =&gt; 'shopsidebar', 'description' =&gt; esc_html__( 'Shop Sidebar Show Only Shop pages', 'moto' ), 'before_widget' =&gt; '&lt;div id="%1$s" class="row no-margin widget %2$s"&gt;', 'after_widget' =&gt; '&lt;/div&gt;', 'before_title' =&gt; '&lt;hr&gt;&lt;h4&gt;', 'after_title' =&gt; '&lt;/h4&gt;', ) ); register_sidebar( array( 'name' =&gt; esc_html__( 'Footer Sidebar - 1', 'moto' ), 'id' =&gt; 'footer-1', 'description' =&gt; esc_html__( 'Footer Sidebar - 1', 'moto' ), 'before_widget' =&gt; '&lt;div class="col-md-3 col-sm-6 text-left"&gt;', 'after_widget' =&gt; '&lt;/div&gt;', 'before_title' =&gt; '&lt;hr&gt;&lt;h4&gt;', 'after_title' =&gt; '&lt;/h4&gt;', ) ); register_sidebar( array( 'name' =&gt; esc_html__( 'Footer Sidebar - 2', 'moto' ), 'id' =&gt; 'footer-2', 'description' =&gt; esc_html__( 'Footer Sidebar - 2', 'moto' ), 'before_widget' =&gt; '&lt;div class="col-md-3 col-sm-6 text-left"&gt;&lt;div class="mt_footer_content"&gt;', 'after_widget' =&gt; '&lt;/div&gt;&lt;/div&gt;', 'before_title' =&gt; '&lt;hr&gt;&lt;h4&gt;', 'after_title' =&gt; '&lt;/h4&gt;', ) ); } add_action( 'widgets_init', 'moto_widgets_init' ); /** * Implement the Custom Header feature. */ require get_template_directory() . '/function/custom-header.php'; /** * Custom template tags for this theme. */ require get_template_directory() . '/function/template-tags.php'; /** * Custom functions that act independently of the theme templates. */ require get_template_directory() . '/function/extras.php'; /** * Customizer additions. */ require get_template_directory() . '/function/customizer.php'; /** * Load Jetpack compatibility file. */ require get_template_directory() . '/function/jetpack.php'; require_once get_template_directory() . '/include/aq_resizer.php'; require_once get_template_directory() . '/include/moto-sys-req.php'; require_once get_template_directory() . '/include/moto-enqueue.php'; require_once get_template_directory() . '/include/moto-functions.php'; require_once get_template_directory() . '/include/theme_plugin/plugin-activate-config.php'; require_once get_template_directory() . '/include/wordpress-reset.php'; </code></pre> <hr> <p>Any suggestions?</p> <p>Thank you in advance.</p>
[ { "answer_id": 309842, "author": "Pim", "author_id": 50432, "author_profile": "https://wordpress.stackexchange.com/users/50432", "pm_score": 0, "selected": false, "text": "<p>Simply use</p>\n\n<pre><code>function moto_setup() { \n // Your new moto_setup function\n}\n</code></pre>\n\n<p>...
2018/07/29
[ "https://wordpress.stackexchange.com/questions/309840", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/147731/" ]
Hope someone can help, am looking for some suggestions on how to override/replace some functions that are loading in a parent theme and move them into the child theme so we can make alterations to the files themselves in the child theme. We will "duplicate" the structure and files into the child theme, but can't yet find a way to "unload" the original parent theme files and then load the child theme files we want to alter instead. Essentially it's all the "require" files listed below that we will duplicate and alter in the child theme, but need to find some way to override the parents functions.php. We have tried multiple ways to do this but just can't seem to get it to work so far. THIS IS THE CURRENT PARENT FUNCTIONS.PHP: --- ``` <?php /** * moto functions and definitions * * @package moto */ if ( ! function_exists( 'moto_setup' ) ) : /** * Sets up theme defaults and registers support for various WordPress features. * * Note that this function is hooked into the after_setup_theme hook, which * runs before the init hook. The init hook is too late for some features, such * as indicating support for post thumbnails. */ function moto_setup() { /* * Make theme available for translation. * Translations can be filed in the /languages/ directory. * If you're building a theme based on moto, use a find and replace * to change 'moto' to the name of your theme in all the template files */ load_theme_textdomain( 'moto', get_template_directory() . '/languages' ); // Add default posts and comments RSS feed links to head. add_theme_support( 'automatic-feed-links' ); /* * Let WordPress manage the document title. * By adding theme support, we declare that this theme does not use a * hard-coded <title> tag in the document head, and expect WordPress to * provide it for us. */ add_theme_support( 'title-tag' ); /* * Enable support for Post Thumbnails on posts and pages. * * @link http://codex.wordpress.org/Function_Reference/add_theme_support#Post_Thumbnails */ add_theme_support( 'post-thumbnails' ); // This theme uses wp_nav_menu() in one location. register_nav_menus( array( 'primary' => esc_html__( 'MOTO Main Menu', 'moto' ), 'pre_header' => esc_html__( 'Preheader Menu(You have to enable Preheader from MOTO Options panel to view this menu.)', 'moto' ) ) ); /* * Switch default core markup for search form, comment form, and comments * to output valid HTML5. */ add_theme_support( 'html5', array( 'search-form', 'comment-form', 'comment-list', 'gallery', 'caption', ) ); /* * Enable support for Post Formats. * See http://codex.wordpress.org/Post_Formats */ add_theme_support( 'post-formats', array( 'aside', 'image', 'video', 'quote', 'link', ) ); // Set up the WordPress core custom background feature. add_theme_support( 'custom-background', apply_filters( 'moto_custom_background_args', array( 'default-color' => 'ffffff', 'default-image' => '', ) ) ); add_theme_support( 'woocommerce' ); global $pagenow; if ( is_admin() && 'themes.php' == $pagenow && isset( $_GET['activated'] ) ) { wp_redirect(admin_url("options-general.php?page=moto-system-status")); // Your admin page URL exit(); } } endif; // moto_setup add_action( 'after_setup_theme', 'moto_setup' ); /** * Set the content width in pixels, based on the theme's design and stylesheet. * * Priority 0 to make it available to lower priority callbacks. * * @global int $content_width */ function moto_content_width() { $GLOBALS['content_width'] = apply_filters( 'moto_content_width', 640 ); } add_action( 'after_setup_theme', 'moto_content_width', 0 ); /** * Register widget area. * * @link http://codex.wordpress.org/Function_Reference/register_sidebar */ function moto_widgets_init() { register_sidebar( array( 'name' => esc_html__( 'Sidebar', 'moto' ), 'id' => 'sidebar-1', 'description' => esc_html__( 'Defualt Sidebar', 'moto' ), 'before_widget' => '<div id="%1$s" class="row no-margin widget %2$s">', 'after_widget' => '</div>', 'before_title' => '<hr><h4>', 'after_title' => '</h4>', ) ); register_sidebar( array( 'name' => esc_html__( 'Shop Sidebar', 'moto' ), 'id' => 'shopsidebar', 'description' => esc_html__( 'Shop Sidebar Show Only Shop pages', 'moto' ), 'before_widget' => '<div id="%1$s" class="row no-margin widget %2$s">', 'after_widget' => '</div>', 'before_title' => '<hr><h4>', 'after_title' => '</h4>', ) ); register_sidebar( array( 'name' => esc_html__( 'Footer Sidebar - 1', 'moto' ), 'id' => 'footer-1', 'description' => esc_html__( 'Footer Sidebar - 1', 'moto' ), 'before_widget' => '<div class="col-md-3 col-sm-6 text-left">', 'after_widget' => '</div>', 'before_title' => '<hr><h4>', 'after_title' => '</h4>', ) ); register_sidebar( array( 'name' => esc_html__( 'Footer Sidebar - 2', 'moto' ), 'id' => 'footer-2', 'description' => esc_html__( 'Footer Sidebar - 2', 'moto' ), 'before_widget' => '<div class="col-md-3 col-sm-6 text-left"><div class="mt_footer_content">', 'after_widget' => '</div></div>', 'before_title' => '<hr><h4>', 'after_title' => '</h4>', ) ); } add_action( 'widgets_init', 'moto_widgets_init' ); /** * Implement the Custom Header feature. */ require get_template_directory() . '/function/custom-header.php'; /** * Custom template tags for this theme. */ require get_template_directory() . '/function/template-tags.php'; /** * Custom functions that act independently of the theme templates. */ require get_template_directory() . '/function/extras.php'; /** * Customizer additions. */ require get_template_directory() . '/function/customizer.php'; /** * Load Jetpack compatibility file. */ require get_template_directory() . '/function/jetpack.php'; require_once get_template_directory() . '/include/aq_resizer.php'; require_once get_template_directory() . '/include/moto-sys-req.php'; require_once get_template_directory() . '/include/moto-enqueue.php'; require_once get_template_directory() . '/include/moto-functions.php'; require_once get_template_directory() . '/include/theme_plugin/plugin-activate-config.php'; require_once get_template_directory() . '/include/wordpress-reset.php'; ``` --- Any suggestions? Thank you in advance.
You can't necessarily replace entire arbitrary files with a child theme. WordPress will automatically look in the child theme for replacements for the templates in the [template hierarchy](https://developer.wordpress.org/themes/basics/template-hierarchy/), as well as a couple of additional files like searchform.php or comments.php, but any other files that the parent theme loads are only replaceable in a child theme if the parent theme author has built them to be. This includes any files included into functions.php or in templates. For a file to be replaceable by a child theme it must be loaded using supported functions. For example, if a theme (like yours) loads a file like this: ``` require_once get_template_directory() . '/include/aq_resizer.php'; ``` Then a child theme *cannot* replace it. This is because the `'/include/aq_resizer.php'` part of the path is not going through WordPress at all. It's a normal PHP include that WordPress cannot intercept. Additionally, `get_template_directory()` will only ever be the directory to the parent theme, not the child theme if one is active. For it to be possible to replace an entire file in a child theme the parent theme must load it with one of these functions: ``` require_once get_theme_file_path( '/include/aq_resizer.php' ); ``` Because the file path is passed as an argument to `get_theme_file_path()`, rather than just being a concatenated string passed directly to PHP, it's possible for the function to look in the child theme first, which it does. For templates, if the parent theme uses `get_template_part()`, like this: ``` get_template_part( 'partials/content' ); ``` Then the child theme can create `partials/content.php` to replace it, but if the parent theme uses `include partials/content.php`, then it's not possible to replace with a child theme. `get_theme_file_path()` is much newer (introduced in **4.7**) than `get_template_part()` (introduced in **3.0**), so is much less common, and non-existent in older themes. It's also not widely known. In your code the parent theme doesn't use either of these methods, so it's just not possible to replace the entire file. This means that you will need to replace individual functions one-by-one. The method for doing this will depend on how the function is used. **If the parent theme hooks the function with `add_action()`** If the parent theme hooks the function you want to replace with `add_action()`, then you can replace the function by creating a new version of the function in your child theme (with a different name), unhooking the original function with [`remove_action()`](https://developer.wordpress.org/reference/functions/remove_action/), then hooking your new function with [`add_action()`](https://developer.wordpress.org/reference/functions/add_action/): ``` remove_action( 'hook_name', 'parent_theme_function_name' ); add_action( 'hook_name', 'child_theme_function_name' ); ``` **If the parent theme uses the function in a template file** If the parent theme has a function you want to replace, and that function is used in a template file, then you will need to create a new version of the function in your child theme (with a different name) then replace the *template file* in your child theme, then in your child theme's version of the template replace the original function usage with your new function. **If the parent theme function is pluggable** Parent themes are loaded before the child theme. This means that it's possible for theme developers to make functions replaceable by child themes by wrapping then in a `function_exists()` check. This means that you can replace the function definition with your own function and it won't cause a conflict, because the parent theme won't try to re-define it if you already have. Your code has an example of this: the `moto_setup()` function is inside this check: ``` if ( ! function_exists( 'moto_setup' ) ) : endif; ``` This makes the `moto_setup()` function 'pluggable', which means that you can define a `moto_setup()` function in your child theme and the parent theme will use it instead. Whether or not other functions in your theme are 'pluggable' this way is impossible to say without seeing the code. **Conclusion** * It's not necessarily possible to replace whole files in child themes. Outside of a handful of core WordPress templates, the parent theme has to explicitly support files being replaceable. * If the theme has not made functions' files replaceable, there are several options for replacing functions depending on how the parent theme was constructed. * Depending on how the parent theme was constructed it is entirely possible that there are parts of it that are impossible to replace with a child theme without replacing huge chunks of the theme that you otherwise don't want to change. This can reach a point where you're better off just forking the theme and creating a new one.
309,849
<p>I am able to get a list of its subcategories in a category archive page using below code in <code>archive-product.php</code> but I want to display the list of the products currently assigned to each subcategory.</p> <pre><code>&lt;?php $parentid = get_queried_object_id(); $args = array( 'parent' =&gt; $parentid ); $categories = get_terms( 'product_cat', $args ); if ( $categories ) { foreach ( $categories as $category ) { echo $category-&gt;name; } } ?&gt; </code></pre> <p><strong>Example:</strong></p> <p>Subcategory 1</p> <ul> <li>Product 1 of Subcategory 1</li> <li>Product 2 of Subcategory 1</li> </ul> <p><hr> Subcategory 2</p> <ul> <li>Product 1 of Subcategory 2</li> <li>Product 2 of Subcategory 2</li> </ul> <p>I am still learning WordPress so any help will be highly appreciated.</p>
[ { "answer_id": 309859, "author": "Krzysiek Dróżdż", "author_id": 34172, "author_profile": "https://wordpress.stackexchange.com/users/34172", "pm_score": 2, "selected": true, "text": "<pre><code>&lt;?php\n $parentid = get_queried_object_id();\n $args = array(\n 'parent' =&gt;...
2018/07/29
[ "https://wordpress.stackexchange.com/questions/309849", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/147735/" ]
I am able to get a list of its subcategories in a category archive page using below code in `archive-product.php` but I want to display the list of the products currently assigned to each subcategory. ``` <?php $parentid = get_queried_object_id(); $args = array( 'parent' => $parentid ); $categories = get_terms( 'product_cat', $args ); if ( $categories ) { foreach ( $categories as $category ) { echo $category->name; } } ?> ``` **Example:** Subcategory 1 * Product 1 of Subcategory 1 * Product 2 of Subcategory 1 --- Subcategory 2 * Product 1 of Subcategory 2 * Product 2 of Subcategory 2 I am still learning WordPress so any help will be highly appreciated.
``` <?php $parentid = get_queried_object_id(); $args = array( 'parent' => $parentid ); $categories = get_terms( 'product_cat', $args ); if ( $categories ) : foreach ( $categories as $category ) : echo esc_html($category->name); $products = new WP_Query( array( 'post_type' => 'product', 'tax_query' => array( array( 'taxonomy' => 'product_cat', 'field' => 'slug', 'terms' => $category->slug, ), ) ) ); if ( $products->have_posts() ) : ?> <ul> <?php while ( $products->have_posts() ) : $products->the_post(); ?> <li><?php the_title(); ?></li> <?php endwhile; ?> </ul> <?php wp_reset_postdata(); endif; endforeach; endif; ?> ```
309,862
<p>How can I check if the editor that is currently being used is Gutenberg in a WordPress plugin?</p> <p>I need this because Gutenberg lacks <code>post_submitbox_misc_actions</code>, so I need a fallback which will only be used if the current editor is Gutenberg.</p>
[ { "answer_id": 309955, "author": "Fayaz", "author_id": 110572, "author_profile": "https://wordpress.stackexchange.com/users/110572", "pm_score": 4, "selected": false, "text": "<h2>Necessary API Functions/Methods:</h2>\n<p>You'll need <a href=\"https://developer.wordpress.org/reference/cl...
2018/07/29
[ "https://wordpress.stackexchange.com/questions/309862", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/123649/" ]
How can I check if the editor that is currently being used is Gutenberg in a WordPress plugin? I need this because Gutenberg lacks `post_submitbox_misc_actions`, so I need a fallback which will only be used if the current editor is Gutenberg.
Necessary API Functions/Methods: -------------------------------- You'll need [`WP_Screen::is_block_editor()`](https://developer.wordpress.org/reference/classes/wp_screen/is_block_editor/) method to check if you are currently in the Gutenberg Editor (Since WordPress 5.0). Also, if you install Gutenberg as a separate plugin, then you'll have the `is_gutenberg_page()` function available to do the same check. So for an overall solution, you'll need to combine these two. Of course, this has to be checked from the admin panel pages and when the internal data is ready to call the function. So **you'll have to do the check using a suitable hook**. For example, *if you check this using **`init`** hook, it **will not work***. Gutenberg itself checks the `is_gutenberg_page()` function from `gutenberg_init()` function, which is loaded using `replace_editor` hook. So `replace_editor` hook is a good place to do this check. However, I'd suggest the use of `admin_enqueue_scripts` for making the check, since: 1. `admin_enqueue_scripts` is the first hook that is fired after the same `is_gutenberg_page()` check Gutenberg makes itself. 2. Because of the nature of Gutenberg, you're more likely to load external scripts / styles for your purpose. 3. `admin_enqueue_scripts` is a well known hook and it's only fired from admin panel pages. So front end is not affected by it. > > Having said that, **if all you need is to enqueue some scripts/styles**, then you may use [`enqueue_block_editor_assets`](https://developer.wordpress.org/reference/hooks/enqueue_block_editor_assets/) hook for editor assets and [`enqueue_block_assets`](https://developer.wordpress.org/reference/hooks/enqueue_block_assets/) hook for both the editor and frontend assets (since WordPress 5.0). > > > I'm not providing the related CODE here as it wasn't directly asked in the question, but it may be enough for most purposes. > > > Solution: --------- > > Sample CODE for Gutenberg check > > > ``` add_action( 'admin_enqueue_scripts', 'wpse_gutenberg_editor_action' ); function wpse_is_gutenberg_editor() { if( function_exists( 'is_gutenberg_page' ) && is_gutenberg_page() ) { return true; } $current_screen = get_current_screen(); if ( method_exists( $current_screen, 'is_block_editor' ) && $current_screen->is_block_editor() ) { return true; } return false; } function wpse_gutenberg_editor_action() { if( wpse_is_gutenberg_editor() ) { // your gutenberg editor related CODE here } else { // this is not gutenberg. // this may not even be an editor, you need to check the screen if you need to check for another editor. } } ```
309,883
<p>Say I have a plugin which fires the <code>plugin_1_action</code> when it initializes.</p> <p>Now, because I wanna extend that plugin, I'll hook into <code>plugin_1_action</code>, but what if my plugin was installed after that plugin? Won't that plugin run first and so, I'll lose the chance to catch the <code>plugin_1_action</code> hook?</p> <p>It's just weird and magical to me that I can, no matter what, hook into, say, Woo's actions and Woo can hook into mine, even if clearly my plugin has been installed later than it.</p> <p>Even if most plugins run on the <code>init</code> hook (so they get executed on the same space), they still have priorities set differently. Meaning that plugin1's code will run before plugin2's code and if plugin2 has a hook into plugin1, well, tough luck...or not, apparently WordPress doesn't have this issue.</p> <p>How does it work?</p>
[ { "answer_id": 309884, "author": "Jacob Peattie", "author_id": 39152, "author_profile": "https://wordpress.stackexchange.com/users/39152", "pm_score": 2, "selected": false, "text": "<p>If the plugin indeed runs <code>plugin_1_action</code> <em>as soon as it's loaded</em>, meaning that th...
2018/07/30
[ "https://wordpress.stackexchange.com/questions/309883", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/143406/" ]
Say I have a plugin which fires the `plugin_1_action` when it initializes. Now, because I wanna extend that plugin, I'll hook into `plugin_1_action`, but what if my plugin was installed after that plugin? Won't that plugin run first and so, I'll lose the chance to catch the `plugin_1_action` hook? It's just weird and magical to me that I can, no matter what, hook into, say, Woo's actions and Woo can hook into mine, even if clearly my plugin has been installed later than it. Even if most plugins run on the `init` hook (so they get executed on the same space), they still have priorities set differently. Meaning that plugin1's code will run before plugin2's code and if plugin2 has a hook into plugin1, well, tough luck...or not, apparently WordPress doesn't have this issue. How does it work?
If the plugin indeed runs `plugin_1_action` *as soon as it's loaded*, meaning that the `do_action()` call is just sitting in the plugin file and not inside a function that's hooked later, then yes, you're correct: you won't be able to hook into it if your plugin is loaded later. This is almost never how plugins work though. Pretty much all plugins won't actually run any code as soon as they're loaded. Plugins will typically hook all their functionality to occur later, usually no earlier than the `init` hook, which is run after all plugins and themes have loaded. So let's say the original plugin has this code: ``` function og_plugin_initialize() { // Does stuff. do_action( 'og_plugin_initialized' ); } ``` This code will probably be hooked to run on the `init` hook: ``` add_action( 'init', 'og_plugin_initialize', 20 ); ``` So the `og_plugin_initialized` hook won't be executed until the `init` hook, at priority 20. If you had a function that you wanted to hook into the `og_plugin_initialized` hook, then you would add it in your plugin like this: ``` function my_plugin_init() { // Do stuff. } add_action( 'og_plugin_initialized', 'my_plugin_init' ); ``` When it's done like this it doesn't matter which order the plugins load in, because both plugins and queued up their functions to run later. And since both those functions will run after all plugins have loaded, you can use functions defined in the original plugin without issue.
309,896
<p>How can i echo product id and product_item_key of each cart item instead of total count ?</p> <pre><code>function iconic_cart_count_fragments( $fragments ) { $fragments['div.header-cart-count'] = '&lt;div class="header-cart-count"&gt;' . WC()-&gt;cart-&gt;get_cart_contents_count() . '&lt;/div&gt;'; return $fragments; } </code></pre> <p>Thank You</p>
[ { "answer_id": 309905, "author": "Techno Deviser", "author_id": 146401, "author_profile": "https://wordpress.stackexchange.com/users/146401", "pm_score": 1, "selected": false, "text": "<p>Try something like this</p>\n\n<pre><code>global $woocommerce;\nforeach ( $woocommerce-&gt;cart-&gt;...
2018/07/30
[ "https://wordpress.stackexchange.com/questions/309896", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/147754/" ]
How can i echo product id and product\_item\_key of each cart item instead of total count ? ``` function iconic_cart_count_fragments( $fragments ) { $fragments['div.header-cart-count'] = '<div class="header-cart-count">' . WC()->cart->get_cart_contents_count() . '</div>'; return $fragments; } ``` Thank You
Techno Deviser, probably by mistake, in the `foreach` loop set value to `$fragments['div.header-cart-count']` instead append it. Try this modification: ``` function iconic_cart_count_fragments( $fragments ) { foreach ( WC()->cart->get_cart() as $cart_item_key => $cart_item ) { $fragments['div.header-cart-count'] .= '<div class="header-cart-count">' .$cart_item_key.'<br><br>'. $cart_item['product_id']. '</div>'; } return $fragments; } ``` Or: ``` function iconic_cart_count_fragments( $fragments ) { $cart = WC()->cart->get_cart(); if (!empty($cart)) { foreach ( $cart as $cart_item_key => $cart_item ) $output .= $cart_item_key. ' - ' . $cart_item['product_id'] . '<br>'; $fragments['div.header-cart-count'] = '<div class="header-cart-count">' . $output . '</div>'; } return $fragments; } ```
309,907
<p>I'm fairly new to Wordpress. I'm using the shop-isle theme that has a default navigation menu. I'm trying to override this with a fancy ‘Ubermenu’ plugin but the default collapse symbol keeps overriding the plugin. </p> <p>The theme header is loaded from directory shop-isle/inc/structure/header.php. </p> <p>I copied the entire directory to my child theme directory and made edit below in /header.php but it only works when I add it to the 'structure' folder in the parent theme NOT the child. </p> <p>example 1</p> <pre><code>&lt;?php if( function_exists( ‘ubermenu’ ) ): ?&gt; &lt;?php ubermenu( 'main' , array( 'theme_location' =&gt; 'primary' ) ); ?&gt; &lt;?php else: ?&gt; &lt;div class="header-menu-wrap"&gt; &lt;div class="collapse navbar-collapse" id="custom-collapse"&gt; &lt;?php wp_nav_menu( array( 'theme_location' =&gt; 'primary', 'container' =&gt; false, 'menu_class' =&gt; 'nav navbar-nav navbar-right', ) ); ?&gt; &lt;/div&gt; &lt;/div&gt; &lt;?php endif; ?&gt; </code></pre> <p>I tried unhooking the function that loads the header but that removes the header all together!</p> <p>The main header.php calls <code>shop-isle/inc/structure/header.php.</code> using </p> <pre><code>&lt;?php do_action( 'shop_isle_header' ); ?&gt; </code></pre> <p>The hooks.php located in <code>shop-isle/inc/structure/hooks.php</code> has the callback function registered using</p> <pre><code>add_action( 'shop_isle_header', 'shop_isle_primary_navigation', 50 ); </code></pre> <p>I've copied all the files over to my child theme and kept the directory structure the same but it does not override the parent files.</p> <p>How do I add the above code (example 1) in 'functions.php' in my child theme to update 'shop-isle/inc/structure/header.php'?</p>
[ { "answer_id": 309908, "author": "Alex Sancho", "author_id": 2536, "author_profile": "https://wordpress.stackexchange.com/users/2536", "pm_score": 1, "selected": false, "text": "<p>You need to copy to your child and edit the function where the file is included, probably ´shop_isle_primar...
2018/07/30
[ "https://wordpress.stackexchange.com/questions/309907", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/147762/" ]
I'm fairly new to Wordpress. I'm using the shop-isle theme that has a default navigation menu. I'm trying to override this with a fancy ‘Ubermenu’ plugin but the default collapse symbol keeps overriding the plugin. The theme header is loaded from directory shop-isle/inc/structure/header.php. I copied the entire directory to my child theme directory and made edit below in /header.php but it only works when I add it to the 'structure' folder in the parent theme NOT the child. example 1 ``` <?php if( function_exists( ‘ubermenu’ ) ): ?> <?php ubermenu( 'main' , array( 'theme_location' => 'primary' ) ); ?> <?php else: ?> <div class="header-menu-wrap"> <div class="collapse navbar-collapse" id="custom-collapse"> <?php wp_nav_menu( array( 'theme_location' => 'primary', 'container' => false, 'menu_class' => 'nav navbar-nav navbar-right', ) ); ?> </div> </div> <?php endif; ?> ``` I tried unhooking the function that loads the header but that removes the header all together! The main header.php calls `shop-isle/inc/structure/header.php.` using ``` <?php do_action( 'shop_isle_header' ); ?> ``` The hooks.php located in `shop-isle/inc/structure/hooks.php` has the callback function registered using ``` add_action( 'shop_isle_header', 'shop_isle_primary_navigation', 50 ); ``` I've copied all the files over to my child theme and kept the directory structure the same but it does not override the parent files. How do I add the above code (example 1) in 'functions.php' in my child theme to update 'shop-isle/inc/structure/header.php'?
You need to copy to your child and edit the function where the file is included, probably ´shop\_isle\_primary\_navigation´, to change the path where the file is located. Wordpress only loads automatically from child the default files, that's the ones defined in template hierarchy. You can read more about this at <https://developer.wordpress.org/themes/basics/template-hierarchy/>
309,938
<p>i need to insert wp_users -> user_login field to wp_terms name and slugs field,when a new user registering. </p> <p>my requirement is admin needs to assign posts to specific users, that is admin need to add a post to user1 ,but user2 should not see that.for this i created a custom post and add taxonomy for that.And the terms are users Usernames .so i need to list the usernames of the users as terms in the taxonomy.when a new user is registered his username should updated in the wp_terms table also,so i will get the usernames as terms.</p> <p>i stucked here .please suggest some solution for this</p>
[ { "answer_id": 309961, "author": "Souvik Sikdar", "author_id": 130021, "author_profile": "https://wordpress.stackexchange.com/users/130021", "pm_score": 0, "selected": false, "text": "<p>There is a simple way to to add username as the term of specific taxonomie.\nYou need to use \"<stron...
2018/07/30
[ "https://wordpress.stackexchange.com/questions/309938", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/143452/" ]
i need to insert wp\_users -> user\_login field to wp\_terms name and slugs field,when a new user registering. my requirement is admin needs to assign posts to specific users, that is admin need to add a post to user1 ,but user2 should not see that.for this i created a custom post and add taxonomy for that.And the terms are users Usernames .so i need to list the usernames of the users as terms in the taxonomy.when a new user is registered his username should updated in the wp\_terms table also,so i will get the usernames as terms. i stucked here .please suggest some solution for this
i got the solution for this ``` add_action('user_register', function ($user_id) { $user_info = get_userdata($user_id); $user_name = $user_info->user_login; wp_insert_term($user_name, 'user1', array()); }, 10, 1); ```
309,939
<p>I'm building a form with Contact Form 7 and I would need to add multiple fields under a single label and I would need to let the user to add more fields under that same label if needed. I'm using 4 fields as a starting point and I'd like to have like a + sign next to the last field which would add another field to the same set. Example:</p> <pre><code>Prizes: [ ] [ ] [ ] [ ] + </code></pre> <p>When that + sign is clicked another field would appear as 5th field</p>
[ { "answer_id": 309961, "author": "Souvik Sikdar", "author_id": 130021, "author_profile": "https://wordpress.stackexchange.com/users/130021", "pm_score": 0, "selected": false, "text": "<p>There is a simple way to to add username as the term of specific taxonomie.\nYou need to use \"<stron...
2018/07/30
[ "https://wordpress.stackexchange.com/questions/309939", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/147779/" ]
I'm building a form with Contact Form 7 and I would need to add multiple fields under a single label and I would need to let the user to add more fields under that same label if needed. I'm using 4 fields as a starting point and I'd like to have like a + sign next to the last field which would add another field to the same set. Example: ``` Prizes: [ ] [ ] [ ] [ ] + ``` When that + sign is clicked another field would appear as 5th field
i got the solution for this ``` add_action('user_register', function ($user_id) { $user_info = get_userdata($user_id); $user_name = $user_info->user_login; wp_insert_term($user_name, 'user1', array()); }, 10, 1); ```
309,972
<p>I added this bit of code to my header.php file:</p> <pre><code>&lt;script type="text/javascript"&gt; $(document).ready(function() { if( $('div').hasClass('icheckbox') &amp;&amp; $('div').hasClass('disabled') ) { $('div').parent().addClass('hide_empty'); } }); &lt;/script&gt; </code></pre> <p>My goal is to add the class .hide_empty to the parent of all div elements that have a class .icheckbox AND a class .disabled, in that order, with no other classes. The parent of these div elements is a li element in all cases.</p> <p>I checked many answers to related questions and tried many variations, but whatever cariation I use, the class .hide_empty is never added to the parent li element.</p> <p>What am I doing wrong here?</p> <p>Thanks to the input of both @Andrea and @dhirenpatel22 I came up with the following working code:</p> <p>In my <code>footer.php</code> I added:</p> <pre><code>&lt;?php function hide_empty_terms() { ?&gt; &lt;script type="text/javascript"&gt; jQuery(window).load(function() { jQuery(".icheckbox.disabled").each(function() { jQuery(this).parent('li').addClass('hide_empty'); }); }); &lt;/script&gt; &lt;?php } add_action('wp_footer', 'hide_empty_terms'); ?&gt; </code></pre> <p>right before <code>&lt;?php wp_footer(); ?&gt;</code>. This actually adds the class <code>hide_empty</code> to the parent <code>li</code> element of <code>&lt;div class="icheckbox disabled"&gt;</code>.</p>
[ { "answer_id": 309974, "author": "dhirenpatel22", "author_id": 124380, "author_profile": "https://wordpress.stackexchange.com/users/124380", "pm_score": 0, "selected": false, "text": "<p>I have just updated your code...</p>\n\n<pre><code>&lt;script type=\"text/javascript\"&gt;\n$(documen...
2018/07/30
[ "https://wordpress.stackexchange.com/questions/309972", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/142885/" ]
I added this bit of code to my header.php file: ``` <script type="text/javascript"> $(document).ready(function() { if( $('div').hasClass('icheckbox') && $('div').hasClass('disabled') ) { $('div').parent().addClass('hide_empty'); } }); </script> ``` My goal is to add the class .hide\_empty to the parent of all div elements that have a class .icheckbox AND a class .disabled, in that order, with no other classes. The parent of these div elements is a li element in all cases. I checked many answers to related questions and tried many variations, but whatever cariation I use, the class .hide\_empty is never added to the parent li element. What am I doing wrong here? Thanks to the input of both @Andrea and @dhirenpatel22 I came up with the following working code: In my `footer.php` I added: ``` <?php function hide_empty_terms() { ?> <script type="text/javascript"> jQuery(window).load(function() { jQuery(".icheckbox.disabled").each(function() { jQuery(this).parent('li').addClass('hide_empty'); }); }); </script> <?php } add_action('wp_footer', 'hide_empty_terms'); ?> ``` right before `<?php wp_footer(); ?>`. This actually adds the class `hide_empty` to the parent `li` element of `<div class="icheckbox disabled">`.
> > So, the elements should be changed into `<div class="icheckbox disabled hide_empty" style="">` > > > that's different from the goal stated in the question where you say you want to add class "hide\_empty" to the parent `<li>` of the `<div class="icheckbox">`. The code posted by @dhirenpatel22 should work to add class hide\_empty to the li element, of course if the element you want to add class to is the same div it should be `$(this).addClass('hide_empty')` Also note that hasClass() will return true even if the element has more classes. To find only the divs with both and exclusively icheckbox + disabled I guess the best way is: ``` $(".icheckbox, .disabled").each(function(){ $(this).parent('li').addClass('hide_empty'); // or $(this).addClass('hide_empty') //if it's the <div> instead of <li> you want to apply the rule }) ```
309,973
<p>In WordPress I want to schedule an Event which will run my function (hook) at a specific time (let's say at 6PM) and then it will run again after 15 minutes (means at 6:15 PM) and keep running after every 15 minutes for 3 hours (till 9 PM) and then it dies.</p> <pre><code>// I have the following code which run after every 6 hours function myprefix_custom_cron_schedule( $schedules ) { $schedules['every_six_hours'] = array( 'interval' =&gt; 21600, // Every 6 hours 'display' =&gt; __( 'Every 6 hours' ), ); return $schedules; } add_filter( 'cron_schedules', 'myprefix_custom_cron_schedule' ); // Schedule an action if it's not already scheduled if ( ! wp_next_scheduled( 'myprefix_cron_hook' ) ) { wp_schedule_event( time(), 'every_six_hours', 'myprefix_cron_hook' ); } // Hook into that action that'll fire every six hours add_action( 'myprefix_cron_hook', 'myprefix_cron_function' ); // create your function, that runs on cron function myprefix_cron_function() { // your function... } </code></pre>
[ { "answer_id": 309988, "author": "Kaperto", "author_id": 147795, "author_profile": "https://wordpress.stackexchange.com/users/147795", "pm_score": 0, "selected": false, "text": "<p>to do that, it's better to have a cron that is fired every 15 minutes and then you test if it's time to do ...
2018/07/30
[ "https://wordpress.stackexchange.com/questions/309973", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/147498/" ]
In WordPress I want to schedule an Event which will run my function (hook) at a specific time (let's say at 6PM) and then it will run again after 15 minutes (means at 6:15 PM) and keep running after every 15 minutes for 3 hours (till 9 PM) and then it dies. ``` // I have the following code which run after every 6 hours function myprefix_custom_cron_schedule( $schedules ) { $schedules['every_six_hours'] = array( 'interval' => 21600, // Every 6 hours 'display' => __( 'Every 6 hours' ), ); return $schedules; } add_filter( 'cron_schedules', 'myprefix_custom_cron_schedule' ); // Schedule an action if it's not already scheduled if ( ! wp_next_scheduled( 'myprefix_cron_hook' ) ) { wp_schedule_event( time(), 'every_six_hours', 'myprefix_cron_hook' ); } // Hook into that action that'll fire every six hours add_action( 'myprefix_cron_hook', 'myprefix_cron_function' ); // create your function, that runs on cron function myprefix_cron_function() { // your function... } ```
Setup WordPress Cron Events --------------------------- Let's say you want to start the cron at 6PM and keep running the cron after every 15 minutes till 9PM (for 3 hours). Then all cron stops. > > **Note:** for the simplicity of implementation, all time entry in the CODE is considered to be GMT/UTC. > > > For this, you need to schedule two cron events, one will start at 6PM and keep running at every 15 minutes from 6PM. The other one will be one time cron event that'll run at 9PM. This one will stop the other cron. The plugin CODE will be something like the following: ``` <?php /* Plugin Name: WPSE Custom Cron Plugin URI: https://wordpress.stackexchange.com/a/309973/110572 Description: Custom Cron Plugin Version: 1.0.0 Author: Fayaz Ahmed Author URI: https://www.fayazmiraz.com/ */ add_action( 'wpse_custom_cron_event', 'wpse_custom_cron' ); add_action( 'wpse_custom_cron_event_stop', 'wpse_custom_cron_stop' ); function wpse_custom_cron() { // Your Custom Cron CODE HERE } function wpse_custom_cron_start() { // Calculate the start time: e.g. whenever the next 6:00PM (UTC) is. $cron_start_time = strtotime( "today 6:00pm" ); // If 6PM has already passed today, set it to 6PM next day if( $cron_start_time < time() ) { $cron_start_time = $cron_start_time + 24 * HOUR_IN_SECONDS; } if ( ! wp_next_scheduled( 'wpse_custom_cron_event' ) ) { wp_schedule_event( $cron_start_time, 'fifteen_minutes', 'wpse_custom_cron_event' ); } if ( ! wp_next_scheduled( 'wpse_custom_cron_event_stop' ) ) { // this 1 time cron will stop the original cron 'wpse_custom_cron_event' after 3 hours of starting $cron_stop_time = $cron_start_time + 3 * HOUR_IN_SECONDS; wp_schedule_single_event( $cron_stop_time, 'wpse_custom_cron_event_stop' ); } } function wpse_custom_cron_stop() { // removing all possible custom cron events named 'wpse_custom_cron_event' while( false !== wp_unschedule_event( wp_next_scheduled( 'wpse_custom_cron_event' ), 'wpse_custom_cron_event' ) ) {} } // Add a 15 minutes custom cron schedule add_filter( 'cron_schedules', 'wpse_custom_cron_schedule' ); function wpse_custom_cron_schedule( $schedules ) { $schedules['fifteen_minutes'] = array( 'interval' => 15 * 60, 'display' => esc_html__( 'Every Fifteen Minutes' ), ); return $schedules; } // schedule the cron event on plugin activation register_activation_hook( __FILE__, 'wpse_custom_cron_plugin_activation' ); function wpse_custom_cron_plugin_activation() { wpse_custom_cron_start(); } // remove the cron event on plugin deactivation register_deactivation_hook( __FILE__, 'wpse_custom_cron_plugin_deactivation' ); function wpse_custom_cron_plugin_deactivation() { wpse_custom_cron_stop(); // in case the stop event didn't run yet while( false !== wp_unschedule_event( wp_next_scheduled( 'wpse_custom_cron_event_stop' ), 'wpse_custom_cron_event_stop' ) ) {} } ``` This sample plugin will start the cron on plugin activation, but if needed, you can edit the CODE to start the cron by other means as well (say using a button click in admin panel) using the `wpse_custom_cron_start()` function. Also, if you want to run the same cron everyday 6PM (not just one time after activation), then simply change the `wp_schedule_single_event` call in `wpse_custom_cron_start()` function to: ``` wp_schedule_event( $cron_stop_time, 'daily', 'wpse_custom_cron_event_stop' ); ``` > > ***Note:* Event/Cron created with arguments** > > > If you create the event/cron with an argument, **you must also stop the event with the exact same argument.** > > > For example, if you created the event like this (in `wpse_custom_cron_start()` function of the above CODE): > > > > ``` > .... > wp_schedule_event( $cron_start_time, 'fifteen_minutes', 'wpse_custom_cron_event', $args1 ); > .... > wp_schedule_single_event( $cron_stop_time, 'wpse_custom_cron_event_stop', $args2 ); > > ``` > > then when stopping the events, you must also use the exact same argument in `wp_next_scheduled()` function call. So the stop CODE will become like: > > > > ``` > .... > while( false !== wp_unschedule_event( wp_next_scheduled( 'wpse_custom_cron_event', $args1 ), 'wpse_custom_cron_event' ) ) {} > .... > while( false !== wp_unschedule_event( wp_next_scheduled( 'wpse_custom_cron_event_stop', $args2 ), 'wpse_custom_cron_event_stop' ) ) {} > > ``` > > Again, remember, it has to be the **exact same argument**, even different data type will not work. For example, in the following CODE, `$args1` and `$args2` are **NOT** the same, but `$args1` and `$args3` are same: > > > > ``` > $args1 = array( 'key' => 1 ); > $args2 = array( 'key' => '1' ); > $args3 = array( 'key' => 1 ); > > ``` > > because `'1'` is string and `1` is a number. > > > This is important because, **sometimes people save the arguments in database as key value pairs**, & when they use it again later, the value from database doesn't work for arguments that were numbers, as the numbers are converted to strings when retrieved from database. So you must convert them back to numbers when passing the argument to the `wp_next_scheduled()` function. > > > for more information, check the documentation: > > > * [wp\_schedule\_event()](https://developer.wordpress.org/reference/functions/wp_schedule_event/) > * [wp\_unschedule\_event()](https://developer.wordpress.org/reference/functions/wp_unschedule_event/) > * [wp\_schedule\_single\_event()](https://developer.wordpress.org/reference/functions/wp_schedule_single_event/) > * [wp\_next\_scheduled()](https://developer.wordpress.org/reference/functions/wp_next_scheduled/) > > > Running the Cron: ----------------- The best way to run WordPress cron is to set `define('DISABLE_WP_CRON', true);` in `wp-config.php` file and then run the cron from system crontab as described [in this post](https://wordpress.stackexchange.com/a/253331/110572). Use external cron service: -------------------------- In case you cannot set crontab, you may use an external cron service like [cron-job.org](https://cron-job.org/en/) and set the cron accordingly. For example, for the above cron events, you may set a single cron job there with a setting like: [![cron-job.org settings](https://i.stack.imgur.com/uUVll.png)](https://i.stack.imgur.com/uUVll.png) > > Here, all the values of `Days of Month`, `Days of Week` & `Months` are selected; and `Hours` selected to `18, 19, 20` and `Minutes` selected to `0, 15, 30, 45`. Which means: run cron Everyday from 6PM to 9PM (GTM is set as time zone from account setting) on 0th, 15th, 30th and 45th minute (i.e. at 15 minutes interval). > > > Cron Check + Manual Cron: ------------------------- You may check if your cron schedules properly using [WP Control](https://wordpress.org/plugins/wp-crontrol/) plugin. This plugin can also be used to set up custom cron events and intervals.
309,981
<p>It seems by default WordPress provides fields for site-title and tagline.</p> <p>I understand how to add (for example) the option to chose a logo, adding <code>add_theme_support( 'custom-logo' );</code> to the functions.php file. However, how do I add fields for 'company name' and 'company division' or for any text field that is not already part of the WordPress theme support?</p>
[ { "answer_id": 309982, "author": "David Sword", "author_id": 132362, "author_profile": "https://wordpress.stackexchange.com/users/132362", "pm_score": 3, "selected": false, "text": "<p>This is all part of the <a href=\"https://codex.wordpress.org/Theme_Customization_API\" rel=\"noreferre...
2018/07/30
[ "https://wordpress.stackexchange.com/questions/309981", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/147800/" ]
It seems by default WordPress provides fields for site-title and tagline. I understand how to add (for example) the option to chose a logo, adding `add_theme_support( 'custom-logo' );` to the functions.php file. However, how do I add fields for 'company name' and 'company division' or for any text field that is not already part of the WordPress theme support?
You'll have to add your own customizer controls to achieve that. So for example, if you want to add Company Name, you can use this code: ``` function my_register_additional_customizer_settings( $wp_customize ) { $wp_customize->add_setting( 'my_company_name', array( 'default' => '', 'type' => 'option', // you can also use 'theme_mod' 'capability' => 'edit_theme_options' ), ); $wp_customize->add_control( new WP_Customize_Control( $wp_customize, 'my_company_name', array( 'label' => __( 'Company name', 'textdomain' ), 'description' => __( 'Description for your field', 'textdomain' ), 'settings' => 'my_company_name', 'priority' => 10, 'section' => 'title_tagline', 'type' => 'text', ) ) ); } add_action( 'customize_register', 'my_register_additional_customizer_settings' ); ``` PS. Here you can find more docs regarding this topic: [Theme Customization API](https://codex.wordpress.org/Theme_Customization_API)
310,013
<p><code>wp_delete_user()</code> function requires user ID and [optional] reassign ID if the content is to be reassigned to another user.</p> <p>All users' user names are also unique as WP doesn't allow duplicate user names. If I know username, is there no way with just one PHP/mysqli query I can delete the user instead of run one query to find ID of that user first and then tell wordpress to delete that user ?</p>
[ { "answer_id": 310016, "author": "Krzysiek Dróżdż", "author_id": 34172, "author_profile": "https://wordpress.stackexchange.com/users/34172", "pm_score": 3, "selected": true, "text": "<p>There is no way to do this with only one query. But to be honest - deleting user takes more than one q...
2018/07/31
[ "https://wordpress.stackexchange.com/questions/310013", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/147821/" ]
`wp_delete_user()` function requires user ID and [optional] reassign ID if the content is to be reassigned to another user. All users' user names are also unique as WP doesn't allow duplicate user names. If I know username, is there no way with just one PHP/mysqli query I can delete the user instead of run one query to find ID of that user first and then tell wordpress to delete that user ?
There is no way to do this with only one query. But to be honest - deleting user takes more than one query itself... You shouldn’t use custom SQL for that, because there are many things you could break this way... Always use WP functions, if they exists (what if some plugin logs every deleted user, or what if some other action is needed, etc.) You can use [`get_user_by`](https://developer.wordpress.org/reference/functions/get_user_by/) to achieve that. Here's the example: ``` $user = get_user_by( 'login', 'john' ); if ( $user ) { // get_user_by can return false, if no such user exists wp_delete_user( $user->ID ); } ``` The fields you can get user by are: `ID` | `slug` | `email` | `login`.
310,026
<p>I am trying to enqueuer a script after registering it but I am getting an error.</p> <p>This is the script:</p> <pre><code>function _test() { console.log("Test"); } </code></pre> <p>That's the PHP:</p> <pre><code>function fsg_shortURL() { echo "Funtion Called"; wp_register_script('_test','/wp-content/themes/theme-child/js/test.js'); wp_enqueue_script('_test'); } add_shortcode( 'fsg', 'fsg_shortURL' ); </code></pre> <p>The console's suppouse to log <code>Test</code> but nothing happens..</p> <p>Thanks!</p>
[ { "answer_id": 310029, "author": "Kaperto", "author_id": 147795, "author_profile": "https://wordpress.stackexchange.com/users/147795", "pm_score": 0, "selected": false, "text": "<p>To add a file located in a directory of the active theme, you have to use <a href=\"https://codex.wordpress...
2018/07/31
[ "https://wordpress.stackexchange.com/questions/310026", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/147331/" ]
I am trying to enqueuer a script after registering it but I am getting an error. This is the script: ``` function _test() { console.log("Test"); } ``` That's the PHP: ``` function fsg_shortURL() { echo "Funtion Called"; wp_register_script('_test','/wp-content/themes/theme-child/js/test.js'); wp_enqueue_script('_test'); } add_shortcode( 'fsg', 'fsg_shortURL' ); ``` The console's suppouse to log `Test` but nothing happens.. Thanks!
Simply you've to call the function to execute it: ``` function _test() { console.log("Test"); } _test(); ```
310,036
<p>I have 4 posts and I displaying 2 posts per page.</p> <pre><code>$ids = array('16085','16088','16083','16091'); $options = array( 'post_type' =&gt; $post_type, 'posts_per_page' =&gt; $posts_per_page, 'paged' =&gt; $paged, 'meta_query' =&gt; $meta_query, 'tax_query' =&gt; $tax_query, 'post__in ' =&gt; $ids, 'orderby' =&gt; 'post__in', ); $get_properties = new WP_Query( $options ); </code></pre> <p>I want to display posts in a specific order is given $ids array.</p>
[ { "answer_id": 310047, "author": "VinothRaja", "author_id": 146008, "author_profile": "https://wordpress.stackexchange.com/users/146008", "pm_score": 0, "selected": false, "text": "<p>Try this below code</p>\n\n<pre><code>$get_properties = new WP_Query( array( 'post_type' =&gt; 'page','p...
2018/07/31
[ "https://wordpress.stackexchange.com/questions/310036", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/127648/" ]
I have 4 posts and I displaying 2 posts per page. ``` $ids = array('16085','16088','16083','16091'); $options = array( 'post_type' => $post_type, 'posts_per_page' => $posts_per_page, 'paged' => $paged, 'meta_query' => $meta_query, 'tax_query' => $tax_query, 'post__in ' => $ids, 'orderby' => 'post__in', ); $get_properties = new WP_Query( $options ); ``` I want to display posts in a specific order is given $ids array.
OK, so you want to define posts order by yourself. WP\_Query allows you to do that - you'll have to use `orderby` => `post__in` to achieve it. And that's what you do. So why isn't it working? Because of a typo ;) Ordering posts by `post__in` preserves post ID order given in the 'post\_\_in' array. But you don't pass `post__in` param in your query (you pass `post__in` - additional space at the end). ``` $ids = array('16085','16088','16083','16091'); $options = array( 'post_type' => $post_type, 'posts_per_page' => $posts_per_page, 'paged' => $paged, 'meta_query' => $meta_query, 'tax_query' => $tax_query, 'post__in ' => $ids, // <-- here is the additional space 'orderby' => 'post__in', ); $get_properties = new WP_Query( $options ); ``` So this should work just fine: ``` $ids = array('16085','16088','16083','16091'); $options = array( 'post_type' => $post_type, 'posts_per_page' => $posts_per_page, 'paged' => $paged, 'meta_query' => $meta_query, 'tax_query' => $tax_query, 'post__in' => $ids, // <-- there is no space anymore in here 'orderby' => 'post__in', ); $get_properties = new WP_Query( $options ); ```
310,058
<p>I downloaded my wordpress site and using it on localhost, but I couldn't. I changed my url in mysql db and followed <a href="https://stackoverflow.com/questions/15557718/after-migration-of-wordpress-website-i-cant-access-the-admin-white-page">this</a> . still I do not have access to my website or wp-admin. </p> <p>I have <a href="https://localhost:8888/nofel/invest/davids/wp-admin/" rel="nofollow noreferrer">https://localhost:8888/nofel/invest/davids/wp-admin/</a></p> <p>I get 404 but when I do <a href="https://localhost:8888/nofel/invest/davids" rel="nofollow noreferrer">https://localhost:8888/nofel/invest/davids</a> I get a lot of error in console about css, images and other things.</p> <p>What am I missing? </p>
[ { "answer_id": 310047, "author": "VinothRaja", "author_id": 146008, "author_profile": "https://wordpress.stackexchange.com/users/146008", "pm_score": 0, "selected": false, "text": "<p>Try this below code</p>\n\n<pre><code>$get_properties = new WP_Query( array( 'post_type' =&gt; 'page','p...
2018/07/31
[ "https://wordpress.stackexchange.com/questions/310058", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/147453/" ]
I downloaded my wordpress site and using it on localhost, but I couldn't. I changed my url in mysql db and followed [this](https://stackoverflow.com/questions/15557718/after-migration-of-wordpress-website-i-cant-access-the-admin-white-page) . still I do not have access to my website or wp-admin. I have <https://localhost:8888/nofel/invest/davids/wp-admin/> I get 404 but when I do <https://localhost:8888/nofel/invest/davids> I get a lot of error in console about css, images and other things. What am I missing?
OK, so you want to define posts order by yourself. WP\_Query allows you to do that - you'll have to use `orderby` => `post__in` to achieve it. And that's what you do. So why isn't it working? Because of a typo ;) Ordering posts by `post__in` preserves post ID order given in the 'post\_\_in' array. But you don't pass `post__in` param in your query (you pass `post__in` - additional space at the end). ``` $ids = array('16085','16088','16083','16091'); $options = array( 'post_type' => $post_type, 'posts_per_page' => $posts_per_page, 'paged' => $paged, 'meta_query' => $meta_query, 'tax_query' => $tax_query, 'post__in ' => $ids, // <-- here is the additional space 'orderby' => 'post__in', ); $get_properties = new WP_Query( $options ); ``` So this should work just fine: ``` $ids = array('16085','16088','16083','16091'); $options = array( 'post_type' => $post_type, 'posts_per_page' => $posts_per_page, 'paged' => $paged, 'meta_query' => $meta_query, 'tax_query' => $tax_query, 'post__in' => $ids, // <-- there is no space anymore in here 'orderby' => 'post__in', ); $get_properties = new WP_Query( $options ); ```
310,064
<p>When I logged in on my site this morning I noticed that my user can’t publish anything. I am administrator and the only user on the site.</p> <p>On Posts and Pages instead of “Publish” I have the “Submit for review” button and if I click on it the page is blank and displays “Sorry you are not allowed to modify this post”.</p> <p>I have the same issue with all my plugins disabled and even after cache reset.</p> <p>Can you help me?</p> <p>Edit: Thanks for the answers i finally managed to fix everything</p> <p>I found the answer ! After wandering on the Internets I found this page : <a href="https://wpindexfixer.tools.managedwphosting.nl/wpindexfixer/" rel="nofollow noreferrer">https://wpindexfixer.tools.managedwphosting.nl/wpindexfixer/</a></p> <p>So here is what I gave SQL:</p> <pre><code> DELETE FROM wp_users WHERE ID = 0; ALTER TABLE wp_users ADD PRIMARY KEY (ID); ALTER TABLE wp_users ADD KEY user_login_key (user_login); ALTER TABLE wp_users ADD KEY user_nicename (user_nicename); ALTER TABLE wp_users ADD KEY user_email (user_email); ALTER TABLE wp_users MODIFY ID bigint(20) unsigned NOT NULL auto_increment; DELETE FROM wp_usermeta WHERE umeta_id = 0; ALTER TABLE wp_usermeta ADD PRIMARY KEY (umeta_id); ALTER TABLE wp_usermeta ADD KEY user_id (user_id); ALTER TABLE wp_usermeta ADD KEY meta_key (meta_key(191)); ALTER TABLE wp_usermeta MODIFY umeta_id bigint(20) unsigned NOT NULL auto_increment; DELETE FROM wp_posts WHERE ID = 0; ALTER TABLE wp_posts ADD PRIMARY KEY (ID); ALTER TABLE wp_posts ADD KEY post_name (post_name(191)); ALTER TABLE wp_posts ADD KEY type_status_date (post_type,post_status,post_date,ID); ALTER TABLE wp_posts ADD KEY post_parent (post_parent); ALTER TABLE wp_posts ADD KEY post_author (post_author); ALTER TABLE wp_posts MODIFY ID bigint(20) unsigned NOT NULL auto_increment; DELETE FROM wp_comments WHERE comment_ID = 0; ALTER TABLE wp_comments ADD PRIMARY KEY (comment_ID); ALTER TABLE wp_comments ADD KEY comment_post_ID (comment_post_ID); ALTER TABLE wp_comments ADD KEY comment_approved_date_gmt (comment_approved,comment_date_gmt); ALTER TABLE wp_comments ADD KEY comment_date_gmt (comment_date_gmt); ALTER TABLE wp_comments ADD KEY comment_parent (comment_parent); ALTER TABLE wp_comments ADD KEY comment_author_email (comment_author_email(10)); ALTER TABLE wp_comments MODIFY comment_ID bigint(20) unsigned NOT NULL auto_increment; DELETE FROM wp_links WHERE link_id = 0; ALTER TABLE wp_links ADD PRIMARY KEY (link_id); ALTER TABLE wp_links ADD KEY link_visible (link_visible); ALTER TABLE wp_links MODIFY link_id bigint(20) unsigned NOT NULL auto_increment; DELETE FROM wp_options WHERE option_id = 0; ALTER TABLE wp_options ADD PRIMARY KEY (option_id); ALTER TABLE wp_options ADD UNIQUE KEY option_name (option_name); ALTER TABLE wp_options MODIFY option_id bigint(20) unsigned NOT NULL auto_increment; DELETE FROM wp_postmeta WHERE meta_id = 0; ALTER TABLE wp_postmeta ADD PRIMARY KEY (meta_id); ALTER TABLE wp_postmeta ADD KEY post_id (post_id); ALTER TABLE wp_postmeta ADD KEY meta_key (meta_key(191)); ALTER TABLE wp_postmeta MODIFY meta_id bigint(20) unsigned NOT NULL auto_increment; DELETE FROM wp_terms WHERE term_id = 0; ALTER TABLE wp_terms ADD PRIMARY KEY (term_id); ALTER TABLE wp_terms ADD KEY slug (slug(191)); ALTER TABLE wp_terms ADD KEY name (name(191)); ALTER TABLE wp_terms MODIFY term_id bigint(20) unsigned NOT NULL auto_increment; DELETE FROM wp_term_taxonomy WHERE term_taxonomy_id = 0; ALTER TABLE wp_term_taxonomy ADD PRIMARY KEY (term_taxonomy_id); ALTER TABLE wp_term_taxonomy ADD UNIQUE KEY term_id_taxonomy (term_id,taxonomy); ALTER TABLE wp_term_taxonomy ADD KEY taxonomy (taxonomy); ALTER TABLE wp_term_taxonomy MODIFY term_taxonomy_id bigint(20) unsigned NOT NULL auto_increment; DELETE FROM wp_term_relationships WHERE object_id = 0; DELETE FROM wp_term_relationships WHERE term_taxonomy_id = 0; ALTER TABLE wp_term_relationships ADD PRIMARY KEY (object_id,term_taxonomy_id); ALTER TABLE wp_term_relationships ADD KEY term_taxonomy_id (term_taxonomy_id); DELETE FROM wp_termmeta WHERE meta_id = 0; ALTER TABLE wp_termmeta ADD PRIMARY KEY (meta_id); ALTER TABLE wp_termmeta ADD KEY term_id (term_id); ALTER TABLE wp_termmeta ADD KEY meta_key (meta_key(191)); ALTER TABLE wp_termmeta MODIFY meta_id bigint(20) unsigned NOT NULL auto_increment; DELETE FROM wp_commentmeta WHERE meta_id = 0; ALTER TABLE wp_commentmeta ADD PRIMARY KEY (meta_id); ALTER TABLE wp_commentmeta ADD KEY comment_id (comment_id); ALTER TABLE wp_commentmeta ADD KEY meta_key (meta_key(191)); ALTER TABLE wp_commentmeta MODIFY meta_id bigint(20) unsigned NOT NULL auto_increment; </code></pre> <p>Despite an error on the primary key for table wp_usermeta this went well and everything is back to normal.</p>
[ { "answer_id": 310047, "author": "VinothRaja", "author_id": 146008, "author_profile": "https://wordpress.stackexchange.com/users/146008", "pm_score": 0, "selected": false, "text": "<p>Try this below code</p>\n\n<pre><code>$get_properties = new WP_Query( array( 'post_type' =&gt; 'page','p...
2018/07/31
[ "https://wordpress.stackexchange.com/questions/310064", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/147835/" ]
When I logged in on my site this morning I noticed that my user can’t publish anything. I am administrator and the only user on the site. On Posts and Pages instead of “Publish” I have the “Submit for review” button and if I click on it the page is blank and displays “Sorry you are not allowed to modify this post”. I have the same issue with all my plugins disabled and even after cache reset. Can you help me? Edit: Thanks for the answers i finally managed to fix everything I found the answer ! After wandering on the Internets I found this page : <https://wpindexfixer.tools.managedwphosting.nl/wpindexfixer/> So here is what I gave SQL: ``` DELETE FROM wp_users WHERE ID = 0; ALTER TABLE wp_users ADD PRIMARY KEY (ID); ALTER TABLE wp_users ADD KEY user_login_key (user_login); ALTER TABLE wp_users ADD KEY user_nicename (user_nicename); ALTER TABLE wp_users ADD KEY user_email (user_email); ALTER TABLE wp_users MODIFY ID bigint(20) unsigned NOT NULL auto_increment; DELETE FROM wp_usermeta WHERE umeta_id = 0; ALTER TABLE wp_usermeta ADD PRIMARY KEY (umeta_id); ALTER TABLE wp_usermeta ADD KEY user_id (user_id); ALTER TABLE wp_usermeta ADD KEY meta_key (meta_key(191)); ALTER TABLE wp_usermeta MODIFY umeta_id bigint(20) unsigned NOT NULL auto_increment; DELETE FROM wp_posts WHERE ID = 0; ALTER TABLE wp_posts ADD PRIMARY KEY (ID); ALTER TABLE wp_posts ADD KEY post_name (post_name(191)); ALTER TABLE wp_posts ADD KEY type_status_date (post_type,post_status,post_date,ID); ALTER TABLE wp_posts ADD KEY post_parent (post_parent); ALTER TABLE wp_posts ADD KEY post_author (post_author); ALTER TABLE wp_posts MODIFY ID bigint(20) unsigned NOT NULL auto_increment; DELETE FROM wp_comments WHERE comment_ID = 0; ALTER TABLE wp_comments ADD PRIMARY KEY (comment_ID); ALTER TABLE wp_comments ADD KEY comment_post_ID (comment_post_ID); ALTER TABLE wp_comments ADD KEY comment_approved_date_gmt (comment_approved,comment_date_gmt); ALTER TABLE wp_comments ADD KEY comment_date_gmt (comment_date_gmt); ALTER TABLE wp_comments ADD KEY comment_parent (comment_parent); ALTER TABLE wp_comments ADD KEY comment_author_email (comment_author_email(10)); ALTER TABLE wp_comments MODIFY comment_ID bigint(20) unsigned NOT NULL auto_increment; DELETE FROM wp_links WHERE link_id = 0; ALTER TABLE wp_links ADD PRIMARY KEY (link_id); ALTER TABLE wp_links ADD KEY link_visible (link_visible); ALTER TABLE wp_links MODIFY link_id bigint(20) unsigned NOT NULL auto_increment; DELETE FROM wp_options WHERE option_id = 0; ALTER TABLE wp_options ADD PRIMARY KEY (option_id); ALTER TABLE wp_options ADD UNIQUE KEY option_name (option_name); ALTER TABLE wp_options MODIFY option_id bigint(20) unsigned NOT NULL auto_increment; DELETE FROM wp_postmeta WHERE meta_id = 0; ALTER TABLE wp_postmeta ADD PRIMARY KEY (meta_id); ALTER TABLE wp_postmeta ADD KEY post_id (post_id); ALTER TABLE wp_postmeta ADD KEY meta_key (meta_key(191)); ALTER TABLE wp_postmeta MODIFY meta_id bigint(20) unsigned NOT NULL auto_increment; DELETE FROM wp_terms WHERE term_id = 0; ALTER TABLE wp_terms ADD PRIMARY KEY (term_id); ALTER TABLE wp_terms ADD KEY slug (slug(191)); ALTER TABLE wp_terms ADD KEY name (name(191)); ALTER TABLE wp_terms MODIFY term_id bigint(20) unsigned NOT NULL auto_increment; DELETE FROM wp_term_taxonomy WHERE term_taxonomy_id = 0; ALTER TABLE wp_term_taxonomy ADD PRIMARY KEY (term_taxonomy_id); ALTER TABLE wp_term_taxonomy ADD UNIQUE KEY term_id_taxonomy (term_id,taxonomy); ALTER TABLE wp_term_taxonomy ADD KEY taxonomy (taxonomy); ALTER TABLE wp_term_taxonomy MODIFY term_taxonomy_id bigint(20) unsigned NOT NULL auto_increment; DELETE FROM wp_term_relationships WHERE object_id = 0; DELETE FROM wp_term_relationships WHERE term_taxonomy_id = 0; ALTER TABLE wp_term_relationships ADD PRIMARY KEY (object_id,term_taxonomy_id); ALTER TABLE wp_term_relationships ADD KEY term_taxonomy_id (term_taxonomy_id); DELETE FROM wp_termmeta WHERE meta_id = 0; ALTER TABLE wp_termmeta ADD PRIMARY KEY (meta_id); ALTER TABLE wp_termmeta ADD KEY term_id (term_id); ALTER TABLE wp_termmeta ADD KEY meta_key (meta_key(191)); ALTER TABLE wp_termmeta MODIFY meta_id bigint(20) unsigned NOT NULL auto_increment; DELETE FROM wp_commentmeta WHERE meta_id = 0; ALTER TABLE wp_commentmeta ADD PRIMARY KEY (meta_id); ALTER TABLE wp_commentmeta ADD KEY comment_id (comment_id); ALTER TABLE wp_commentmeta ADD KEY meta_key (meta_key(191)); ALTER TABLE wp_commentmeta MODIFY meta_id bigint(20) unsigned NOT NULL auto_increment; ``` Despite an error on the primary key for table wp\_usermeta this went well and everything is back to normal.
OK, so you want to define posts order by yourself. WP\_Query allows you to do that - you'll have to use `orderby` => `post__in` to achieve it. And that's what you do. So why isn't it working? Because of a typo ;) Ordering posts by `post__in` preserves post ID order given in the 'post\_\_in' array. But you don't pass `post__in` param in your query (you pass `post__in` - additional space at the end). ``` $ids = array('16085','16088','16083','16091'); $options = array( 'post_type' => $post_type, 'posts_per_page' => $posts_per_page, 'paged' => $paged, 'meta_query' => $meta_query, 'tax_query' => $tax_query, 'post__in ' => $ids, // <-- here is the additional space 'orderby' => 'post__in', ); $get_properties = new WP_Query( $options ); ``` So this should work just fine: ``` $ids = array('16085','16088','16083','16091'); $options = array( 'post_type' => $post_type, 'posts_per_page' => $posts_per_page, 'paged' => $paged, 'meta_query' => $meta_query, 'tax_query' => $tax_query, 'post__in' => $ids, // <-- there is no space anymore in here 'orderby' => 'post__in', ); $get_properties = new WP_Query( $options ); ```
310,074
<p>I'm trying to concatenate my <strong>site_url</strong> and a string, but it doesn't work. This is what I'm doing:</p> <pre><code>$myurl = site_url(); var_dump($myurl); $url = "https" . $myurl . "/inbox/?fepaction=viewmessage&amp;fep_id=" . $inserted_message-&gt;ID; var_dump($url); die; </code></pre> <p>The output looks like this:</p> <blockquote> <p>string(31) "//zgp.mydomain.be" string(78) "https:/inbox/?fepaction=viewmessage&amp;fep_id=4813"</p> </blockquote> <p>As you can see it isn't merged. How can this be?</p>
[ { "answer_id": 310087, "author": "helle", "author_id": 32871, "author_profile": "https://wordpress.stackexchange.com/users/32871", "pm_score": 0, "selected": false, "text": "<p>What you are lookgin for is <a href=\"https://codex.wordpress.org/Function_Reference/home_url\" rel=\"nofollow ...
2018/07/31
[ "https://wordpress.stackexchange.com/questions/310074", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/65180/" ]
I'm trying to concatenate my **site\_url** and a string, but it doesn't work. This is what I'm doing: ``` $myurl = site_url(); var_dump($myurl); $url = "https" . $myurl . "/inbox/?fepaction=viewmessage&fep_id=" . $inserted_message->ID; var_dump($url); die; ``` The output looks like this: > > string(31) "//zgp.mydomain.be" string(78) "https:/inbox/?fepaction=viewmessage&fep\_id=4813" > > > As you can see it isn't merged. How can this be?
Without knowing exactly what you are trying to do, it seems you want to append query variables to the URL. WordPress has methods for handling that properly, without manual string concatenation. Look at the documentation for `add_query_arg()` for details: <https://developer.wordpress.org/reference/functions/add_query_arg/> You can rebuild the URL and append query variables to the URL query by using this function. There are two ways to use this function; either a single key and value, or an associative array. Using a single key and value: ``` add_query_arg( 'key', 'value', 'http://example.com' ); ``` Would create `http://example.com/?key=value` Using an associative array: ``` add_query_arg( array( 'key1' => 'value1', 'key2' => 'value2', ), 'http://example.com' ); ``` This would create `http://example.com/?key1=value1&key2=value2`
310,081
<p>I am trying to make an ajax call and I am getting the error:</p> <pre><code>TypeError: $ is undefined </code></pre> <p>This is my function.php file:</p> <pre><code>&lt;?php // Add custom Theme Functions here // function gear_guide_product_view( $atts ) { $a = shortcode_atts( array( 'id' =&gt; '0' ), $atts ); wp_register_script( 'load_product_info' , '/wp-content/themes/theme-child/js/test.js' , array( 'jquery' ) ); wp_enqueue_script( 'load_product_info' ); wp_localize_script( 'load_product_info' , 'para' , $atts); } add_shortcode( 'fsg' , 'gear_guide_product_view' ); </code></pre> <p>this is the ajax:</p> <pre><code>function load_product_info() { console.log(para.id); $.ajax({ type: 'POST', url: '/wp-content/themes/flatsome-child/js/controllers/get_product_info.php', data: para, dataType: 'json', success: function (data) { console.log(data); } }); } load_product_info(); </code></pre> <p>I have declared the use of jquery and from what I read on google it's all I need in order to make an ajax call.</p> <p>If there is any more information needed tell me and I'll do my best to provide it.</p> <p>Thanks!</p>
[ { "answer_id": 310089, "author": "Krzysiek Dróżdż", "author_id": 34172, "author_profile": "https://wordpress.stackexchange.com/users/34172", "pm_score": 3, "selected": true, "text": "<p>As Milo already said in comment, jQuery is in noConflict mode in WordPress. This way other JS librarie...
2018/07/31
[ "https://wordpress.stackexchange.com/questions/310081", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/147331/" ]
I am trying to make an ajax call and I am getting the error: ``` TypeError: $ is undefined ``` This is my function.php file: ``` <?php // Add custom Theme Functions here // function gear_guide_product_view( $atts ) { $a = shortcode_atts( array( 'id' => '0' ), $atts ); wp_register_script( 'load_product_info' , '/wp-content/themes/theme-child/js/test.js' , array( 'jquery' ) ); wp_enqueue_script( 'load_product_info' ); wp_localize_script( 'load_product_info' , 'para' , $atts); } add_shortcode( 'fsg' , 'gear_guide_product_view' ); ``` this is the ajax: ``` function load_product_info() { console.log(para.id); $.ajax({ type: 'POST', url: '/wp-content/themes/flatsome-child/js/controllers/get_product_info.php', data: para, dataType: 'json', success: function (data) { console.log(data); } }); } load_product_info(); ``` I have declared the use of jquery and from what I read on google it's all I need in order to make an ajax call. If there is any more information needed tell me and I'll do my best to provide it. Thanks!
As Milo already said in comment, jQuery is in noConflict mode in WordPress. This way other JS libraries can also use $ character... One way to solve it is using jQuery everywhere in your JS files. Another is to create block and define $ variable in it: ``` jQuery(function ($) { $.ajax(...); // here you can use $ since it is already defined and won’t cause conflicts }); ```
310,101
<p>I am developing a section on the front of our website. Our users submit properties to our directory. we would like to show how many properties they have listed and what types. I have got this code but it shows all post counts by all users I just want to show their post count so it would be like Residential Properties: 15. This is the code I am using can anyone tell me where I have gone wrong.</p> <pre><code>$term = get_term( 110, 'property_type' ); // WP_Term_Query arguments $args = array( 'taxonomy' =&gt; array( 'property_type' ), 'name' =&gt; array( 'Residential' ), 'slug' =&gt; array( 'residential' ), 'author' =&gt; $userID, 'pad_counts' =&gt; false, 'fields' =&gt; 'count', 'hide_empty' =&gt; true, ); // The Term Query $term_query = new WP_Term_Query( $args ); echo 'Residential Properties: '. $term-&gt;count; </code></pre>
[ { "answer_id": 310109, "author": "Krzysiek Dróżdż", "author_id": 34172, "author_profile": "https://wordpress.stackexchange.com/users/34172", "pm_score": 1, "selected": false, "text": "<p>It's a little bit hard to guess, what are you trying to do exactly, but let me try to answer...</p>\n...
2018/07/31
[ "https://wordpress.stackexchange.com/questions/310101", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/147857/" ]
I am developing a section on the front of our website. Our users submit properties to our directory. we would like to show how many properties they have listed and what types. I have got this code but it shows all post counts by all users I just want to show their post count so it would be like Residential Properties: 15. This is the code I am using can anyone tell me where I have gone wrong. ``` $term = get_term( 110, 'property_type' ); // WP_Term_Query arguments $args = array( 'taxonomy' => array( 'property_type' ), 'name' => array( 'Residential' ), 'slug' => array( 'residential' ), 'author' => $userID, 'pad_counts' => false, 'fields' => 'count', 'hide_empty' => true, ); // The Term Query $term_query = new WP_Term_Query( $args ); echo 'Residential Properties: '. $term->count; ```
It's a little bit hard to guess, what are you trying to do exactly, but let me try to answer... My best guess is that you want to tell, how many properties has given user published in given property type. So first - why your code doesn't work... ---------------------------------------- `get_term` will get the term info and there is no user context in it, so it will get count of all posts published in this term... So this won't help you. `WP_Term_Query` is almost the same function. And, if you'll take a look at [its reference](https://developer.wordpress.org/reference/classes/wp_term_query/__construct/), then you'll notice, that there is no `author` param. So it also won't help you. **Why is it so?** Because these functions are getting terms info and terms don't have authors... So how to get the count of posts in given term authored by given user? ---------------------------------------------------------------------- The easiest ways will be to use WP\_Query and use its `found_posts` field (which stores the total number of posts found matching the current query parameters)... ``` $posts = new WP_Query( array( 'author' => $userID, 'post_type' => 'property', // I'm guessing that is your post type 'tax_query' => array( // here goes your taxonomy query array( 'taxonomy' => 'property_type', 'field' => 'slug', 'terms' => 'residential' ), ), 'fields' => 'ids', // we don't need content of posts 'posts_per_page' => 1, // We don't need to get these posts ) ); echo 'Residential Properties: '. $posts->found_posts; ```
310,126
<p>i need to Delete wp_terms -> name field when a user is delete .</p> <p>my requirement is admin needs to assign posts to specific users, that is admin need to add a post to user1 ,but user2 should not see that.for this i created a custom post and add taxonomy for that.And the terms are users Usernames .so i need to list the usernames of the users as terms in the taxonomy.when a new user is registered his username should updated in the wp_terms table also,so i will get the usernames as terms. this is working well ,now i need to delete the term from taxonomy when the user is removed.</p> <p>i stucked here .please suggest some solution for this</p> <p>what i have done is</p> <pre><code>add_action( 'delete_user', 'yg_user_delete', 10, 1 ); function yg_user_delete( $user_id ) { $user_info = get_userdata($user_id); $user_name = $user_info-&gt;user_login; wp_delete_term( $user_name, 'user1', array() ); } </code></pre> <p>here 'user1' is my taxonomy</p>
[ { "answer_id": 310128, "author": "Andrea Somovigo", "author_id": 64435, "author_profile": "https://wordpress.stackexchange.com/users/64435", "pm_score": 1, "selected": false, "text": "<p>If I understand well you have a <code>custom_taxonomy</code> and the terms slugs of it correspond to...
2018/08/01
[ "https://wordpress.stackexchange.com/questions/310126", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/143452/" ]
i need to Delete wp\_terms -> name field when a user is delete . my requirement is admin needs to assign posts to specific users, that is admin need to add a post to user1 ,but user2 should not see that.for this i created a custom post and add taxonomy for that.And the terms are users Usernames .so i need to list the usernames of the users as terms in the taxonomy.when a new user is registered his username should updated in the wp\_terms table also,so i will get the usernames as terms. this is working well ,now i need to delete the term from taxonomy when the user is removed. i stucked here .please suggest some solution for this what i have done is ``` add_action( 'delete_user', 'yg_user_delete', 10, 1 ); function yg_user_delete( $user_id ) { $user_info = get_userdata($user_id); $user_name = $user_info->user_login; wp_delete_term( $user_name, 'user1', array() ); } ``` here 'user1' is my taxonomy
Replace this with yours: ``` add_action( 'delete_user', 'yg_user_delete', 10, 1 ); function yg_user_delete( $user_id ) { $user_info = get_userdata($user_id); $user_name = $user_info->user_login; print_r($user_info); wp_delete_term( get_term_by('name', $user_name, 'user1')->term_id, 'user1', array() ); } ```
310,127
<p>I have a user registration form implemented and working correctly on the front end of a website. My main issue is that I would like to redirect a user after completing the profile form. </p> <p>My idea would be to show a page with some content to let the user know that their account is being reviewed. So this kind of users will have a new role called "members-in-approval" and once the admin reviews their profile and approve them, they would get the role "active member".</p> <p>Everything is working fine right now but I cannot redirect them to the page I mention before after completing the profile.</p> <p>I'm pretty new using WP so any help or advice would be appreciated. Thanks!</p>
[ { "answer_id": 310128, "author": "Andrea Somovigo", "author_id": 64435, "author_profile": "https://wordpress.stackexchange.com/users/64435", "pm_score": 1, "selected": false, "text": "<p>If I understand well you have a <code>custom_taxonomy</code> and the terms slugs of it correspond to...
2018/08/01
[ "https://wordpress.stackexchange.com/questions/310127", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/147869/" ]
I have a user registration form implemented and working correctly on the front end of a website. My main issue is that I would like to redirect a user after completing the profile form. My idea would be to show a page with some content to let the user know that their account is being reviewed. So this kind of users will have a new role called "members-in-approval" and once the admin reviews their profile and approve them, they would get the role "active member". Everything is working fine right now but I cannot redirect them to the page I mention before after completing the profile. I'm pretty new using WP so any help or advice would be appreciated. Thanks!
Replace this with yours: ``` add_action( 'delete_user', 'yg_user_delete', 10, 1 ); function yg_user_delete( $user_id ) { $user_info = get_userdata($user_id); $user_name = $user_info->user_login; print_r($user_info); wp_delete_term( get_term_by('name', $user_name, 'user1')->term_id, 'user1', array() ); } ```
310,138
<pre><code> &lt;?php wp_nav_menu(array( 'theme_location' =&gt; 'primary', 'container' =&gt; 'ul', 'menu_class'=&gt; 'top-menu' /* 'walker' =&gt; new Walker_nav_Primary() */ ) ); ?&gt; </code></pre> <p>This is a simple wp_nav_menu </p> <p><a href="https://i.stack.imgur.com/ElDeP.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/ElDeP.png" alt="enter image description here"></a></p> <p>You can see ascending order from above example </p> <p>I have done this in WP. </p> <p><a href="https://i.stack.imgur.com/Z05LZ.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Z05LZ.png" alt="enter image description here"></a> </p> <p>wp_nav_menu gives me ascending order menu. How can I arrange as dashboard?</p> <p>Please help.</p>
[ { "answer_id": 310134, "author": "Siavash1991", "author_id": 35070, "author_profile": "https://wordpress.stackexchange.com/users/35070", "pm_score": 0, "selected": false, "text": "<p>Replace this with your search form and products will show in results:</p>\n\n<pre><code> &lt;form method=...
2018/08/01
[ "https://wordpress.stackexchange.com/questions/310138", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/-1/" ]
``` <?php wp_nav_menu(array( 'theme_location' => 'primary', 'container' => 'ul', 'menu_class'=> 'top-menu' /* 'walker' => new Walker_nav_Primary() */ ) ); ?> ``` This is a simple wp\_nav\_menu [![enter image description here](https://i.stack.imgur.com/ElDeP.png)](https://i.stack.imgur.com/ElDeP.png) You can see ascending order from above example I have done this in WP. [![enter image description here](https://i.stack.imgur.com/Z05LZ.png)](https://i.stack.imgur.com/Z05LZ.png) wp\_nav\_menu gives me ascending order menu. How can I arrange as dashboard? Please help.
You have in your query `WHERE p.post_type IN ('post', 'page')`, that is why it shows only the posts and pages. Add post type **product** to query: `WHERE p.post_type IN ('post', 'page', 'product')`
310,165
<p>I am creating a custom user role with the code below in functions.php, however WordPress only allows the user to create draft pages, they can't then edit draft pages or publish pages even though I have set the capabilities to true?</p> <p>Any help is much appreciated!. Thanks in advance.</p> <pre><code>add_action('admin_init', 'user_custom_roles'); function user_custom_roles() { add_role( 'editor_limited', 'Editor Limited', array( 'read' =&gt; true, 'edit_pages' =&gt; true, 'edit_posts' =&gt; true, 'edit_published_pages' =&gt; true, 'edit_published_posts' =&gt; true, 'edit_others_pages' =&gt; true, 'edit_others_posts' =&gt; true, 'publish_pages' =&gt; true, 'publish_posts' =&gt; true, 'upload_files' =&gt; true, 'unfiltered_html' =&gt; true ) ); } </code></pre>
[ { "answer_id": 310134, "author": "Siavash1991", "author_id": 35070, "author_profile": "https://wordpress.stackexchange.com/users/35070", "pm_score": 0, "selected": false, "text": "<p>Replace this with your search form and products will show in results:</p>\n\n<pre><code> &lt;form method=...
2018/08/01
[ "https://wordpress.stackexchange.com/questions/310165", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/116154/" ]
I am creating a custom user role with the code below in functions.php, however WordPress only allows the user to create draft pages, they can't then edit draft pages or publish pages even though I have set the capabilities to true? Any help is much appreciated!. Thanks in advance. ``` add_action('admin_init', 'user_custom_roles'); function user_custom_roles() { add_role( 'editor_limited', 'Editor Limited', array( 'read' => true, 'edit_pages' => true, 'edit_posts' => true, 'edit_published_pages' => true, 'edit_published_posts' => true, 'edit_others_pages' => true, 'edit_others_posts' => true, 'publish_pages' => true, 'publish_posts' => true, 'upload_files' => true, 'unfiltered_html' => true ) ); } ```
You have in your query `WHERE p.post_type IN ('post', 'page')`, that is why it shows only the posts and pages. Add post type **product** to query: `WHERE p.post_type IN ('post', 'page', 'product')`
310,173
<p>I am using <code>woocommerce_admin_order_actions</code> hook to add an additional action like Invoice. But it is repeating many many times whereas others button are repeating once.</p> <pre class="lang-php prettyprint-override"><code>public function add_new_list_for_action($actions, $the_order) { if ( $the_order-&gt;has_status( array( 'processing' ) ) ) { $status = $_GET['status']; $order_id = method_exists($the_order, 'get_id') ? $the_order-&gt;get_id() : $the_order-&gt;id; $actions[] = [&quot;action&quot; =&gt; &quot;invoice&quot;, &quot;url&quot; =&gt; wp_nonce_url(admin_url('admin-ajax.php?action=wip_pdf_generator&amp;status=invoice'.$status.'&amp;order_id=' . $order_id), 'wip_pdf_generator'), &quot;name&quot; =&gt; &quot;Invoice&quot;]; } return $actions; } add_filter( 'woocommerce_admin_order_actions', array($this, 'add_new_list_for_action'),1, 2); </code></pre>
[ { "answer_id": 310175, "author": "VinothRaja", "author_id": 146008, "author_profile": "https://wordpress.stackexchange.com/users/146008", "pm_score": 1, "selected": false, "text": "<p>Add this below code your current active theme functions.php file</p>\n\n<pre><code>add_filter( 'woocomme...
2018/08/01
[ "https://wordpress.stackexchange.com/questions/310173", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/141331/" ]
I am using `woocommerce_admin_order_actions` hook to add an additional action like Invoice. But it is repeating many many times whereas others button are repeating once. ```php public function add_new_list_for_action($actions, $the_order) { if ( $the_order->has_status( array( 'processing' ) ) ) { $status = $_GET['status']; $order_id = method_exists($the_order, 'get_id') ? $the_order->get_id() : $the_order->id; $actions[] = ["action" => "invoice", "url" => wp_nonce_url(admin_url('admin-ajax.php?action=wip_pdf_generator&status=invoice'.$status.'&order_id=' . $order_id), 'wip_pdf_generator'), "name" => "Invoice"]; } return $actions; } add_filter( 'woocommerce_admin_order_actions', array($this, 'add_new_list_for_action'),1, 2); ```
Add this below code your current active theme functions.php file ``` add_filter( 'woocommerce_admin_order_actions', 'add_custom_order_status_actions_button', 100, 2 ); function add_custom_order_status_actions_button( $actions, $order ) { if ( $order->has_status( array( 'processing' ) ) ) { // The key slug defined for your action button $action_slug = 'invoice'; $status = $_GET['status']; $order_id = method_exists($the_order, 'get_id') ? $the_order->get_id() : $the_order->id; // Set the action button $actions[$action_slug] = array( 'url' => wp_nonce_url(admin_url('admin-ajax.php?action=wip_pdf_generator&status=invoice'.$status.'&order_id=' . $order_id), 'wip_pdf_generator'), 'name' => __( 'Invoice', 'woocommerce' ), 'action' => $action_slug, ); } return $actions; } add_action( 'admin_head', 'add_custom_order_status_actions_button_css' ); function add_custom_order_status_actions_button_css() { $action_slug = "invoice"; // The key slug defined for your action button echo '<style>.wc-action-button-'.$action_slug.'::after { font-family: woocommerce !important; content: "\e029" !important; }</style>'; } ``` [![enter image description here](https://i.stack.imgur.com/1GTMe.png)](https://i.stack.imgur.com/1GTMe.png)
310,201
<p>Simple task, but it isn't working:</p> <pre><code>&lt;?php $content = apply_filters( 'the_content', get_the_content() ); $contentWithoutHTML = wp_strip_all_tags($content); $pos = strpos($contentWithoutHTML, " ", 100); $contentFinal = substr($contentWithoutHTML,0,$pos ); echo $contentFinal . "..."; ?&gt; </code></pre> <p>My post is way over 100 characters long (with spaces), and yet I get <code>strpos(): Offset not contained in string</code> error, which leads me to believe it isn't actually pulling the entire content string. But I applied filters like I believe I should... please assist. Also sometimes even if I get no offset error I just get <code>...</code> even though again, over 100 characters with spaces... although sometimes it works. Why the inconsistency?</p> <p>This is in a <code>WP_Query</code> loop in which most of them work, but some of them do not... so I am pretty sure it is being fed a string because I see it happening to the other posts in the loop...</p> <p>Full Loop:</p> <pre><code>&lt;?php $args = array( 'orderby' =&gt; 'ID', 'order' =&gt; 'ASC', 'posts_per_page' =&gt; 7, 'meta_query' =&gt; array( array( 'key' =&gt; '_thumbnail_id' ) ) ); $query = new WP_Query($args); while ($query-&gt;have_posts()): $query-&gt;the_post(); ?&gt; &lt;div class="articleboxs boxs"&gt; &lt;div class="col-sm-4 noleft"&gt; &lt;div class="aricleleft boxs"&gt; &lt;?php the_post_thumbnail('medium', array( 'class' =&gt; 'img-responsive' )) ?&gt; &lt;/div&gt; &lt;/div&gt; &lt;div class="col-sm-8 noright"&gt; &lt;div class="aricleright boxs"&gt; &lt;div class="boxs"&gt; &lt;a href="&lt;?php echo get_permalink(); ?&gt;"&gt;&lt;h2 class="heading font_Libre"&gt;&lt;?php the_title(); ?&gt;&lt;/h2&gt;&lt;/a&gt; &lt;?php $content = apply_filters('the_content', get_the_content('', true)); print_r($content); $contentWithoutHTML = wp_strip_all_tags($content); $pos = strpos($contentWithoutHTML, " ", 100); $contentFinal = substr($contentWithoutHTML, 0, $pos); ?&gt; &lt;p class="font_Roboto"&gt;&lt;?php echo $contentFinal . "..."; ?&gt;&lt;/p&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;?php endwhile; wp_reset_postdata(); ?&gt; </code></pre>
[ { "answer_id": 310177, "author": "Martin Jarvis", "author_id": 147693, "author_profile": "https://wordpress.stackexchange.com/users/147693", "pm_score": 2, "selected": true, "text": "<p>If you want all of the product meta to be styled in the same way, then add the following to your theme...
2018/08/01
[ "https://wordpress.stackexchange.com/questions/310201", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/77764/" ]
Simple task, but it isn't working: ``` <?php $content = apply_filters( 'the_content', get_the_content() ); $contentWithoutHTML = wp_strip_all_tags($content); $pos = strpos($contentWithoutHTML, " ", 100); $contentFinal = substr($contentWithoutHTML,0,$pos ); echo $contentFinal . "..."; ?> ``` My post is way over 100 characters long (with spaces), and yet I get `strpos(): Offset not contained in string` error, which leads me to believe it isn't actually pulling the entire content string. But I applied filters like I believe I should... please assist. Also sometimes even if I get no offset error I just get `...` even though again, over 100 characters with spaces... although sometimes it works. Why the inconsistency? This is in a `WP_Query` loop in which most of them work, but some of them do not... so I am pretty sure it is being fed a string because I see it happening to the other posts in the loop... Full Loop: ``` <?php $args = array( 'orderby' => 'ID', 'order' => 'ASC', 'posts_per_page' => 7, 'meta_query' => array( array( 'key' => '_thumbnail_id' ) ) ); $query = new WP_Query($args); while ($query->have_posts()): $query->the_post(); ?> <div class="articleboxs boxs"> <div class="col-sm-4 noleft"> <div class="aricleleft boxs"> <?php the_post_thumbnail('medium', array( 'class' => 'img-responsive' )) ?> </div> </div> <div class="col-sm-8 noright"> <div class="aricleright boxs"> <div class="boxs"> <a href="<?php echo get_permalink(); ?>"><h2 class="heading font_Libre"><?php the_title(); ?></h2></a> <?php $content = apply_filters('the_content', get_the_content('', true)); print_r($content); $contentWithoutHTML = wp_strip_all_tags($content); $pos = strpos($contentWithoutHTML, " ", 100); $contentFinal = substr($contentWithoutHTML, 0, $pos); ?> <p class="font_Roboto"><?php echo $contentFinal . "..."; ?></p> </div> </div> </div> </div> <?php endwhile; wp_reset_postdata(); ?> ```
If you want all of the product meta to be styled in the same way, then add the following to your theme custom CSS or style.css in your child theme, and edit as required... .product\_meta { padding-top: 6px; border-top: 1px solid #dadada; color: #666; font-size: 18px; } If you want something different for each of the product meta elements, then you would add something like the following... .sku\_wrapper { padding-top: 6px; border-top: 1px solid #dadada; color: #666; font-size: 18px; } and .posted\_in { padding-top: 6px; border-top: 1px solid #dadada; color: #666; font-size: 18px; }
310,213
<p>I have a very simple plugin with a javascript file and a PHP file. I want to call the PHP file from my javascript code and get the output. The javascript functions is something like the following:</p> <pre><code>function img_upload(){ var ajax = new XMLHttpRequest(); ajax.open('GET', 'http://My_Domain_Name.com/wp-content/plugins/My_Plugin/auth.php', false); ajax.send(); if (ajax.status === 200) { console.log(ajax.responseText); } </code></pre> <p>and the PHP file which returns the results:</p> <pre><code>&lt;?php $token=Get_Token(); echo $token; function Get_Token() { //Do some stuff return $token; } ?&gt; </code></pre> <p>both files (auth.php and myjs.js) are in the root directory of the plugin.</p> <pre><code>/home/My_Username/public_html/wp-content/plugins/My_Plugin </code></pre> <p>If I use the domain name I can call the php file in ajax.open() and get the results, but I know this is not the right way to do that. How can I call the php file inside my javascrip code via ajax.open('path_to_php') in Wordpress properly without indicating the domain name?</p>
[ { "answer_id": 310215, "author": "Adam Mellen", "author_id": 147913, "author_profile": "https://wordpress.stackexchange.com/users/147913", "pm_score": -1, "selected": false, "text": "<p>Use <code>plugins_url()</code> to get the location of <code>site/wp-content/plugins</code>:</p>\n\n<pr...
2018/08/01
[ "https://wordpress.stackexchange.com/questions/310213", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/122813/" ]
I have a very simple plugin with a javascript file and a PHP file. I want to call the PHP file from my javascript code and get the output. The javascript functions is something like the following: ``` function img_upload(){ var ajax = new XMLHttpRequest(); ajax.open('GET', 'http://My_Domain_Name.com/wp-content/plugins/My_Plugin/auth.php', false); ajax.send(); if (ajax.status === 200) { console.log(ajax.responseText); } ``` and the PHP file which returns the results: ``` <?php $token=Get_Token(); echo $token; function Get_Token() { //Do some stuff return $token; } ?> ``` both files (auth.php and myjs.js) are in the root directory of the plugin. ``` /home/My_Username/public_html/wp-content/plugins/My_Plugin ``` If I use the domain name I can call the php file in ajax.open() and get the results, but I know this is not the right way to do that. How can I call the php file inside my javascrip code via ajax.open('path\_to\_php') in Wordpress properly without indicating the domain name?
Here's an example: Use this sample JavaScript code: ``` jQuery(document).on('click', '.some-element', function(e){ var ipc = jQuery(this).data('collection-id'); jQuery('.some-other-element').show(); jQuery.ajax({ method: 'post', url: ipAjaxVar.ajaxurl, data: { collection_id: ipc, action: 'my_function', } }).done(function(msg) { // Do something when done }); e.preventDefault(); }); ``` PHP (include the function in your plugin, do not use a separate file): ``` // Include the JavaScript above in your plugin wp_enqueue_script('main', plugins_url('js/jquery.main.js', __FILE__), array('jquery'), '', true); wp_localize_script('main', 'ipAjaxVar', array( 'ajaxurl' => admin_url('admin-ajax.php') )); add_action('wp_ajax_my_function', 'my_function'); ``` **UPDATE:** Add the PHP code to your main plugin file. Create a JavaScript file - `js/jquery.main.js` - and add the code above. That should do the trick.
310,214
<p>I have 2 custom post types, <code>project</code> and <code>person</code>. Both have several custom fields. I'm working on a template for the <code>project</code> custom post type.</p> <p>In the <code>project</code> custom fields I have several fields of type relation, as seen in this screenshot. Unfortunately I don't really undestand what they mean and how to use them, but that is not my main question.<a href="https://i.stack.imgur.com/sEPPx.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/sEPPx.png" alt="enter image description here"></a></p> <p>Next, inside the <code>person</code> custom fields, I have only text fields, like <code>first_name</code>, <code>last_name</code>, etc.</p> <p>Now let's say I have one custom post type of type <code>person</code>. That person has contributed to a project, which is a custom post type of type <code>project</code>. </p> <p>How can I now, when working on the template of the <code>project</code> posts, include an [acf field] shortcode to a custom field of type <code>person</code>?</p> <p>Here is a screenshot/concept of what I want to do: Circled in red are information pulled from the <code>project</code> custom fields, whereas circled in blue are information pulled from the <code>person</code> custom fields. <a href="https://i.stack.imgur.com/j0vhJ.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/j0vhJ.png" alt="enter image description here"></a></p> <p>Notes:</p> <ul> <li><p>I'm fairly new to wordpress and have no knowledge in php</p></li> <li><p>Ideally a solution to my problem should not need me to add code to php files as that is not desired by my client. Preferably it should be doable inside the WPBakery template editor.</p> <ul> <li>Installed and usable plugins are ACF, WPBakery, toolset, salient, acf-vc, custom post type UI</li> </ul></li> </ul> <p>Thank you for your help, I hope I succeeded to phrase my problem in an understandable manner.</p> <h2>UPDATE</h2> <p>I found this plugin, which seems to do provide one solution: nested shortcodes: <a href="https://wordpress.org/plugins/nested-shortcodes/" rel="nofollow noreferrer">https://wordpress.org/plugins/nested-shortcodes/</a></p> <p>Unfortunately, it also poses constraints, and has not allowed me to find a solution. What I want to do is this: </p> <p>Input: <code>[acf field="first_name" post_id=[acf field="student"]]</code></p> <p>With the expected output being: <code>John Doe</code></p> <p>Unfortunately the output I get is: <code>]</code></p> <p>Which according to them is partly due to shortcode limitations listed here <a href="https://codex.wordpress.org/Shortcode_API#Limitations" rel="nofollow noreferrer">https://codex.wordpress.org/Shortcode_API#Limitations</a></p> <p>On the other hand, this hardcoded workaround works:</p> <p>Input: <code>[acf field="student"]</code> Output: <code>89</code></p> <p>Input: <code>[acf field="first_name" post_id=89]</code> Output: <code>John Doe</code></p> <p>Unfortunately this workaround has the hardcoded unique ID 89, which makes it thus unable to use as a template for future usage.</p> <p>Does anyone have a solution or better workaround that does not necessite me to hardcode? I'm also open for completely new ideas and directions, as long as it helps me solve this problem</p>
[ { "answer_id": 310215, "author": "Adam Mellen", "author_id": 147913, "author_profile": "https://wordpress.stackexchange.com/users/147913", "pm_score": -1, "selected": false, "text": "<p>Use <code>plugins_url()</code> to get the location of <code>site/wp-content/plugins</code>:</p>\n\n<pr...
2018/08/01
[ "https://wordpress.stackexchange.com/questions/310214", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/147919/" ]
I have 2 custom post types, `project` and `person`. Both have several custom fields. I'm working on a template for the `project` custom post type. In the `project` custom fields I have several fields of type relation, as seen in this screenshot. Unfortunately I don't really undestand what they mean and how to use them, but that is not my main question.[![enter image description here](https://i.stack.imgur.com/sEPPx.png)](https://i.stack.imgur.com/sEPPx.png) Next, inside the `person` custom fields, I have only text fields, like `first_name`, `last_name`, etc. Now let's say I have one custom post type of type `person`. That person has contributed to a project, which is a custom post type of type `project`. How can I now, when working on the template of the `project` posts, include an [acf field] shortcode to a custom field of type `person`? Here is a screenshot/concept of what I want to do: Circled in red are information pulled from the `project` custom fields, whereas circled in blue are information pulled from the `person` custom fields. [![enter image description here](https://i.stack.imgur.com/j0vhJ.png)](https://i.stack.imgur.com/j0vhJ.png) Notes: * I'm fairly new to wordpress and have no knowledge in php * Ideally a solution to my problem should not need me to add code to php files as that is not desired by my client. Preferably it should be doable inside the WPBakery template editor. + Installed and usable plugins are ACF, WPBakery, toolset, salient, acf-vc, custom post type UI Thank you for your help, I hope I succeeded to phrase my problem in an understandable manner. UPDATE ------ I found this plugin, which seems to do provide one solution: nested shortcodes: <https://wordpress.org/plugins/nested-shortcodes/> Unfortunately, it also poses constraints, and has not allowed me to find a solution. What I want to do is this: Input: `[acf field="first_name" post_id=[acf field="student"]]` With the expected output being: `John Doe` Unfortunately the output I get is: `]` Which according to them is partly due to shortcode limitations listed here <https://codex.wordpress.org/Shortcode_API#Limitations> On the other hand, this hardcoded workaround works: Input: `[acf field="student"]` Output: `89` Input: `[acf field="first_name" post_id=89]` Output: `John Doe` Unfortunately this workaround has the hardcoded unique ID 89, which makes it thus unable to use as a template for future usage. Does anyone have a solution or better workaround that does not necessite me to hardcode? I'm also open for completely new ideas and directions, as long as it helps me solve this problem
Here's an example: Use this sample JavaScript code: ``` jQuery(document).on('click', '.some-element', function(e){ var ipc = jQuery(this).data('collection-id'); jQuery('.some-other-element').show(); jQuery.ajax({ method: 'post', url: ipAjaxVar.ajaxurl, data: { collection_id: ipc, action: 'my_function', } }).done(function(msg) { // Do something when done }); e.preventDefault(); }); ``` PHP (include the function in your plugin, do not use a separate file): ``` // Include the JavaScript above in your plugin wp_enqueue_script('main', plugins_url('js/jquery.main.js', __FILE__), array('jquery'), '', true); wp_localize_script('main', 'ipAjaxVar', array( 'ajaxurl' => admin_url('admin-ajax.php') )); add_action('wp_ajax_my_function', 'my_function'); ``` **UPDATE:** Add the PHP code to your main plugin file. Create a JavaScript file - `js/jquery.main.js` - and add the code above. That should do the trick.
310,226
<p>I am using this code and I am not sure why the script is not loaded. I believe the syntax is correct since I am trying to load the script only on the "events" custom post type single posts.</p> <pre><code>add_action( 'login_enqueue_scripts', 'wpse_login_enqueue_scripts', 10 ); function wpse_login_enqueue_scripts() { if( is_single() &amp;&amp; get_post_type()=='events' ){ wp_enqueue_script( 'bootstrap', 'https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js', array('jquery'), '3.3.5', true ); } } </code></pre>
[ { "answer_id": 310227, "author": "Kaperto", "author_id": 147795, "author_profile": "https://wordpress.stackexchange.com/users/147795", "pm_score": 0, "selected": false, "text": "<p>this hook is only fired on the login page :<br>\n<a href=\"https://developer.wordpress.org/reference/hooks/...
2018/08/01
[ "https://wordpress.stackexchange.com/questions/310226", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/40727/" ]
I am using this code and I am not sure why the script is not loaded. I believe the syntax is correct since I am trying to load the script only on the "events" custom post type single posts. ``` add_action( 'login_enqueue_scripts', 'wpse_login_enqueue_scripts', 10 ); function wpse_login_enqueue_scripts() { if( is_single() && get_post_type()=='events' ){ wp_enqueue_script( 'bootstrap', 'https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js', array('jquery'), '3.3.5', true ); } } ```
To enqueue scripts on the front-end, the hook should be `wp_enqueue_scripts`, not `login_enqueue_scripts`. Also, a better way to see if you’re on a single custom post type is to use `is_singular()` and pass the post type you want to check: ``` if ( is_singular( 'events' ) ) { } ``` `get_post_type()` relies on the global `$post` object, and not the main query. They're often the same but under some circumstances the `$post` object might not be the same post as the current single post.
310,243
<p>I used this code for changing the email sender name from Wordpress to my own title.</p> <pre><code>function wpb_sender_email($original_email_address) { return 'info@mydomain.com'; } // Function to change sender name function wpb_sender_name($original_email_from) { return 'mydomain.com'; } // Hooking up our functions to WordPress filters add_filter('wp_mail_from', 'wpb_sender_email'); add_filter('wp_mail_from_name', 'wpb_sender_name'); </code></pre> <p>But it just changes welcome emails. when a user wants to change his/her email, the email notification send by <code>WordPress@mydomain.com</code> So how can I change it too?</p>
[ { "answer_id": 310250, "author": "John Dee", "author_id": 131224, "author_profile": "https://wordpress.stackexchange.com/users/131224", "pm_score": 2, "selected": false, "text": "<p>As of version 4.9 there is a dubious \"feature\" that prevents you from changing the site email without a ...
2018/08/01
[ "https://wordpress.stackexchange.com/questions/310243", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/141105/" ]
I used this code for changing the email sender name from Wordpress to my own title. ``` function wpb_sender_email($original_email_address) { return 'info@mydomain.com'; } // Function to change sender name function wpb_sender_name($original_email_from) { return 'mydomain.com'; } // Hooking up our functions to WordPress filters add_filter('wp_mail_from', 'wpb_sender_email'); add_filter('wp_mail_from_name', 'wpb_sender_name'); ``` But it just changes welcome emails. when a user wants to change his/her email, the email notification send by `WordPress@mydomain.com` So how can I change it too?
As of version 4.9 there is a dubious "feature" that prevents you from changing the site email without a confirmation email going out, and the admin confirming his own change. Those filters, as you've discovered, won't work. For instance, from now on, if you're using WordPress for an IOT device or on localhost, it's impossible for an admin to change the site admin address on a single site. You'll have to remove the new hooks, and plop in your own. I put a plugin on the .org repo that does this. You can use that and just put your own values in. <https://wordpress.org/plugins/change-admin-email-setting-without-outbound-email/> Here is the code on Github: <https://github.com/JohnDeeBDD/change-admin-email/blob/master/change-admin-email.php>
310,264
<p>I have <code>process_ipn</code> method that runs on <code>init</code> action hook. Looks like it is fired after PayPal returns to merchant. Under this method, I could find out the payment status such as <code>completed</code>, <code>pending</code>, <code>failed</code> from PayPal. And, save it to the database.</p> <pre><code>update_user_meta( $user_id, 'status', 'completed' ); </code></pre> <p>I am redirecting back to login page from PayPal's return to merchant with added <code>user_id</code> and <code>form_id</code> in return url. I used the <code>login_message</code> filter to override message depending upon payment status.</p> <pre><code>add_filter( 'login_message', array( $this,'custom_login_message' ) ); public function custom_login_message() { $return = base64_decode ( $_GET['wdb_return'] ); $return = explode( '&amp;', $return ); $return = explode( '=', $return[1] ); $user_id = isset( $return[1] ) ? $return[1] : -1; if( 'completed' === get_user_meta( $user_id, 'status', true ) ) { return print_notice( __( 'Payment Completed. Now login.','wdp' ) ); } else { return print_notice( __( 'Payment Failed','wdp' ) ); } } </code></pre> <p>The return to merchant will return to login page. The problem the status is updated too late after the login page appears. So, <code>Payment Failed</code> appears if I click on return to merchant instantly after payment. If I waited a few minutes after payment and then return to merchant, It's okay.</p> <p>Note that <code>$user_id</code> is grabbed from return url from PayPal and is valid.</p> <p>What could be the solution?</p> <p>Thanks!</p>
[ { "answer_id": 310447, "author": "Sanzeeb Aryal", "author_id": 126847, "author_profile": "https://wordpress.stackexchange.com/users/126847", "pm_score": 0, "selected": false, "text": "<p><code>sleep()</code> function can be used to delay the execution.</p>\n\n<pre><code>add_filter( 'logi...
2018/08/02
[ "https://wordpress.stackexchange.com/questions/310264", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/126847/" ]
I have `process_ipn` method that runs on `init` action hook. Looks like it is fired after PayPal returns to merchant. Under this method, I could find out the payment status such as `completed`, `pending`, `failed` from PayPal. And, save it to the database. ``` update_user_meta( $user_id, 'status', 'completed' ); ``` I am redirecting back to login page from PayPal's return to merchant with added `user_id` and `form_id` in return url. I used the `login_message` filter to override message depending upon payment status. ``` add_filter( 'login_message', array( $this,'custom_login_message' ) ); public function custom_login_message() { $return = base64_decode ( $_GET['wdb_return'] ); $return = explode( '&', $return ); $return = explode( '=', $return[1] ); $user_id = isset( $return[1] ) ? $return[1] : -1; if( 'completed' === get_user_meta( $user_id, 'status', true ) ) { return print_notice( __( 'Payment Completed. Now login.','wdp' ) ); } else { return print_notice( __( 'Payment Failed','wdp' ) ); } } ``` The return to merchant will return to login page. The problem the status is updated too late after the login page appears. So, `Payment Failed` appears if I click on return to merchant instantly after payment. If I waited a few minutes after payment and then return to merchant, It's okay. Note that `$user_id` is grabbed from return url from PayPal and is valid. What could be the solution? Thanks!
If I understand your question, the race condition you describe between WordPress knowing the transaction was "complete" and the user returning to your site is the problem. Regarding a potential solution, what about changing the way you're approaching this such that this race condition is accepted as a real possibility rather than something that you can avoid? You do mention one of the possible Paypal status is "pending"... Its been years since I've worked with Paypal, but I recall the IPN feed can sometimes lag for quite a while. Suppose you use ajax: you could show the login page with a conditional box, or you could use an interstitial 'transaction processing' page that redirects to the login. Your process could thank your customer, show a throbber animation, and explain that you're processing the transaction / waiting for payment confirmation from Paypal. Your page can keep polling WordPress and when the user's meta `status` is "complete" you can update the user and show them the login form, and if it "failed" you can handle accordingly. I'm not sure if you're setting the Paypal "pending" status in the user meta, but regardless an easy way to trigger this case is by checking for the presence of the `user_id` and `form_id` in the request from Paypal. In cases where IPN is updated quick and/or the user pauses before returning to your site, the 'payment success' case could already work seamlessly as you desire: no need to show any throbbers or anything like that. I think ajax is the best approach. A continuous poll every couple seconds might sound like you're generating a lot of requests, but I doubt you will have scores of users waiting to find out their transaction outcome at any one time. If you do, congratulations, you're making lots of money :) WordPress also has a Heartbeat API but the fastest this can poll is 15 seconds. Web Sockets is another approach but is probably overkill and introduces its own complexities. Here is a tutorial that covers an example implementation: <https://premium.wpmudev.org/blog/using-ajax-with-wordpress/> For a docs reference: <https://developer.wordpress.org/plugins/javascript/ajax/> To have javascript check continuously every few seconds, see `setInterval()` and `setTimeout()`, references: <https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/setInterval> and there's always: <https://www.w3schools.com/js/js_timing.asp> Good luck!
310,298
<p>I want to show HTML text after the short description on the product page, but only on specific products that are in a specific category (categories).</p> <p>I think I have to use in_category, but I can't figure out how to display the text right after the short description.</p> <p>My preference is to work with a function/filter/action.</p> <p>This code works:</p> <pre><code>function filter_woocommerce_short_description( $post_excerpt ) { $your_msg='Test'; return $post_excerpt.'&lt;br&gt;'.$your_msg; }; add_filter( 'woocommerce_short_description','filter_woocommerce_short_description',10, 1 ); </code></pre> <p>But this one works on all product pages..</p>
[ { "answer_id": 310338, "author": "Peter HvD", "author_id": 134918, "author_profile": "https://wordpress.stackexchange.com/users/134918", "pm_score": 3, "selected": true, "text": "<p>Woocommerce's product categories are custom taxonomy terms, so you need to use the taxonomy functions (eg,...
2018/08/02
[ "https://wordpress.stackexchange.com/questions/310298", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/147900/" ]
I want to show HTML text after the short description on the product page, but only on specific products that are in a specific category (categories). I think I have to use in\_category, but I can't figure out how to display the text right after the short description. My preference is to work with a function/filter/action. This code works: ``` function filter_woocommerce_short_description( $post_excerpt ) { $your_msg='Test'; return $post_excerpt.'<br>'.$your_msg; }; add_filter( 'woocommerce_short_description','filter_woocommerce_short_description',10, 1 ); ``` But this one works on all product pages..
Woocommerce's product categories are custom taxonomy terms, so you need to use the taxonomy functions (eg, [`has_term()`](https://codex.wordpress.org/has_term)) rather than WordPress' category ones. ``` function filter_woocommerce_short_description( $post_excerpt ) { global $post; if ( has_term( "term-name", "product_cat", $post->ID ) ) { $post_excerpt .= "<br/>" . "Test"; } return $post_excerpt; }; add_filter( 'woocommerce_short_description','filter_woocommerce_short_description',10, 1 ); ```
310,301
<p>I'm working on a design that has different styling if a certain Gutenberg block is present on a page. In other words, if the first block is a custom built Gutenberg block, the post_title is rendered elsewhere due to design choices made.</p> <p>Is there any function in WordPress to get a list of all Gutenberg blocks present in the post_content?</p>
[ { "answer_id": 310309, "author": "Jebble", "author_id": 81939, "author_profile": "https://wordpress.stackexchange.com/users/81939", "pm_score": 2, "selected": false, "text": "<p>The solution I'm using as of writing check the post_content for the Gutenberg HTML comments. Due to future Gut...
2018/08/02
[ "https://wordpress.stackexchange.com/questions/310301", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/81939/" ]
I'm working on a design that has different styling if a certain Gutenberg block is present on a page. In other words, if the first block is a custom built Gutenberg block, the post\_title is rendered elsewhere due to design choices made. Is there any function in WordPress to get a list of all Gutenberg blocks present in the post\_content?
WordPress 5.0+ has a function for this: `parse_blocks()`. To see if the first block in the post is the Heading block, you'd do this: ``` $post = get_post(); if ( has_blocks( $post->post_content ) ) { $blocks = parse_blocks( $post->post_content ); if ( $blocks[0]['blockName'] === 'core/heading' ) { } } ```
310,304
<p>I have this layout I am trying to implement - <a href="https://drive.google.com/file/d/1cP831xAM1F5CT3HEmedCBkINwiCC18Rb/view" rel="nofollow noreferrer">https://drive.google.com/file/d/1cP831xAM1F5CT3HEmedCBkINwiCC18Rb/view</a></p> <p>And I have created a news template, but I need to get the posts to display like my example where the first bootstrap row displays 3 posts then beneath that it displays 4 posts.</p> <p>Is this possible, I cant seem to find the relevant information for me to achieve this.</p> <p>Really hoping someone can point me in the right direction, on how I would code my template for this layout.</p> <p>Many Thanks</p> <p>Here is my current code</p> <pre><code>&lt;div class="container"&gt; &lt;div class="row"&gt; &lt;?php while ( have_posts() ) { the_post(); $class = 'col-md-4'; if( $counter &lt; 3 ) { $class = 'col-md-3'; } ?&gt; &lt;div class="col-12 &lt;?php echo $class; ?&gt;"&gt; &lt;?php the_post_thumbnail(', '); ?&gt; &lt;h3&gt;&lt;a href="&lt;?php the_permalink(); ?&gt;" title="Read more"&gt;&lt;?php the_title(); ?&gt;&lt;/a&gt;&lt;/h3&gt; &lt;/div&gt; &lt;!-- .col-12 --&gt; &lt;?php $counter++; } // end while ?&gt; &lt;/div&gt;&lt;!-- .row --&gt; &lt;/div&gt;&lt;!-- .container --&gt; </code></pre>
[ { "answer_id": 310310, "author": "Lisa", "author_id": 113452, "author_profile": "https://wordpress.stackexchange.com/users/113452", "pm_score": 0, "selected": false, "text": "<p>try to take a look at this <a href=\"https://stackoverflow.com/questions/38304093/wordpress-blog-first-row-2-c...
2018/08/02
[ "https://wordpress.stackexchange.com/questions/310304", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/147953/" ]
I have this layout I am trying to implement - <https://drive.google.com/file/d/1cP831xAM1F5CT3HEmedCBkINwiCC18Rb/view> And I have created a news template, but I need to get the posts to display like my example where the first bootstrap row displays 3 posts then beneath that it displays 4 posts. Is this possible, I cant seem to find the relevant information for me to achieve this. Really hoping someone can point me in the right direction, on how I would code my template for this layout. Many Thanks Here is my current code ``` <div class="container"> <div class="row"> <?php while ( have_posts() ) { the_post(); $class = 'col-md-4'; if( $counter < 3 ) { $class = 'col-md-3'; } ?> <div class="col-12 <?php echo $class; ?>"> <?php the_post_thumbnail(', '); ?> <h3><a href="<?php the_permalink(); ?>" title="Read more"><?php the_title(); ?></a></h3> </div> <!-- .col-12 --> <?php $counter++; } // end while ?> </div><!-- .row --> </div><!-- .container --> ```
You can accomplish this by using a counter then updating the class according to your needs. The code below will create a variable `$counter` and assign it to `0` if posts exist. By default a `'col-md-4'` is bound to `$class`, if the `$counter` is less than `3` `$class` will be updated to `'col-md-3'` (making it fill 4 columns instead of 3). Then we output the html including the stored class. Finally, the `$counter` is incremented ready for the next post item. ``` <?php if ( have_posts() ) { $counter = 0; ?> <div class="container"> <div class="row"> <?php while ( have_posts() ) { the_post(); $class = 'col-md-4'; if( $counter < 3 ) { $class = 'col-md-3'; } ?> <div class="col-12 <?php echo $class; ?>"> <?php // content etc here ?> </div> <!-- .col-12 --> <?php $counter++; } // end while ?> </div><!-- .row --> </div><!-- .container --> <?php } else { // end if ?> <p>There are no posts to display</p> <?php } ?> ```
310,333
<p>When I click the "Add to cart" button on a variable product, with no variation selected, the WooCommerce pops up an alert: "Please select some product options before adding this product to your cart.".</p> <p>The problem is, it shows up as an Alert (browser window with Ok button). I would like to display it as a classic WooCommerce notice box within the page (or possibly to do some custom actions), but I am unable to find the responsible actions. </p> <p>I tried to look for "single_add_to_cart_button". The theme is Shopkeeper, but I've looked for other themes and they seem to display it in the same manner - so I believe it is WooCommerce's default.</p> <p>Any hints on how to achieve this?</p>
[ { "answer_id": 310310, "author": "Lisa", "author_id": 113452, "author_profile": "https://wordpress.stackexchange.com/users/113452", "pm_score": 0, "selected": false, "text": "<p>try to take a look at this <a href=\"https://stackoverflow.com/questions/38304093/wordpress-blog-first-row-2-c...
2018/08/02
[ "https://wordpress.stackexchange.com/questions/310333", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/138610/" ]
When I click the "Add to cart" button on a variable product, with no variation selected, the WooCommerce pops up an alert: "Please select some product options before adding this product to your cart.". The problem is, it shows up as an Alert (browser window with Ok button). I would like to display it as a classic WooCommerce notice box within the page (or possibly to do some custom actions), but I am unable to find the responsible actions. I tried to look for "single\_add\_to\_cart\_button". The theme is Shopkeeper, but I've looked for other themes and they seem to display it in the same manner - so I believe it is WooCommerce's default. Any hints on how to achieve this?
You can accomplish this by using a counter then updating the class according to your needs. The code below will create a variable `$counter` and assign it to `0` if posts exist. By default a `'col-md-4'` is bound to `$class`, if the `$counter` is less than `3` `$class` will be updated to `'col-md-3'` (making it fill 4 columns instead of 3). Then we output the html including the stored class. Finally, the `$counter` is incremented ready for the next post item. ``` <?php if ( have_posts() ) { $counter = 0; ?> <div class="container"> <div class="row"> <?php while ( have_posts() ) { the_post(); $class = 'col-md-4'; if( $counter < 3 ) { $class = 'col-md-3'; } ?> <div class="col-12 <?php echo $class; ?>"> <?php // content etc here ?> </div> <!-- .col-12 --> <?php $counter++; } // end while ?> </div><!-- .row --> </div><!-- .container --> <?php } else { // end if ?> <p>There are no posts to display</p> <?php } ?> ```
310,360
<p>I've read alot, I've tried a bunch of different things, I still can't get my query to order posts by acf's datepicker field. This is what my code looks like:</p> <pre><code>$args = array( 'post_type' =&gt; 'arm_careers', 'post_status' =&gt; 'publish', 'posts_per_page' =&gt; -1, 'meta_key' =&gt; 'post_date', 'orderby' =&gt; 'meta_value_num', 'meta_type' =&gt; 'DATE', 'order' =&gt; 'ASC', ); </code></pre> <p>I'm not using PRO, I'm using the free one. The save format is <code>yymmdd</code>, I've also tried <code>YYYYMMDD</code> but neither worked.</p> <p>Here is what it currently looks like: August 14, 2018 August 2, 2018 August 9, 2018</p> <p>when I want it to look like: August 2, 2018 August 9, 2018 August 14, 2018</p> <p>The display format is <code>MM d, yy</code>.</p>
[ { "answer_id": 310361, "author": "Nicholas Koskowski", "author_id": 92318, "author_profile": "https://wordpress.stackexchange.com/users/92318", "pm_score": 2, "selected": false, "text": "<p>You need to convert your saved format to the post_date format which is in </p>\n\n<p><code>Y-m-d H...
2018/08/02
[ "https://wordpress.stackexchange.com/questions/310360", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/138558/" ]
I've read alot, I've tried a bunch of different things, I still can't get my query to order posts by acf's datepicker field. This is what my code looks like: ``` $args = array( 'post_type' => 'arm_careers', 'post_status' => 'publish', 'posts_per_page' => -1, 'meta_key' => 'post_date', 'orderby' => 'meta_value_num', 'meta_type' => 'DATE', 'order' => 'ASC', ); ``` I'm not using PRO, I'm using the free one. The save format is `yymmdd`, I've also tried `YYYYMMDD` but neither worked. Here is what it currently looks like: August 14, 2018 August 2, 2018 August 9, 2018 when I want it to look like: August 2, 2018 August 9, 2018 August 14, 2018 The display format is `MM d, yy`.
You need to convert your saved format to the post\_date format which is in `Y-m-d H:i:s` Only then will the comparators work properly with automatically generated query objects.
310,393
<p>I am trying to build a plugin and at the moment my plugin contains only <code>plugin.php</code> file.</p> <p>There is not a real code in it yet:</p> <pre><code>&lt;? /* Plugin Name: Plugin Name Plugin URI: https://www.example.info description: A description about the plugin Version: 1.0.0 Author: Author Name Author URI: https://www.example.info License: GPL2 */ </code></pre> <p>And I am getting these errors as long as the plugin is activated:</p> <blockquote> <p>Warning: session_start(): Cannot send session cache limiter - headers already sent - (output started at /home1/website/public_html/wp-content/plugins/plugin-name/plugin-name.php:1) in /home1/website/public_html/wp-content/plugins/flexible-shipping/classes/flexible-shipping-plugin.php on line 169</p> <p>Warning: Cannot modify header information - headers already sent by (output started at /home1/website/public_html/wp-content/plugins/plugin-name/plugin-name.php:1) in /home1/website/public_html/wp-admin/includes/misc.php on line 1124</p> </blockquote> <p>I already faced an issue like this and it was due to whitespaces, but I don't have any whitespaces this time... I barely have a plugin...</p> <p>Thanks.</p>
[ { "answer_id": 310401, "author": "Kaperto", "author_id": 147795, "author_profile": "https://wordpress.stackexchange.com/users/147795", "pm_score": 0, "selected": false, "text": "<p>You start the PHP code with short tags <code>&lt;?</code>.<br>\nIf it is on a server with short tags disabl...
2018/08/03
[ "https://wordpress.stackexchange.com/questions/310393", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/147331/" ]
I am trying to build a plugin and at the moment my plugin contains only `plugin.php` file. There is not a real code in it yet: ``` <? /* Plugin Name: Plugin Name Plugin URI: https://www.example.info description: A description about the plugin Version: 1.0.0 Author: Author Name Author URI: https://www.example.info License: GPL2 */ ``` And I am getting these errors as long as the plugin is activated: > > Warning: session\_start(): Cannot send session cache limiter - headers > already sent - (output started at > /home1/website/public\_html/wp-content/plugins/plugin-name/plugin-name.php:1) > in > /home1/website/public\_html/wp-content/plugins/flexible-shipping/classes/flexible-shipping-plugin.php > on line 169 > > > Warning: Cannot modify header information - headers already sent by > (output started at > /home1/website/public\_html/wp-content/plugins/plugin-name/plugin-name.php:1) > in /home1/website/public\_html/wp-admin/includes/misc.php on line 1124 > > > I already faced an issue like this and it was due to whitespaces, but I don't have any whitespaces this time... I barely have a plugin... Thanks.
You start the PHP code with short tags `<?`. If it is on a server with short tags disabled, the PHP code is not rendered and is outputted. Then it's better to use complete tags `<?php`.
310,394
<p>I want to get posts of a specific date, I tried the following code but I did not get the result what I wanted.</p> <pre><code>&lt;?php $mil = 1532996880000; $seconds = $mil / 1000; $dt = date( "Y-m-d", $seconds ); $post_by_date = $wpdb-&gt;get_row(" SELECT * FROM {$wpdb-&gt;posts} WHERE post_date = $dt AND post_status = 'publish' "); </code></pre> <p><strong>WP QUERY</strong></p> <pre><code>$posts = get_posts(array( 'post_type' =&gt; 'post', 'date' =&gt; $dt, 'posts_per_page' =&gt; 1 )); </code></pre> <hr> <p>This did not work because, the output of <code>$dt = 2018-07-31</code>, but the output shows no results. Because it compares with <code>2018-07-31 09:09:40</code>. So is there any way to get posts of a specific date?</p>
[ { "answer_id": 310396, "author": "Trilok", "author_id": 145962, "author_profile": "https://wordpress.stackexchange.com/users/145962", "pm_score": 1, "selected": false, "text": "<blockquote>\n <p>Please use date query for that also use below code hope it will work for you</p>\n</blockquo...
2018/08/03
[ "https://wordpress.stackexchange.com/questions/310394", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/129128/" ]
I want to get posts of a specific date, I tried the following code but I did not get the result what I wanted. ``` <?php $mil = 1532996880000; $seconds = $mil / 1000; $dt = date( "Y-m-d", $seconds ); $post_by_date = $wpdb->get_row(" SELECT * FROM {$wpdb->posts} WHERE post_date = $dt AND post_status = 'publish' "); ``` **WP QUERY** ``` $posts = get_posts(array( 'post_type' => 'post', 'date' => $dt, 'posts_per_page' => 1 )); ``` --- This did not work because, the output of `$dt = 2018-07-31`, but the output shows no results. Because it compares with `2018-07-31 09:09:40`. So is there any way to get posts of a specific date?
``` <?php // primarily get $year, $month and $day $args = array( 'date_query' => array( 'year' => $year, 'month' => $month, 'day' => $day, ) ); $query = new WP_Query( $args ); if ( $query->have_posts() ) { while ( $query->have_posts() ) { // do whatever here } } ```
310,400
<p>I have an inline SVG tag with an embedded &lt;USE&gt; tag.</p> <p><strong>HTML:</strong></p> <pre><code>&lt;ul&gt; &lt;li&gt;&lt;svg class="icon-user"&gt;&lt;use xlink:href="#icon-user"&gt;&lt;/use&gt;&lt;/svg&gt; My Account&lt;/li&gt; &lt;/ul&gt; </code></pre> <p>I have created a filter function to force the Tiny MCE editor to leave SVG tags alone. The code was adapted from post: <a href="https://wordpress.stackexchange.com/questions/185234/use-of-svg-tag-into-wordpress">use of &lt;svg&gt; tag into wordpress</a>.</p> <p><strong>Filter function:</strong></p> <pre><code>add_filter( 'tiny_mce_before_init', 'fb_tinymce_add_pre' ); function fb_tinymce_add_pre( $initArray ) { // Command separated string of extended elements $ext = 'svg[preserveAspectRatio|class|style|version|viewbox|xmlns],defs,use[xlink:href|x|y],linearGradient[id|x1|y1|z1]'; if ( isset( $initArray['extended_valid_elements'] ) ) { $initArray['extended_valid_elements'] .= ',' . $ext; } else { $initArray['extended_valid_elements'] = $ext; } // maybe; set tiny paramter verify_html //$initArray['verify_html'] = false; return $initArray; } </code></pre> <p>I adapted the posted solution to add SVG CLASS, the USE tag and its XLINK:HREF, X and Y parameters.</p> <p>Problem is the xlink:href parameter is being miss-interpreted resulting in code butchery upon switching to VISUAL mode in the editor.</p> <p><strong>HTML before switch to visual mode:</strong></p> <pre><code> &lt;svg class="icon-user"&gt;&lt;use xlink:href="#icon-user"&gt;&lt;/use&gt;&lt;/svg&gt; </code></pre> <p><strong>HTML after switch to visual mode:</strong></p> <pre><code> &lt;svg class="icon-user"&gt;&lt;use xlink="href"&gt;&lt;/use&gt;&lt;/svg&gt; </code></pre> <p>I have tried escaping the colon in the <code>xlink:href</code> function parameter like this: <code>xlink\:href</code>, tried an encoded value for the colon like this: <code>xlink%3Ahref</code> and using quotes around it like this <code>"xlink:href"</code> but all failed.</p> <p>I know you can embed svg using HTML5 markup, but I would like to try this method if I can get a solution that sticks.</p>
[ { "answer_id": 310426, "author": "TheDeadMedic", "author_id": 1685, "author_profile": "https://wordpress.stackexchange.com/users/1685", "pm_score": 3, "selected": true, "text": "<p>Unfortunately the colon is <a href=\"https://www.tiny.cloud/docs/configure/content-filtering/#valid_element...
2018/08/03
[ "https://wordpress.stackexchange.com/questions/310400", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/148020/" ]
I have an inline SVG tag with an embedded <USE> tag. **HTML:** ``` <ul> <li><svg class="icon-user"><use xlink:href="#icon-user"></use></svg> My Account</li> </ul> ``` I have created a filter function to force the Tiny MCE editor to leave SVG tags alone. The code was adapted from post: [use of <svg> tag into wordpress](https://wordpress.stackexchange.com/questions/185234/use-of-svg-tag-into-wordpress). **Filter function:** ``` add_filter( 'tiny_mce_before_init', 'fb_tinymce_add_pre' ); function fb_tinymce_add_pre( $initArray ) { // Command separated string of extended elements $ext = 'svg[preserveAspectRatio|class|style|version|viewbox|xmlns],defs,use[xlink:href|x|y],linearGradient[id|x1|y1|z1]'; if ( isset( $initArray['extended_valid_elements'] ) ) { $initArray['extended_valid_elements'] .= ',' . $ext; } else { $initArray['extended_valid_elements'] = $ext; } // maybe; set tiny paramter verify_html //$initArray['verify_html'] = false; return $initArray; } ``` I adapted the posted solution to add SVG CLASS, the USE tag and its XLINK:HREF, X and Y parameters. Problem is the xlink:href parameter is being miss-interpreted resulting in code butchery upon switching to VISUAL mode in the editor. **HTML before switch to visual mode:** ``` <svg class="icon-user"><use xlink:href="#icon-user"></use></svg> ``` **HTML after switch to visual mode:** ``` <svg class="icon-user"><use xlink="href"></use></svg> ``` I have tried escaping the colon in the `xlink:href` function parameter like this: `xlink\:href`, tried an encoded value for the colon like this: `xlink%3Ahref` and using quotes around it like this `"xlink:href"` but all failed. I know you can embed svg using HTML5 markup, but I would like to try this method if I can get a solution that sticks.
Unfortunately the colon is [a TinyMCE control character](https://www.tiny.cloud/docs/configure/content-filtering/#valid_elements) > > Forces the attribute to the specified value. For example, 'border:0' > > > ...hence the switch to `xlink=href`. The only apparent solution is the wildcard `use[*]` Use the control character `?` which "separates attribute verification values" i.e. `use[xlink?href]`
310,411
<p>I have a function in my functions.php file that is supossed to update my post status once the expiry date has passed. I call this function in a test.php file that is also a template page with url /test-search-results/. If I access this url via my browser the function fires and does what it supposed to do. </p> <p>I want to create a server side cronjob to do this but I cant seem to get this right. I have contacted my host and they confirm that the path is correct and that the cron is executing si the problem has to be with my script. </p> <p>Can someone please advise what I have to change in my script to have the cronjob execute it.</p> <p>Function in my functions.php file:</p> <pre><code> function expire_posts () { $args = array ( 'post_type' =&gt; 'post', 'meta_key' =&gt; 'Expiry Date', 'meta_value' =&gt; date('Y-m-d'), 'meta_compare' =&gt; '&lt;', ); $query = new WP_Query($args); if( $query-&gt;have_posts() ) : while ( $query-&gt;have_posts() ) : $query-&gt;the_post(); $post_id = get_the_ID(); $post_data = array( 'ID' =&gt; $post_id, 'post_type' =&gt; 'post', 'post_status' =&gt; 'expired', 'post_modified' =&gt; current_time ( 'mysql' ), ); wp_update_post($post_data); endwhile; wp_reset_postdata(); endif; } </code></pre> <p>I call the function in my test.php file like this:</p> <pre><code>expire_posts(); </code></pre> <p>The path my cronjob is following is:</p> <pre><code>/home/userID/public_html/wp-content/themes/twentyseventeen-child/test.php </code></pre> <p>I am hoping someone can shed some light as to why my script isn't executing via the cronjob.</p>
[ { "answer_id": 310430, "author": "Kaperto", "author_id": 147795, "author_profile": "https://wordpress.stackexchange.com/users/147795", "pm_score": 0, "selected": false, "text": "<p>With WP cron, you can launch a action daily, twice daily or hourly :<br>\n<a href=\"https://codex.wordpress...
2018/08/03
[ "https://wordpress.stackexchange.com/questions/310411", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/107025/" ]
I have a function in my functions.php file that is supossed to update my post status once the expiry date has passed. I call this function in a test.php file that is also a template page with url /test-search-results/. If I access this url via my browser the function fires and does what it supposed to do. I want to create a server side cronjob to do this but I cant seem to get this right. I have contacted my host and they confirm that the path is correct and that the cron is executing si the problem has to be with my script. Can someone please advise what I have to change in my script to have the cronjob execute it. Function in my functions.php file: ``` function expire_posts () { $args = array ( 'post_type' => 'post', 'meta_key' => 'Expiry Date', 'meta_value' => date('Y-m-d'), 'meta_compare' => '<', ); $query = new WP_Query($args); if( $query->have_posts() ) : while ( $query->have_posts() ) : $query->the_post(); $post_id = get_the_ID(); $post_data = array( 'ID' => $post_id, 'post_type' => 'post', 'post_status' => 'expired', 'post_modified' => current_time ( 'mysql' ), ); wp_update_post($post_data); endwhile; wp_reset_postdata(); endif; } ``` I call the function in my test.php file like this: ``` expire_posts(); ``` The path my cronjob is following is: ``` /home/userID/public_html/wp-content/themes/twentyseventeen-child/test.php ``` I am hoping someone can shed some light as to why my script isn't executing via the cronjob.
When you use \*nix cron to run a PHP file like that it won't have WordPress loaded. You can load it manually, but a better method is to use WordPress' own [cron API](https://developer.wordpress.org/plugins/cron/). Schedule the event in your `functions.php`: ``` if ( ! wp_next_scheduled( 'expire_posts' ) ) { wp_schedule_event( time(), 'hourly', 'expire_posts' ); } ``` I've used `hourly`, the other available defaults are `daily` & `twicedaily` ([more on scheduling](https://developer.wordpress.org/plugins/cron/understanding-wp-cron-scheduling/)). Now let's hook up your `expire_posts` *function* to our newly created `expire_posts` *event*: ``` add_action( 'expire_posts', 'expire_posts' ); ``` Tada! NB: WordPress cron relies on a request (i.e. a user or bot visiting the site) at least as often as your schedule to run smoothly. If your site is quiet we can use \*nix cron to trigger the WordPress cron API every 15 minutes and let WordPress handle its own internal events. First, disable the default request-based cron behaviour in `wp-config.php`: ``` define( 'DISABLE_WP_CRON', true ); ``` Now set up a \*nix cron to trigger WordPress' cron: ``` /15 * * * wget -q -O - http://yourdomain.com/wp-cron.php?doing_wp_cron ```
310,439
<p>I've created the following pages and hierarchy:</p> <ul> <li>Grandparent <ul> <li>Parent</li> <li>Parent</li> <li>Parent <ul> <li>Child</li> <li>Child</li> <li>Child</li> </ul></li> <li>Parent</li> <li>Parent</li> </ul></li> <li>Grandparent</li> </ul> <p>The Grandparent pages have an ACF custom field to pick the colour. <a href="https://i.stack.imgur.com/2pBfg.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/2pBfg.png" alt="ACF Page Type"></a></p> <p>I'd like that colour selection to be applied for the Grandparent, Parent and Child pages.</p> <p>Within the loop, I've written the following code to grab the Grandparent colour selection:</p> <pre><code>&lt;div class="&lt;?= get_field('colour', $post-&gt;post_parent); ?&gt;"&gt; </code></pre> <p>Let's say I've picked the colour "red".</p> <p>Here's the front-end result:</p> <ul> <li>Grandparent (Red) <ul> <li>Parent (Red)</li> <li>Parent (Red)</li> <li>Parent (Red) <ul> <li>Child (Null)</li> <li>Child (Null)</li> <li>Child (Null)</li> </ul></li> <li>Parent (Red)</li> <li>Parent (Red)</li> </ul></li> <li>Grandparent</li> </ul> <p>The colour is only being applied to the Grandparent and Parent Pages. Child pages are returning no colour (null).</p> <p>How do I include the Child pages too?</p>
[ { "answer_id": 310442, "author": "Jacob Peattie", "author_id": 39152, "author_profile": "https://wordpress.stackexchange.com/users/39152", "pm_score": 3, "selected": true, "text": "<p>As far as I'm aware there's no limit to how many levels of ancestry Pages can have, so any solution shou...
2018/08/03
[ "https://wordpress.stackexchange.com/questions/310439", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/37548/" ]
I've created the following pages and hierarchy: * Grandparent + Parent + Parent + Parent - Child - Child - Child + Parent + Parent * Grandparent The Grandparent pages have an ACF custom field to pick the colour. [![ACF Page Type](https://i.stack.imgur.com/2pBfg.png)](https://i.stack.imgur.com/2pBfg.png) I'd like that colour selection to be applied for the Grandparent, Parent and Child pages. Within the loop, I've written the following code to grab the Grandparent colour selection: ``` <div class="<?= get_field('colour', $post->post_parent); ?>"> ``` Let's say I've picked the colour "red". Here's the front-end result: * Grandparent (Red) + Parent (Red) + Parent (Red) + Parent (Red) - Child (Null) - Child (Null) - Child (Null) + Parent (Red) + Parent (Red) * Grandparent The colour is only being applied to the Grandparent and Parent Pages. Child pages are returning no colour (null). How do I include the Child pages too?
As far as I'm aware there's no limit to how many levels of ancestry Pages can have, so any solution should not depend on specifically referencing a particular ancestor. The best solution would be to get a list of all ancestors for the page and loop over them until you find a value for your field. Then stop looping over them and return the found value. The function `get_post_ancestors()` can be used for this: ``` $colour = null; /** * Get the IDs of the page's ancestors into a list. */ $page_ids = get_post_ancestors( $post ); /** * Put the current page's ID at the beginning of the list so we don't have to * handle it separately. */ array_unshift( $page_ids, $post->ID ); /** * Loop over pages and find the first one with a colour. */ foreach ( $page_ids as $page_id ) { $maybe_colour = get_post_meta( 'colour', $page_id, true ); /** * If the page has a value for colour, put it in the colour variable and * stop the loop. */ if ( $maybe_colour ) { $colour = $maybe_colour; break; } } echo $colour; ``` To save space in your template you could add this to a function and use the function in your template instead: ``` function wpse_310439_get_the_colour( $post = 0 ) { $post = get_post( $post ); $page_ids = get_post_ancestors( $post ); array_unshift( $page_ids, $post->ID ); $colour = null; foreach ( $page_ids as $page_id ) { $maybe_colour = get_post_meta( 'colour', $page_id, true ); if ( $maybe_colour ) { $colour = $maybe_colour; break; } } return $colour; } ``` Then in your template: ``` <div class="<?php echo esc_attr( wpse_310439_get_the_colour() ); ?>"> ```
310,465
<p>I'm trying to unregister core block types in WordPress Gutenberg. </p> <p>I've used the code provided here: <a href="https://github.com/WordPress/gutenberg/blob/master/docs/extensibility/extending-blocks.md#removing-blocks" rel="noreferrer">https://github.com/WordPress/gutenberg/blob/master/docs/extensibility/extending-blocks.md#removing-blocks</a></p> <p>But I can't get it to work. I feel like there may be a simple step I am missing? </p> <ol> <li>I created a plugin which I activated in my WP theme. </li> <li>In my plugin [clore-blocks] folder I created "clore-blocks.php". It contains:</li> </ol> <pre> /** * Remove certain blocks. */ function clore_blacklist_blocks() { wp_enqueue_script( 'clore-blacklist-blocks', plugins_url( 'blocks.js', __FILE__ ), array( 'wp-blocks' ), filemtime( plugin_dir_path( __FILE__ ) . 'blocks.js' ) // Version: filemtime - Gets file modification time. ); } add_action( 'enqueue_block_editor_assets', 'clore_blacklist_blocks' ); </pre> <ol start="3"> <li>In blocks.js I have only: </li> </ol> <pre> wp.blocks.unregisterBlockType( 'core/verse' ); </pre> <p>I thought this would remove the "Verse" block type from being used, but when I go to edit a page with the Gutenberg editor, "Verse" is still there. </p> <p>When I view the page source from the WP edit page, I can see that my "blocks.js" file is being referenced correctly, but It's just not doing anything... or at least not what I want it to do. Do you have any idea why that is?</p>
[ { "answer_id": 311633, "author": "Misha Rudrastyh", "author_id": 85985, "author_profile": "https://wordpress.stackexchange.com/users/85985", "pm_score": 2, "selected": false, "text": "<p>Everything works for me with <code>allowed_block_types</code> hook.</p>\n\n<p>Example:</p>\n\n<pre><c...
2018/08/03
[ "https://wordpress.stackexchange.com/questions/310465", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/148068/" ]
I'm trying to unregister core block types in WordPress Gutenberg. I've used the code provided here: <https://github.com/WordPress/gutenberg/blob/master/docs/extensibility/extending-blocks.md#removing-blocks> But I can't get it to work. I feel like there may be a simple step I am missing? 1. I created a plugin which I activated in my WP theme. 2. In my plugin [clore-blocks] folder I created "clore-blocks.php". It contains: ``` /** * Remove certain blocks. */ function clore_blacklist_blocks() { wp_enqueue_script( 'clore-blacklist-blocks', plugins_url( 'blocks.js', __FILE__ ), array( 'wp-blocks' ), filemtime( plugin_dir_path( __FILE__ ) . 'blocks.js' ) // Version: filemtime - Gets file modification time. ); } add_action( 'enqueue_block_editor_assets', 'clore_blacklist_blocks' ); ``` 3. In blocks.js I have only: ``` wp.blocks.unregisterBlockType( 'core/verse' ); ``` I thought this would remove the "Verse" block type from being used, but when I go to edit a page with the Gutenberg editor, "Verse" is still there. When I view the page source from the WP edit page, I can see that my "blocks.js" file is being referenced correctly, but It's just not doing anything... or at least not what I want it to do. Do you have any idea why that is?
Everything works for me with `allowed_block_types` hook. Example: ``` add_filter( 'allowed_block_types', 'my_function' ); function my_function( $allowed_block_types ) { return array( 'core/paragraph' ); } ``` You can insert the above code to your `functions.php` file to a custom plugin. It removes all blocks except the Paragraph block. More examples here <https://rudrastyh.com/gutenberg/remove-default-blocks.html>
310,508
<p>I have a radio control in the theme customizer. The code for that control is like below:</p> <pre><code>$wp_customize-&gt;add_setting( 'post_layout', array( 'capability' =&gt; 'edit_theme_options', 'default' =&gt; 'cover', 'sanitize_callback' =&gt; 'sanitize_text_field', ) ); $wp_customize-&gt;add_control( 'post_layout', array( 'type' =&gt; 'radio', 'section' =&gt; 'post_options', 'label' =&gt; __( 'Post Layout', 'mytheme' ), 'choices' =&gt; array( 'cover' =&gt; __( 'Cover', 'mytheme' ), 'thumbnail' =&gt; __( 'Thumbnail', 'mytheme' ), 'default' =&gt; __( 'Default', 'mytheme' ), ), ) ); </code></pre> <p>And the complete code responsible to render the post meta-box is:</p> <pre><code>&lt;?php /** * Add the meta box * * @return void */ function mytheme_add_custom_box() { add_meta_box( 'mytheme_sectionid', __( 'Post Options', 'mytheme' ), 'mytheme_build_custom_box', 'post', 'side', 'low' ); } add_action( 'add_meta_boxes', 'mytheme_add_custom_box' ); /** * Prints the box content. * * @param WP_Post $post The object for the current post/page. * @return void */ function mytheme_build_custom_box( $post ) { // Add an nonce field so we can check for it later. wp_nonce_field( 'mytheme_build_custom_box', 'mytheme_build_custom_box_nonce' ); /* * Use get_post_meta() to retrieve an existing value * from the database and use the value for the form. */ $value = get_post_meta( $post-&gt;ID, '_my_meta_value_key', true ); $loxxo_post_header_layout = get_theme_mod( 'loxxo_post_header', 'cover' ); ?&gt; &lt;p&gt;&lt;?php __( 'Select a style', 'mytheme' ); ?&gt;&lt;/p&gt; &lt;input type="radio" id="mytheme_post_layout-cover" name="mytheme_post_layout" value="cover" &lt;?php checked( $value, 'cover' ) ?&gt; /&gt;&lt;label for="mytheme_post_layout-cover"&gt;&lt;?php _e( 'Cover/Fullscreen', 'mytheme' ); ?&gt;&lt;/label&gt; &lt;br&gt; &lt;input type="radio" id="mytheme_post_layout-thumbnail" name="mytheme_post_layout" value="thumbnail" &lt;?php checked( $value, 'thumbnail' ) ?&gt; /&gt;&lt;label for="mytheme_post_layout-thumbnail"&gt;&lt;?php _e( 'Regular', 'mytheme' ) ?&gt;&lt;/label&gt; &lt;br&gt; &lt;input type="radio" id="mytheme_post_layout-default" name="mytheme_post_layout" value="default" &lt;?php checked( $value, 'default' ) ?&gt; /&gt;&lt;label for="mytheme_post_layout-default"&gt;&lt;?php _e( 'Default', 'mytheme' ) ?&gt;&lt;/label&gt; &lt;?php } /** * When the post is saved, saves our custom data. * * @param int $post_id The ID of the post being saved. * @return void */ function mytheme_save_postdata( $post_id ) { /* * We need to verify this came from the our screen and with proper authorization, * because save_post can be triggered at other times. */ // Check if our nonce is set. if ( ! isset( $_POST['mytheme_build_custom_box_nonce'] ) ) return $post_id; $nonce = $_POST['mytheme_build_custom_box_nonce']; // Verify that the nonce is valid. if ( ! wp_verify_nonce( $nonce, 'mytheme_build_custom_box' ) ) return $post_id; // If this is an autosave, our form has not been submitted, so we don't want to do anything. if ( defined( 'DOING_AUTOSAVE' ) &amp;&amp; DOING_AUTOSAVE ) return $post_id; // Check the user's permissions. if ( 'page' == $_POST['post_type'] ) { if ( ! current_user_can( 'edit_page', $post_id ) ) return $post_id; } else { if ( ! current_user_can( 'edit_post', $post_id ) ) return $post_id; } // Sanitize user input. $mydata = sanitize_text_field( $_POST['mytheme_post_layout'] ); // Update the meta field in the database. update_post_meta( $post_id, '_my_meta_value_key', $mydata ); } add_action( 'save_post', 'mytheme_save_postdata' ); </code></pre> <p>Above is a bit lengthy code, sorry about that. The options are rendering correctly, and everything looks fine in the customizer and the meta-box.</p> <p>The problem is, that I'm confused about making the default value of the meta-box radio options go hand-in-hand with the customizer's. Any clues and ideas will be appreciated.</p>
[ { "answer_id": 310509, "author": "Jacob Peattie", "author_id": 39152, "author_profile": "https://wordpress.stackexchange.com/users/39152", "pm_score": 1, "selected": false, "text": "<p>You're getting the saved value here:</p>\n\n<pre><code>$value = get_post_meta( $post-&gt;ID, '_my_meta_...
2018/08/04
[ "https://wordpress.stackexchange.com/questions/310508", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/67150/" ]
I have a radio control in the theme customizer. The code for that control is like below: ``` $wp_customize->add_setting( 'post_layout', array( 'capability' => 'edit_theme_options', 'default' => 'cover', 'sanitize_callback' => 'sanitize_text_field', ) ); $wp_customize->add_control( 'post_layout', array( 'type' => 'radio', 'section' => 'post_options', 'label' => __( 'Post Layout', 'mytheme' ), 'choices' => array( 'cover' => __( 'Cover', 'mytheme' ), 'thumbnail' => __( 'Thumbnail', 'mytheme' ), 'default' => __( 'Default', 'mytheme' ), ), ) ); ``` And the complete code responsible to render the post meta-box is: ``` <?php /** * Add the meta box * * @return void */ function mytheme_add_custom_box() { add_meta_box( 'mytheme_sectionid', __( 'Post Options', 'mytheme' ), 'mytheme_build_custom_box', 'post', 'side', 'low' ); } add_action( 'add_meta_boxes', 'mytheme_add_custom_box' ); /** * Prints the box content. * * @param WP_Post $post The object for the current post/page. * @return void */ function mytheme_build_custom_box( $post ) { // Add an nonce field so we can check for it later. wp_nonce_field( 'mytheme_build_custom_box', 'mytheme_build_custom_box_nonce' ); /* * Use get_post_meta() to retrieve an existing value * from the database and use the value for the form. */ $value = get_post_meta( $post->ID, '_my_meta_value_key', true ); $loxxo_post_header_layout = get_theme_mod( 'loxxo_post_header', 'cover' ); ?> <p><?php __( 'Select a style', 'mytheme' ); ?></p> <input type="radio" id="mytheme_post_layout-cover" name="mytheme_post_layout" value="cover" <?php checked( $value, 'cover' ) ?> /><label for="mytheme_post_layout-cover"><?php _e( 'Cover/Fullscreen', 'mytheme' ); ?></label> <br> <input type="radio" id="mytheme_post_layout-thumbnail" name="mytheme_post_layout" value="thumbnail" <?php checked( $value, 'thumbnail' ) ?> /><label for="mytheme_post_layout-thumbnail"><?php _e( 'Regular', 'mytheme' ) ?></label> <br> <input type="radio" id="mytheme_post_layout-default" name="mytheme_post_layout" value="default" <?php checked( $value, 'default' ) ?> /><label for="mytheme_post_layout-default"><?php _e( 'Default', 'mytheme' ) ?></label> <?php } /** * When the post is saved, saves our custom data. * * @param int $post_id The ID of the post being saved. * @return void */ function mytheme_save_postdata( $post_id ) { /* * We need to verify this came from the our screen and with proper authorization, * because save_post can be triggered at other times. */ // Check if our nonce is set. if ( ! isset( $_POST['mytheme_build_custom_box_nonce'] ) ) return $post_id; $nonce = $_POST['mytheme_build_custom_box_nonce']; // Verify that the nonce is valid. if ( ! wp_verify_nonce( $nonce, 'mytheme_build_custom_box' ) ) return $post_id; // If this is an autosave, our form has not been submitted, so we don't want to do anything. if ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE ) return $post_id; // Check the user's permissions. if ( 'page' == $_POST['post_type'] ) { if ( ! current_user_can( 'edit_page', $post_id ) ) return $post_id; } else { if ( ! current_user_can( 'edit_post', $post_id ) ) return $post_id; } // Sanitize user input. $mydata = sanitize_text_field( $_POST['mytheme_post_layout'] ); // Update the meta field in the database. update_post_meta( $post_id, '_my_meta_value_key', $mydata ); } add_action( 'save_post', 'mytheme_save_postdata' ); ``` Above is a bit lengthy code, sorry about that. The options are rendering correctly, and everything looks fine in the customizer and the meta-box. The problem is, that I'm confused about making the default value of the meta-box radio options go hand-in-hand with the customizer's. Any clues and ideas will be appreciated.
Before to handle the defaut value, there is a lot of changes that you can do for the hook "save\_post" and the first one is to no more use it. You add the metabox only on post type `post`, then you can use the hook `save_post_post` to only doing the treatment for this custom post : <https://developer.wordpress.org/reference/hooks/save_post_post-post_type/> After that, you don't need to test the capability `edit_post` because the backend page "edit.php" does the test before to save. And you don't need to test DOING\_AUTOSAVE because in the autosave case, the metabox values are not send. And then you just have to test the nonce. Finally, to set a default value in the metabox, you can do it when `$update === FALSE` which is called when you click on the link "create a new post". and then try this code : ``` add_action("save_post_post", function ($post_ID, $post, $update) { if (!$update) { // default values here $mydata = get_theme_mod( 'post_layout', 'cover' ); update_post_meta( $post_ID, '_my_meta_value_key', $mydata ); return; } if ( ! isset( $_POST['mytheme_build_custom_box_nonce'] ) ) { return; } // check the nonce check_admin_referer( "mytheme_build_custom_box" , "mytheme_build_custom_box_nonce" ); // save the values // Sanitize user input. $mydata = sanitize_text_field( $_POST['mytheme_post_layout'] ); // Update the meta field in the database. update_post_meta( $post_ID, '_my_meta_value_key', $mydata ); }, 10, 3); ```
310,513
<p>I'm trying to create a new og:image for author avatar when the users sharing their author profile page to Facebook.</p> <p>I'm a newbie with WordPress, After searching for more than 6 months but i'm always failing.</p> <p>My site is multi-authors and all what i need to add og:image meta tag for author.php "author profile", I'm stuck and I really get tired from searching.</p> <p>When our users trying to share his profile..the avatar image not coming up! because Facebook can't find the author avatar og:image!</p> <p>Plugins i'm using : <a href="https://yoast.com/" rel="nofollow noreferrer">Yoast SEO</a>, <a href="https://wordpress.org/plugins/simple-local-avatars/" rel="nofollow noreferrer">Simple Local Avatars</a>, <a href="https://wordpress.org/plugins/add-to-any/" rel="nofollow noreferrer">AddToAny Share Buttons</a>.</p> <p>I tried to use wpseo_opengraph_image filter, but not working.</p> <p>This is code I'm using:</p> <pre><code>function custom_author_og_image() { if ( is_author ( ) ) { $author = get_queried_object(); $image_attributes = get_avatar_url( $author-&gt;user_email, 'full' ); if ( $image_attributes !== false ) { return $image_attributes[0]; } } } add_filter('wpseo_opengraph_image', 'custom_author_og_image', 10, 0); </code></pre>
[ { "answer_id": 310509, "author": "Jacob Peattie", "author_id": 39152, "author_profile": "https://wordpress.stackexchange.com/users/39152", "pm_score": 1, "selected": false, "text": "<p>You're getting the saved value here:</p>\n\n<pre><code>$value = get_post_meta( $post-&gt;ID, '_my_meta_...
2018/08/04
[ "https://wordpress.stackexchange.com/questions/310513", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/146329/" ]
I'm trying to create a new og:image for author avatar when the users sharing their author profile page to Facebook. I'm a newbie with WordPress, After searching for more than 6 months but i'm always failing. My site is multi-authors and all what i need to add og:image meta tag for author.php "author profile", I'm stuck and I really get tired from searching. When our users trying to share his profile..the avatar image not coming up! because Facebook can't find the author avatar og:image! Plugins i'm using : [Yoast SEO](https://yoast.com/), [Simple Local Avatars](https://wordpress.org/plugins/simple-local-avatars/), [AddToAny Share Buttons](https://wordpress.org/plugins/add-to-any/). I tried to use wpseo\_opengraph\_image filter, but not working. This is code I'm using: ``` function custom_author_og_image() { if ( is_author ( ) ) { $author = get_queried_object(); $image_attributes = get_avatar_url( $author->user_email, 'full' ); if ( $image_attributes !== false ) { return $image_attributes[0]; } } } add_filter('wpseo_opengraph_image', 'custom_author_og_image', 10, 0); ```
Before to handle the defaut value, there is a lot of changes that you can do for the hook "save\_post" and the first one is to no more use it. You add the metabox only on post type `post`, then you can use the hook `save_post_post` to only doing the treatment for this custom post : <https://developer.wordpress.org/reference/hooks/save_post_post-post_type/> After that, you don't need to test the capability `edit_post` because the backend page "edit.php" does the test before to save. And you don't need to test DOING\_AUTOSAVE because in the autosave case, the metabox values are not send. And then you just have to test the nonce. Finally, to set a default value in the metabox, you can do it when `$update === FALSE` which is called when you click on the link "create a new post". and then try this code : ``` add_action("save_post_post", function ($post_ID, $post, $update) { if (!$update) { // default values here $mydata = get_theme_mod( 'post_layout', 'cover' ); update_post_meta( $post_ID, '_my_meta_value_key', $mydata ); return; } if ( ! isset( $_POST['mytheme_build_custom_box_nonce'] ) ) { return; } // check the nonce check_admin_referer( "mytheme_build_custom_box" , "mytheme_build_custom_box_nonce" ); // save the values // Sanitize user input. $mydata = sanitize_text_field( $_POST['mytheme_post_layout'] ); // Update the meta field in the database. update_post_meta( $post_ID, '_my_meta_value_key', $mydata ); }, 10, 3); ```
310,524
<p>There are specific plugins that I want to use my own repo for for updating my sites. How can I identify the plugin to target and what server they should be looking at?</p>
[ { "answer_id": 310509, "author": "Jacob Peattie", "author_id": 39152, "author_profile": "https://wordpress.stackexchange.com/users/39152", "pm_score": 1, "selected": false, "text": "<p>You're getting the saved value here:</p>\n\n<pre><code>$value = get_post_meta( $post-&gt;ID, '_my_meta_...
2018/08/04
[ "https://wordpress.stackexchange.com/questions/310524", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/116443/" ]
There are specific plugins that I want to use my own repo for for updating my sites. How can I identify the plugin to target and what server they should be looking at?
Before to handle the defaut value, there is a lot of changes that you can do for the hook "save\_post" and the first one is to no more use it. You add the metabox only on post type `post`, then you can use the hook `save_post_post` to only doing the treatment for this custom post : <https://developer.wordpress.org/reference/hooks/save_post_post-post_type/> After that, you don't need to test the capability `edit_post` because the backend page "edit.php" does the test before to save. And you don't need to test DOING\_AUTOSAVE because in the autosave case, the metabox values are not send. And then you just have to test the nonce. Finally, to set a default value in the metabox, you can do it when `$update === FALSE` which is called when you click on the link "create a new post". and then try this code : ``` add_action("save_post_post", function ($post_ID, $post, $update) { if (!$update) { // default values here $mydata = get_theme_mod( 'post_layout', 'cover' ); update_post_meta( $post_ID, '_my_meta_value_key', $mydata ); return; } if ( ! isset( $_POST['mytheme_build_custom_box_nonce'] ) ) { return; } // check the nonce check_admin_referer( "mytheme_build_custom_box" , "mytheme_build_custom_box_nonce" ); // save the values // Sanitize user input. $mydata = sanitize_text_field( $_POST['mytheme_post_layout'] ); // Update the meta field in the database. update_post_meta( $post_ID, '_my_meta_value_key', $mydata ); }, 10, 3); ```
310,535
<p>I created my own category selection widget. So i used <code>&lt;select&gt;</code> but i want to use with <code>multiple</code> attribute. </p> <p>Here is my widget class. It works perfect without <code>multiple</code> attr. But i want to use it. And it must be return category ids in array.</p> <pre><code>&lt;?php class myCatWidget extends WP_Widget { function myCatWidget() { parent::WP_Widget( false, $name = 'My cat widget' ); } function form( $instance ) { $title = esc_attr( $instance[ 'title' ] ); $postCats = $instance[ 'postCats' ]; ?&gt; &lt;p&gt; &lt;label for="&lt;?php echo $this-&gt;get_field_id( 'title' ); ?&gt;"&gt;Title&lt;/label&gt; &lt;input type="text" class="widfat" id="&lt;?php echo $this-&gt;get_field_id( 'title' ); ?&gt;" name="&lt;?php echo $this-&gt;get_field_name( 'title' ); ?&gt;" style="width: 100%;" value="&lt;?php echo $title; ?&gt;"/&gt; &lt;/p&gt; &lt;p&gt; &lt;label for="&lt;?php echo $this-&gt;get_field_id( 'postCats' ); ?&gt;"&gt;Categories&lt;/label&gt; &lt;select name="&lt;?php echo $this-&gt;get_field_name( 'postCats' ); ?&gt;" id="&lt;?php echo $this-&gt;get_field_id( 'postCats' ); ?&gt;" style="width: 100%;" multiple&gt; &lt;?php $args = array( 'taxonomy' =&gt; 'category', ); $terms = get_terms( $args ); foreach( $terms as $term ) { ?&gt; &lt;option &lt;?php selected( $instance[ 'postCats' ], $term-&gt;term_id ); ?&gt; value="&lt;?php echo esc_attr( $term-&gt;term_id ); ?&gt;"&gt; &lt;?php echo esc_html( $term-&gt;name ); ?&gt; &lt;/option&gt; &lt;?php } ?&gt; &lt;/select&gt; &lt;/p&gt; &lt;?php } function update( $new_instance, $old_instance ) { $instance = $old_instance; $instance[ 'title' ] = strip_tags( $new_instance[ 'title' ] ); $instance[ 'postCats' ] = esc_sql( $new_instance[ 'postCats' ] ); return $instance; } function widget( $args, $instance ) { extract( $args ); $title = apply_filters( 'widget_title', $instance[ 'title' ] ); $postCats = $instance[ 'postCats' ]; echo $before_widget; if( $title ) { echo $before_title . $title . $after_title; } echo $postCats; echo $after_widget; } } add_action( 'widgets_init', create_function( '', 'return register_widget("myCatWidget");' ) ); ?&gt; </code></pre>
[ { "answer_id": 310595, "author": "Nilesh Sanura", "author_id": 148097, "author_profile": "https://wordpress.stackexchange.com/users/148097", "pm_score": 2, "selected": true, "text": "<p>Hi why don't you used multiple check-box instead of select option field. As well as you have used depr...
2018/08/04
[ "https://wordpress.stackexchange.com/questions/310535", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/133897/" ]
I created my own category selection widget. So i used `<select>` but i want to use with `multiple` attribute. Here is my widget class. It works perfect without `multiple` attr. But i want to use it. And it must be return category ids in array. ``` <?php class myCatWidget extends WP_Widget { function myCatWidget() { parent::WP_Widget( false, $name = 'My cat widget' ); } function form( $instance ) { $title = esc_attr( $instance[ 'title' ] ); $postCats = $instance[ 'postCats' ]; ?> <p> <label for="<?php echo $this->get_field_id( 'title' ); ?>">Title</label> <input type="text" class="widfat" id="<?php echo $this->get_field_id( 'title' ); ?>" name="<?php echo $this->get_field_name( 'title' ); ?>" style="width: 100%;" value="<?php echo $title; ?>"/> </p> <p> <label for="<?php echo $this->get_field_id( 'postCats' ); ?>">Categories</label> <select name="<?php echo $this->get_field_name( 'postCats' ); ?>" id="<?php echo $this->get_field_id( 'postCats' ); ?>" style="width: 100%;" multiple> <?php $args = array( 'taxonomy' => 'category', ); $terms = get_terms( $args ); foreach( $terms as $term ) { ?> <option <?php selected( $instance[ 'postCats' ], $term->term_id ); ?> value="<?php echo esc_attr( $term->term_id ); ?>"> <?php echo esc_html( $term->name ); ?> </option> <?php } ?> </select> </p> <?php } function update( $new_instance, $old_instance ) { $instance = $old_instance; $instance[ 'title' ] = strip_tags( $new_instance[ 'title' ] ); $instance[ 'postCats' ] = esc_sql( $new_instance[ 'postCats' ] ); return $instance; } function widget( $args, $instance ) { extract( $args ); $title = apply_filters( 'widget_title', $instance[ 'title' ] ); $postCats = $instance[ 'postCats' ]; echo $before_widget; if( $title ) { echo $before_title . $title . $after_title; } echo $postCats; echo $after_widget; } } add_action( 'widgets_init', create_function( '', 'return register_widget("myCatWidget");' ) ); ?> ```
Hi why don't you used multiple check-box instead of select option field. As well as you have used deprecated functions like "create\_function". I have modified your code which replaced select option with multiple check-box selection. ``` function myCatWidget() { register_widget( 'my_custom_cat_widget' ); } add_action( 'widgets_init', 'myCatWidget' ); class my_custom_cat_widget extends WP_Widget { function __construct() { parent::__construct('my_custom_cat_widget', __('My cat widget', 'wpb_widget_domain'), array( 'description' => __( 'Your description', 'wpb_widget_domain' ), ) ); } public function form( $instance ) { $title = isset($instance[ 'title' ]) ? $instance[ 'title' ] : 'Categories'; $instance['postCats'] = !empty($instance['postCats']) ? explode(",",$instance['postCats']) : array(); ?> <p> <label for="<?php echo $this->get_field_id( 'title' ); ?>">Title</label> <input type="text" class="widfat" id="<?php echo $this->get_field_id( 'title' ); ?>" name="<?php echo $this->get_field_name( 'title' ); ?>" style="width: 100%;" value="<?php echo $title; ?>"/> </p> <p> <label for="<?php echo $this->get_field_id( 'postCats' ); ?>"><?php _e( 'Select Categories you want to show:' ); ?></label><br /> <?php $args = array( 'post_type' => 'post', 'taxonomy' => 'category', ); $terms = get_terms( $args ); //print_r($terms); foreach( $terms as $id => $name ) { $checked = ""; if(in_array($name->name,$instance['postCats'])){ $checked = "checked='checked'"; } ?> <input type="checkbox" class="checkbox" id="<?php echo $this->get_field_id('postCats'); ?>" name="<?php echo $this->get_field_name('postCats[]'); ?>" value="<?php echo $name->name; ?>" <?php echo $checked; ?>/> <label for="<?php echo $this->get_field_id('postCats'); ?>"><?php echo $name->name; ?></label><br /> <?php } ?> </p> <?php } public function update( $new_instance, $old_instance ) { $instance = $old_instance; $instance[ 'title' ] = strip_tags( $new_instance[ 'title' ] ); $instance['postCats'] = !empty($new_instance['postCats']) ? implode(",",$new_instance['postCats']) : 0; return $instance; } public function widget( $args, $instance ) { extract( $args ); $title = apply_filters( 'widget_title', $instance[ 'title' ] ); $postCats = $instance[ 'postCats' ]; $categories_list = explode(",", $postCats); echo $before_widget; if( $title ) { echo $before_title . $title . $after_title; } $args = array('post_type' => 'post','taxonomy' => 'category',); $terms = get_terms( $args ); ?> <ul> <?php foreach ($categories_list as $cat) { foreach($terms as $term) { if($cat === $term->name) { echo "<li>".$term->name."</li>"; } } } ?> </ul> <?php echo $after_widget; } } ``` Hope it will help to solved your problem. :)
310,628
<p>I have created a custom banner image block for Gutenberg, which works great, but I want to know if it is possible to use the page title as the current banner text placeholder until it has been edited?</p> <p><a href="https://i.stack.imgur.com/GRkwW.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/GRkwW.png" alt="enter image description here"></a></p> <p>My Edit function is</p> <pre><code> return [ el('div', {className:'header-banner'}, el( element.Fragment, null, controls, el( "div",{ className: 'banner-image', style: { backgroundImage: 'url('+attributes.mediaURL+')' } }, attributes.title || isSelected ? el(RichText, { key: 'editable', tagName: "h1", className: "banner-title", //Can i add the page title in here if it is avaiable?? //placeholder: i18n.__('Write title…'), value: attributes.title, onChange: function onChange(value) { return props.setAttributes({ title: value }); }, inlineToolbar: true }) : null ) ) )//header-banner ]; </code></pre> <p>Thanks :)</p>
[ { "answer_id": 311271, "author": "Jim-miraidev", "author_id": 130369, "author_profile": "https://wordpress.stackexchange.com/users/130369", "pm_score": 2, "selected": false, "text": "<p>Thanks to the answer in this post i have managed to add the title into the banner and it updates as th...
2018/08/06
[ "https://wordpress.stackexchange.com/questions/310628", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/130369/" ]
I have created a custom banner image block for Gutenberg, which works great, but I want to know if it is possible to use the page title as the current banner text placeholder until it has been edited? [![enter image description here](https://i.stack.imgur.com/GRkwW.png)](https://i.stack.imgur.com/GRkwW.png) My Edit function is ``` return [ el('div', {className:'header-banner'}, el( element.Fragment, null, controls, el( "div",{ className: 'banner-image', style: { backgroundImage: 'url('+attributes.mediaURL+')' } }, attributes.title || isSelected ? el(RichText, { key: 'editable', tagName: "h1", className: "banner-title", //Can i add the page title in here if it is avaiable?? //placeholder: i18n.__('Write title…'), value: attributes.title, onChange: function onChange(value) { return props.setAttributes({ title: value }); }, inlineToolbar: true }) : null ) ) )//header-banner ]; ``` Thanks :)
Due to the `getDocumentTitle` selector being deprecated as mentioned here <https://stackoverflow.com/questions/51674293/use-page-title-in-gutenberg-custom-banner-block/51792096#comment92130728_51792096> I managed to get it working with a slight tweak to the code by Jim-miraidev ``` var GetTitle = function GetTitle(props) { return el("h1", {className: "jab-banner-title"}, props.title); }; var selectTitle = withSelect(function (select) { var title; if (typeof select("core/editor").getPostEdits().title !== 'undefined') { title = select("core/editor").getPostEdits().title; } else { title = select("core/editor").getCurrentPost().title; } return { title: title }; }); var PostTitle = selectTitle(GetTitle); ``` ..... ``` return [ el('div', {className:'jab-header-banner '+classes+''}, el( element.Fragment, null, controls, el( "div",{ className: 'jab-banner-image', style: { backgroundImage: 'url('+attributes.mediaURL+')' } }, el(PostTitle,{className: "jab-banner-title"}) ) ) )//header-banner ]; ```
310,668
<p>I want to redirect users to account details after registering, by default it is redirecting to my account dashboard.</p> <p>This is where I want users to be redirected</p> <blockquote> <p>mydomain.com/my-account/edit-account/</p> </blockquote> <p>I found something like this, but I think it won't work</p> <pre><code>function iconic_register_redirect( $redirect ) { return wc_get_page_permalink( '' ); } add_filter( 'woocommerce_registration_redirect', 'iconic_register_redirect' ); </code></pre>
[ { "answer_id": 310697, "author": "Suraj Rathod", "author_id": 141555, "author_profile": "https://wordpress.stackexchange.com/users/141555", "pm_score": 0, "selected": false, "text": "<pre><code>function woo_login_redirect( $redirect, $user ) {\n$redirect_page_id = url_to_postid( $redirec...
2018/08/06
[ "https://wordpress.stackexchange.com/questions/310668", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/148207/" ]
I want to redirect users to account details after registering, by default it is redirecting to my account dashboard. This is where I want users to be redirected > > mydomain.com/my-account/edit-account/ > > > I found something like this, but I think it won't work ``` function iconic_register_redirect( $redirect ) { return wc_get_page_permalink( '' ); } add_filter( 'woocommerce_registration_redirect', 'iconic_register_redirect' ); ```
To get "*Account details*" permalink (endpoint `edit-account`) you need to use function `wc_get_account_endpoint_url`. ``` function wc_redirect_to_account_details( $redirect ) { $redirect = wc_get_account_endpoint_url('edit-account'); return $redirect; } add_filter( 'woocommerce_registration_redirect', 'wc_redirect_to_account_details' ); ```
310,685
<p>I am trying to enqueue a js file (calculator.js) from my theme's functions.php file.</p> <p>I have a desktop theme and a smartphone theme, and I am using a plugin to switch between the two themes depending on the user's device.</p> <p>I have the exact same code on my desktop theme and it works perfectly, however when I copied it to my smartphone theme, it just seems to ignore the enqueue script.</p> <p>Here is my code:</p> <pre><code>function wpb_adding_scripts() { wp_register_script('calculator_script', get_template_directory_uri() . '/js/calculator.js', array( 'jquery' ), NULL, 'all'); wp_enqueue_script('calculator_script'); wp_enqueue_style( 'slider', get_template_directory_uri() . '/css/calculator.css',false,'1.1','all'); } add_action( 'wp_enqueue_scripts', 'wpb_adding_scripts' ); </code></pre> <p>What I have done/notes: </p> <ul> <li>Made sure functions.php file does indeed start with a opening php tag</li> <li>Made sure all files are in their correct directories</li> <li>Console is not flagging any errors</li> <li>Sources does not show my js file being loaded, however the css file (calculator.css) is being loaded correctly..</li> </ul> <p>Any insights as to what might be the cause of this issue?</p> <p>Thank you very much.</p>
[ { "answer_id": 310690, "author": "maverick", "author_id": 132953, "author_profile": "https://wordpress.stackexchange.com/users/132953", "pm_score": 1, "selected": false, "text": "<p>Just some modifications</p>\n\n<pre><code>function wpb_adding_scripts() {\n wp_enqueue_script( 'calcula...
2018/08/07
[ "https://wordpress.stackexchange.com/questions/310685", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/148215/" ]
I am trying to enqueue a js file (calculator.js) from my theme's functions.php file. I have a desktop theme and a smartphone theme, and I am using a plugin to switch between the two themes depending on the user's device. I have the exact same code on my desktop theme and it works perfectly, however when I copied it to my smartphone theme, it just seems to ignore the enqueue script. Here is my code: ``` function wpb_adding_scripts() { wp_register_script('calculator_script', get_template_directory_uri() . '/js/calculator.js', array( 'jquery' ), NULL, 'all'); wp_enqueue_script('calculator_script'); wp_enqueue_style( 'slider', get_template_directory_uri() . '/css/calculator.css',false,'1.1','all'); } add_action( 'wp_enqueue_scripts', 'wpb_adding_scripts' ); ``` What I have done/notes: * Made sure functions.php file does indeed start with a opening php tag * Made sure all files are in their correct directories * Console is not flagging any errors * Sources does not show my js file being loaded, however the css file (calculator.css) is being loaded correctly.. Any insights as to what might be the cause of this issue? Thank you very much.
``` You can better try this way and let me know. function wpb_adding_scripts() { wp_enqueue_style( 'slider', get_stylesheet_directory_uri() . '/css/calculator.css'); wp_enqueue_script('jquery'); wp_enqueue_script('calculator_script', get_stylesheet_directory_uri() . '/js/calculator.js'); } add_action( 'wp_enqueue_scripts', 'wpb_adding_scripts' ); ```
310,698
<p>I have a <strong>notmytheme</strong>, the original css load order is like so:</p> <pre><code>&lt;link rel='stylesheet' id='something' href='http://localhost/mywp/wp-content/themes/notmytheme/something.css' type='text/css' media='all' /&gt; &lt;link rel='stylesheet' id='notmytheme-style-css' href='http://localhost/mywp/wp-content/themes/notmytheme/style.css?ver=1.0.9' type='text/css' media='all' /&gt; </code></pre> <p>When I created a child theme called the <strong>notmytheme-child</strong>, and enqueue the child style, it became like this:</p> <pre><code>&lt;link rel='stylesheet' id='notmytheme-style-css' href='http://localhost/mywp/wp-content/themes/notmytheme/style.css?ver=1.0.9' type='text/css' media='all' /&gt; &lt;link rel='stylesheet' id='child-style-css' href='http://localhost/mywp/wp-content/themes/notmytheme-child/style.css?ver=18.08.07' type='text/css' media='all' /&gt; &lt;link rel='stylesheet' id='something' href='http://localhost/mywp/wp-content/themes/notmytheme/something.css' type='text/css' media='all' /&gt; </code></pre> <p>I want the parent and child style to be loaded after other styles like how the parent theme did it, so I moved it down with priority ( <code>add_action( 'wp_enqueue_scripts', 'my_theme_enqueue_styles', 999 );</code> ), now it became like this:</p> <pre><code>&lt;link rel='stylesheet' id='something' href='http://localhost/mywp/wp-content/themes/notmytheme/something.css' type='text/css' media='all' /&gt; &lt;link rel='stylesheet' id='notmytheme-style-css' href='http://localhost/mywp/wp-content/themes/notmytheme-child/style.css?ver=1.0.9' type='text/css' media='all' /&gt; &lt;link rel='stylesheet' id='child-style-css' href='http://localhost/mywp/wp-content/themes/notmytheme-child/style.css?ver=18.08.07' type='text/css' media='all' /&gt; </code></pre> <p>I do not know why but now the <code>get_template_directory_uri()</code> now points to <strong>notmytheme-child</strong> instead of <strong>notmytheme</strong>.</p> <p>My current enqueue script is like so:</p> <pre><code>add_action( 'wp_enqueue_scripts', 'my_theme_enqueue_styles', 999 ); function my_theme_enqueue_styles() { $parent_style = 'notmytheme-style'; wp_enqueue_style( $parent_style, get_template_directory_uri() . '/style.css', array(), '1.0.9' ); wp_enqueue_style( 'child-style', get_stylesheet_directory_uri() . '/style.css', array( $parent_style ), '18.08.07', 'all' ); } </code></pre> <p>Adjusting the priority changes the position of where the css are loaded, and also which directory <code>get_template_directory_uri()</code> points to.</p> <p><strong>EDIT/SOLUTION</strong></p> <p>My codes are now:</p> <pre><code>add_action( 'wp_enqueue_scripts', 'my_enqueue_child', 999 ); function my_enqueue_child() { wp_dequeue_style( 'notmytheme-style' ); wp_enqueue_style( 'parent-style', get_template_directory_uri() . '/style.css', array(), '1.0.9' ); wp_enqueue_style( 'child-style', get_stylesheet_directory_uri() . '/style.css', array( 'parent-style' ), '18.08.07', 'all' ); } </code></pre>
[ { "answer_id": 310700, "author": "Nilesh Sanura", "author_id": 148097, "author_profile": "https://wordpress.stackexchange.com/users/148097", "pm_score": -1, "selected": false, "text": "<p>Please use get_stylesheet_directory_uri() instead of get_template_directory_uri() when you have to e...
2018/08/07
[ "https://wordpress.stackexchange.com/questions/310698", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/117364/" ]
I have a **notmytheme**, the original css load order is like so: ``` <link rel='stylesheet' id='something' href='http://localhost/mywp/wp-content/themes/notmytheme/something.css' type='text/css' media='all' /> <link rel='stylesheet' id='notmytheme-style-css' href='http://localhost/mywp/wp-content/themes/notmytheme/style.css?ver=1.0.9' type='text/css' media='all' /> ``` When I created a child theme called the **notmytheme-child**, and enqueue the child style, it became like this: ``` <link rel='stylesheet' id='notmytheme-style-css' href='http://localhost/mywp/wp-content/themes/notmytheme/style.css?ver=1.0.9' type='text/css' media='all' /> <link rel='stylesheet' id='child-style-css' href='http://localhost/mywp/wp-content/themes/notmytheme-child/style.css?ver=18.08.07' type='text/css' media='all' /> <link rel='stylesheet' id='something' href='http://localhost/mywp/wp-content/themes/notmytheme/something.css' type='text/css' media='all' /> ``` I want the parent and child style to be loaded after other styles like how the parent theme did it, so I moved it down with priority ( `add_action( 'wp_enqueue_scripts', 'my_theme_enqueue_styles', 999 );` ), now it became like this: ``` <link rel='stylesheet' id='something' href='http://localhost/mywp/wp-content/themes/notmytheme/something.css' type='text/css' media='all' /> <link rel='stylesheet' id='notmytheme-style-css' href='http://localhost/mywp/wp-content/themes/notmytheme-child/style.css?ver=1.0.9' type='text/css' media='all' /> <link rel='stylesheet' id='child-style-css' href='http://localhost/mywp/wp-content/themes/notmytheme-child/style.css?ver=18.08.07' type='text/css' media='all' /> ``` I do not know why but now the `get_template_directory_uri()` now points to **notmytheme-child** instead of **notmytheme**. My current enqueue script is like so: ``` add_action( 'wp_enqueue_scripts', 'my_theme_enqueue_styles', 999 ); function my_theme_enqueue_styles() { $parent_style = 'notmytheme-style'; wp_enqueue_style( $parent_style, get_template_directory_uri() . '/style.css', array(), '1.0.9' ); wp_enqueue_style( 'child-style', get_stylesheet_directory_uri() . '/style.css', array( $parent_style ), '18.08.07', 'all' ); } ``` Adjusting the priority changes the position of where the css are loaded, and also which directory `get_template_directory_uri()` points to. **EDIT/SOLUTION** My codes are now: ``` add_action( 'wp_enqueue_scripts', 'my_enqueue_child', 999 ); function my_enqueue_child() { wp_dequeue_style( 'notmytheme-style' ); wp_enqueue_style( 'parent-style', get_template_directory_uri() . '/style.css', array(), '1.0.9' ); wp_enqueue_style( 'child-style', get_stylesheet_directory_uri() . '/style.css', array( 'parent-style' ), '18.08.07', 'all' ); } ```
It's very common for themes to enqueue their stylesheet like this: ``` wp_enqueue_style( 'notmytheme-style', get_stylesheet_uri() ); ``` When you activate a child theme for a theme that does this, `get_stylesheet_uri()` becomes the *child theme's* stylesheet URL. This means that the parent theme will enqueue the *child theme's* stylesheet (with `notmytheme-style` as the ID), but *not* it's own stylesheet. That's where this would be coming from: ``` <link rel='stylesheet' id='notmytheme-style-css' href='http://localhost/mywp/wp-content/themes/notmytheme-child/style.css?ver=1.0.9' type='text/css' media='all' /> ``` It's the parent theme's ID with the child theme's URL. The issue with your code is that you're using the same handle (`notmytheme-style`) to enqueue the parent theme stylesheet as the parent theme is using the load the child theme's stylesheet. When you do this it will be ignored and enqueue the first version defined. This is why changing the priority affected the result. Whichever `notmytheme-style` is defined first is loaded. So the proper way to enqueue the CSS in this circumstance would be to not enqueue the child theme stylesheet, and enqueue the parent theme's stylesheet with a different handle and higher priority (lower number): ``` add_action( 'wp_enqueue_scripts', 'my_theme_enqueue_styles', 9 ); function my_theme_enqueue_styles() { $parent_style = 'notmytheme-parent-style'; // New handle. wp_enqueue_style( $parent_style, get_template_directory_uri() . '/style.css', array(), '1.0.9' ); } ``` This does mean that your child theme stylesheet will be using the version number of the parent theme. This could be avoided by instead dequeuing the parent theme's original style and re-enqueuing it: ``` add_action( 'wp_enqueue_scripts', 'my_theme_enqueue_styles', 999 ); function my_theme_enqueue_styles() { $parent_style = 'notmytheme-style'; wp_dequeue_style( $parent_style ); wp_enqueue_style( $parent_style, get_template_directory_uri() . '/style.css', array(), '1.0.9' ); wp_enqueue_style( 'child-style', get_stylesheet_directory_uri() . '/style.css', array( $parent_style ), '18.08.07', 'all' ); } ```
310,761
<p>I have the following setup in my <code>.htaccess</code> file, but I am still able to go to my site via <code>http:</code></p> <pre><code># BEGIN WordPress &lt;IfModule mod_rewrite.c&gt; RewriteEngine On RewriteBase / RewriteRule ^index\.php$ - [L] RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule . /index.php [L] # Rewrite HTTP to HTTPS RewriteCond %{HTTPS} !=on RewriteRule ^(.*) https://%{SERVER_NAME}/$1 [R,L] &lt;/IfModule&gt; # END WordPress </code></pre> <p>Any idea what I could be doing wrong?</p>
[ { "answer_id": 310763, "author": "MrWhite", "author_id": 8259, "author_profile": "https://wordpress.stackexchange.com/users/8259", "pm_score": 3, "selected": true, "text": "<p>You've put the code in the wrong place. The HTTP to HTTPS directives must go <em>before</em> the WordPress front...
2018/08/07
[ "https://wordpress.stackexchange.com/questions/310761", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/145165/" ]
I have the following setup in my `.htaccess` file, but I am still able to go to my site via `http:` ``` # BEGIN WordPress <IfModule mod_rewrite.c> RewriteEngine On RewriteBase / RewriteRule ^index\.php$ - [L] RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule . /index.php [L] # Rewrite HTTP to HTTPS RewriteCond %{HTTPS} !=on RewriteRule ^(.*) https://%{SERVER_NAME}/$1 [R,L] </IfModule> # END WordPress ``` Any idea what I could be doing wrong?
You've put the code in the wrong place. The HTTP to HTTPS directives must go *before* the WordPress front-controller, otherwise it's simply never going to get processed for anything other than direct file requests. Your custom directives should also be outside the `# BEGIN WordPress` block, otherwise WordPress itself is likely to override your directives in a future update. For example: ``` # Redirect HTTP to HTTPS RewriteCond %{HTTPS} !=on RewriteRule (.*) https://%{SERVER_NAME}/$1 [R,L] # BEGIN WordPress <IfModule mod_rewrite.c> RewriteEngine On RewriteBase / RewriteRule ^index\.php$ - [L] RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule . /index.php [L] </IfModule> # END WordPress ``` It is a "redirect", not a "rewrite". Change the `R` to `R=301` when you are sure it's working OK (as this should ultimately be a *permanent* redirect).
310,774
<p>I have a Custom Post Type all set up. I would like the slug to be the same as a page name, because all of these CPT's will be queried on that particular page (/team-members).</p> <p>If I set the Custom Post Type slug to the page URL, that particular page doesn't load the page template anymore. It loads a broken post template.</p> <p>My Custom Post Type rewrite:</p> <pre><code>$rewrite = array( 'slug' =&gt; 'team-members', 'with_front' =&gt; false, 'pages' =&gt; false, 'feeds' =&gt; false, ); </code></pre> <p>This allows me to generate the <strong>proper URL</strong> of: <a href="http://www.example.org/team-members/bob-jones" rel="nofollow noreferrer">http://www.example.org/team-members/bob-jones</a></p> <p>The problem now is when I try to access the page: <a href="http://www.example.org/team-members/" rel="nofollow noreferrer">http://www.example.org/team-members/</a>, it does not render the correct page template file (aptly titled <code>page-team-members.php</code>). Saving permalink settings didn't work.</p> <p><strong>How can I create the URL slug of my Custom Post Type to not interfere with a page titled the exact same thing?</strong></p>
[ { "answer_id": 310802, "author": "Jacob Peattie", "author_id": 39152, "author_profile": "https://wordpress.stackexchange.com/users/39152", "pm_score": 3, "selected": true, "text": "<p>What is appearing at <a href=\"http://www.example.org/team-members/\" rel=\"nofollow noreferrer\">http:/...
2018/08/07
[ "https://wordpress.stackexchange.com/questions/310774", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/122225/" ]
I have a Custom Post Type all set up. I would like the slug to be the same as a page name, because all of these CPT's will be queried on that particular page (/team-members). If I set the Custom Post Type slug to the page URL, that particular page doesn't load the page template anymore. It loads a broken post template. My Custom Post Type rewrite: ``` $rewrite = array( 'slug' => 'team-members', 'with_front' => false, 'pages' => false, 'feeds' => false, ); ``` This allows me to generate the **proper URL** of: <http://www.example.org/team-members/bob-jones> The problem now is when I try to access the page: <http://www.example.org/team-members/>, it does not render the correct page template file (aptly titled `page-team-members.php`). Saving permalink settings didn't work. **How can I create the URL slug of my Custom Post Type to not interfere with a page titled the exact same thing?**
What is appearing at <http://www.example.org/team-members/> is the 'post type archive' for your post type. It's the automatically generated list of posts created by WordPress. If you don't want the post type to have an archive you can disable the archive by setting the `has_archive` argument to false: ``` register_post_type( 'post_type_name', array( 'has_archive' => false, ) ); ``` Now you can create a page at /team-members without a conflict.
310,865
<p>I am creating a theme and i have added custom hooks to make the developement easier. when using the code in functions it works in all pages. the code is below</p> <pre><code>add_action('before_footer','post_prev_nex'); function post_prev_nex(){ the_post_navigation(); } </code></pre> <p>But when i try to put a conditional, it doesnt work.</p> <pre><code>if (is_singular()) { add_action('before_footer','post_prev_nex'); function post_prev_nex(){ the_post_navigation(); } } </code></pre> <p>what is the problem here. Thanks in advance</p>
[ { "answer_id": 310867, "author": "nmr", "author_id": 147428, "author_profile": "https://wordpress.stackexchange.com/users/147428", "pm_score": 3, "selected": true, "text": "<p>Put condition inside your function:</p>\n\n<pre><code>add_action('before_footer','post_prev_nex');\nfunction pos...
2018/08/08
[ "https://wordpress.stackexchange.com/questions/310865", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/140102/" ]
I am creating a theme and i have added custom hooks to make the developement easier. when using the code in functions it works in all pages. the code is below ``` add_action('before_footer','post_prev_nex'); function post_prev_nex(){ the_post_navigation(); } ``` But when i try to put a conditional, it doesnt work. ``` if (is_singular()) { add_action('before_footer','post_prev_nex'); function post_prev_nex(){ the_post_navigation(); } } ``` what is the problem here. Thanks in advance
Put condition inside your function: ``` add_action('before_footer','post_prev_nex'); function post_prev_nex() { if (is_singular()) the_post_navigation(); } ``` In your version `is_singular()` is executed when `functions.php` file is loaded, not while displaying the page.
310,866
<p>I am using contact for 7 to create form. Currently I am auto completing value under text name field from Custom post type title, see below:</p> <pre><code>$post_ids = new WP_Query(array( 'post_type' =&gt; 'Buyers', // replace with CPT name 'fields' =&gt; 'fname' // replace with custom field name )); $name = array(); // go through each of the retrieved ids and get the title if ($post_ids-&gt;have_posts()): foreach( $post_ids-&gt;posts as $id): // get the post title, and apply any filters which plugins may have added // (get_the_title returns unfiltered value) $name[] = apply_filters('the_title', get_the_title($id)); endforeach; endif; &lt;script&gt; $( "#autocomplete" ).autocomplete({ source: &lt;?php echo json_encode($name); ?&gt; }); &lt;/script&gt; </code></pre> <p>Now I want to auto fill other form fields(i.e last name, address, contact info etc. ) with custom field values from post, based on above selected post title. How can we achieve this? </p> <p>I want something below:</p> <pre><code>&lt;label&gt; Your Name &lt;/label&gt; &lt;input type="text" id="name" name="name" /&gt; &lt;input readonly="readonly" type="text" id="iprice" name="iprice" size="5"&gt; &lt;input readonly="readonly" type="text" id="icode" name="icode" size="3"&gt; [submit "Send"] $(function() { $('#iprice').val(""); $('#icode').val(""); $("#name").autocomplete({ source: [{"label":"Air Soft Gun","price":"212","abbrev":"BMW"}, {"label":"Pepsi Cola Hat","price":"24","abbrev":"CRY"}, {"label":"Candle Lights Dinner","price":"780","abbrev":"NSS"}, {"label":"Pork Meat Ball","price":"178","abbrev":"SZK"}, {"label":"Granny Health Supplement","price":"24","abbrev":"TYT"}], minLength: 2, select: function(event, ui) { $('#iprice').val(ui.item.price); $('#icode').val(ui.item.abbrev); } }); $["ui"]["autocomplete"].prototype["_renderItem"] = function( ul, item) { return $( "&lt;li&gt;&lt;/li&gt;" ) .data( "item.autocomplete", item ) .append( $( "&lt;a&gt;&lt;/a&gt;" ).html( item.label ) ) .appendTo( ul ); }; }); </code></pre> <p>Label will be my post title and based on selected post tiltle, display custom fields value under price and icode.</p> <p>Any help would be appreciated. Thank you in advance.</p>
[ { "answer_id": 310867, "author": "nmr", "author_id": 147428, "author_profile": "https://wordpress.stackexchange.com/users/147428", "pm_score": 3, "selected": true, "text": "<p>Put condition inside your function:</p>\n\n<pre><code>add_action('before_footer','post_prev_nex');\nfunction pos...
2018/08/08
[ "https://wordpress.stackexchange.com/questions/310866", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/123547/" ]
I am using contact for 7 to create form. Currently I am auto completing value under text name field from Custom post type title, see below: ``` $post_ids = new WP_Query(array( 'post_type' => 'Buyers', // replace with CPT name 'fields' => 'fname' // replace with custom field name )); $name = array(); // go through each of the retrieved ids and get the title if ($post_ids->have_posts()): foreach( $post_ids->posts as $id): // get the post title, and apply any filters which plugins may have added // (get_the_title returns unfiltered value) $name[] = apply_filters('the_title', get_the_title($id)); endforeach; endif; <script> $( "#autocomplete" ).autocomplete({ source: <?php echo json_encode($name); ?> }); </script> ``` Now I want to auto fill other form fields(i.e last name, address, contact info etc. ) with custom field values from post, based on above selected post title. How can we achieve this? I want something below: ``` <label> Your Name </label> <input type="text" id="name" name="name" /> <input readonly="readonly" type="text" id="iprice" name="iprice" size="5"> <input readonly="readonly" type="text" id="icode" name="icode" size="3"> [submit "Send"] $(function() { $('#iprice').val(""); $('#icode').val(""); $("#name").autocomplete({ source: [{"label":"Air Soft Gun","price":"212","abbrev":"BMW"}, {"label":"Pepsi Cola Hat","price":"24","abbrev":"CRY"}, {"label":"Candle Lights Dinner","price":"780","abbrev":"NSS"}, {"label":"Pork Meat Ball","price":"178","abbrev":"SZK"}, {"label":"Granny Health Supplement","price":"24","abbrev":"TYT"}], minLength: 2, select: function(event, ui) { $('#iprice').val(ui.item.price); $('#icode').val(ui.item.abbrev); } }); $["ui"]["autocomplete"].prototype["_renderItem"] = function( ul, item) { return $( "<li></li>" ) .data( "item.autocomplete", item ) .append( $( "<a></a>" ).html( item.label ) ) .appendTo( ul ); }; }); ``` Label will be my post title and based on selected post tiltle, display custom fields value under price and icode. Any help would be appreciated. Thank you in advance.
Put condition inside your function: ``` add_action('before_footer','post_prev_nex'); function post_prev_nex() { if (is_singular()) the_post_navigation(); } ``` In your version `is_singular()` is executed when `functions.php` file is loaded, not while displaying the page.
310,874
<p>I have created a post taxonomy in functions.php called 'leadership' and then tagged posts with three different labels. I have a team page on which I want to place three links (each slugged to a label in the taxonomy).</p> <ul> <li>Corporate</li> <li>Sales</li> <li>Support</li> </ul> <p>So that when the above word is clicked, the featured image for each post with that label becomes visible on the page.</p> <p>So there's three basic elements (I think):</p> <ol> <li>Calling all the post data for the specified taxonomic label</li> <li>Generating a link that calls the featured images for those posts</li> <li>Having the content appear/disappear based on which link is clicked</li> </ol> <p><em>While I've done #2 and #3 individually before, my head is swimming trying to figure out how to merge all the elements together.</em></p> <p>Can someone give me some pointers, beyond the codex which I've read thru already? And maybe even some sample code - especially for #1 and #2?</p> <p><strong>And the dream...</strong> I'd love to implement it as two shortcodes - one for the link and one for the display - so that I can reuse it in other areas of the website.</p>
[ { "answer_id": 310896, "author": "Andrea Somovigo", "author_id": 64435, "author_profile": "https://wordpress.stackexchange.com/users/64435", "pm_score": 3, "selected": true, "text": "<p>Something quite rough that needs improvement but can give you a starting point, if I've understood you...
2018/08/08
[ "https://wordpress.stackexchange.com/questions/310874", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/35991/" ]
I have created a post taxonomy in functions.php called 'leadership' and then tagged posts with three different labels. I have a team page on which I want to place three links (each slugged to a label in the taxonomy). * Corporate * Sales * Support So that when the above word is clicked, the featured image for each post with that label becomes visible on the page. So there's three basic elements (I think): 1. Calling all the post data for the specified taxonomic label 2. Generating a link that calls the featured images for those posts 3. Having the content appear/disappear based on which link is clicked *While I've done #2 and #3 individually before, my head is swimming trying to figure out how to merge all the elements together.* Can someone give me some pointers, beyond the codex which I've read thru already? And maybe even some sample code - especially for #1 and #2? **And the dream...** I'd love to implement it as two shortcodes - one for the link and one for the display - so that I can reuse it in other areas of the website.
Something quite rough that needs improvement but can give you a starting point, if I've understood your needs: use `[dr]` as shortcode marker where you want ``` function my_dream_shortcode($atts, $content = null) { ob_start(); ?> <ul> <li class="button" onClick="get_data('corporate')">Corporate</li> <li class="button" onClick="get_data('sales')">Sales</li> <li class="button" onClick="get_data('support')">Support</li> </ul> <div class="my_plugin_result"></div> <style> li.button{ list-style:none; padding:4px 10px; background-color:cadetblue; margin:10px; float:left; min-width: 160px; text-align: center; cursor:pointer; } .my_plugin_result figure{ float:left; padding:4px; background:#ccc; } </style> <script> var myPluginAjaxUrl = '<?php echo admin_url( 'admin-ajax.php'); ?>'; function get_data(term) { jQuery.ajax({ url: myPluginAjaxUrl, data: { action: 'get_data_for_my_shortcode', term: term } }).done(function (response) { console.log(response) jQuery(".my_plugin_result").html(response); }); } </script> <?php return ob_get_clean(); } add_shortcode("dr", "my_dream_shortcode"); add_action('wp_ajax_nopriv_get_data_for_my_shortcode', 'get_data_for_my_shortcode'); //add_action('wp_ajax_get_data_for_my_shortcode', 'get_data_for_my_shortcode'); function get_data_for_my_shortcode(){ global $wpdb; $args = array( 'post_type' => 'post', 'tax_query' => array( array( 'taxonomy' => 'leadership', 'field' => 'slug', 'terms' => $_REQUEST['term'] ) ) ); $response=""; $query = new WP_Query( $args ); while($query->have_posts() ): if($query->have_posts() ): $query->the_post(); $response.='<figure><img src="'.get_the_post_thumbnail_url(get_the_ID(),'medium').'"/></figure>'; endif; endwhile; echo $response; die(); } ``` Thanks to [@bulldog](https://wordpress.stackexchange.com/users/35991/bulldog) edited code to work effectively in front-end
310,881
<p>I have a Custom Post Type called <code>books</code>. This Custom Post Type has a taxonomy called <code>book_category</code>. As of now, and in the foreseeable future, there are 5 categories each book can be filtered under.</p> <p>Now, each of these categories have their own respective page that will query the books based on respective category (among other ancillary information pertaining to each category).</p> <p>In my code below, I made an attempt to query posts based on <code>is_page()</code>. While this DOES work... something is telling me there's a more efficient / proper way of handling this.</p> <pre><code>&lt;?php if (is_page('horror')) { $theTermBasedOnPage = 'horror'; } elseif (is_page('comedy')) { $theTermBasedOnPage = 'comedy'; } elseif (is_page('romantic')) { $theTermBasedOnPage = 'romantic'; } elseif (is_page('nonfiction')) { $theTermBasedOnPage = 'nonfiction'; } elseif (is_page('drama')) { $theTermBasedOnPage = 'drama'; } $args = array( 'posts_per_page' =&gt; -1, 'post_type' =&gt; 'books', 'post_status' =&gt; 'publish', 'tax_query' =&gt; array( array( 'taxonomy' =&gt; 'book_category', 'terms' =&gt; $theTermBasedOnPage, ), ), ); ?&gt; </code></pre> <p><strong>What is the best way to query posts (Custom Post Type > Taxonomy) based on page?</strong></p>
[ { "answer_id": 310882, "author": "David Sword", "author_id": 132362, "author_profile": "https://wordpress.stackexchange.com/users/132362", "pm_score": 3, "selected": true, "text": "<p>To make that more efficient, instead of arguing the current page slug, you just place the current slug a...
2018/08/08
[ "https://wordpress.stackexchange.com/questions/310881", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/122225/" ]
I have a Custom Post Type called `books`. This Custom Post Type has a taxonomy called `book_category`. As of now, and in the foreseeable future, there are 5 categories each book can be filtered under. Now, each of these categories have their own respective page that will query the books based on respective category (among other ancillary information pertaining to each category). In my code below, I made an attempt to query posts based on `is_page()`. While this DOES work... something is telling me there's a more efficient / proper way of handling this. ``` <?php if (is_page('horror')) { $theTermBasedOnPage = 'horror'; } elseif (is_page('comedy')) { $theTermBasedOnPage = 'comedy'; } elseif (is_page('romantic')) { $theTermBasedOnPage = 'romantic'; } elseif (is_page('nonfiction')) { $theTermBasedOnPage = 'nonfiction'; } elseif (is_page('drama')) { $theTermBasedOnPage = 'drama'; } $args = array( 'posts_per_page' => -1, 'post_type' => 'books', 'post_status' => 'publish', 'tax_query' => array( array( 'taxonomy' => 'book_category', 'terms' => $theTermBasedOnPage, ), ), ); ?> ``` **What is the best way to query posts (Custom Post Type > Taxonomy) based on page?**
To make that more efficient, instead of arguing the current page slug, you just place the current slug as the tax\_query's terms value. Something like: ``` global $post; $args = array( 'posts_per_page' => -1, 'post_type' => 'books', 'post_status' => 'publish', 'tax_query' => array( array( 'taxonomy' => 'book_category', 'field' => 'slug', 'terms' => $post->post_name, // which'd be `horror` or `comedy`, etc ), ), ); ``` Note that there's high probability of human error doing things this way: for example having a page of `nonfiction` but a book\_category term of `non-fiction` could break the logic and cause problems. I don't know the context of what you're working on, but if the goal is just *"each of these categories have their own respective page"* you do not need to build this custom-query-with-manual-page-relation for each term. WordPress taxonomies and terms will have their own URLs if you've [registered](https://codex.wordpress.org/Function_Reference/register_taxonomy) the taxonomy as `public` and `publicly_queryable`. (Guessing here, but) You can probably visit `your-site.com/book_category/horror/` and see the list of horror books. You can then customize the template files for all terms or individually using the [WordPress template hierarchy](https://developer.wordpress.org/themes/basics/template-hierarchy/) as reference.
310,886
<p>I'm creating a shipping method where the customer can choose a time for the delivery to happen. This choice can be made on product page, cart and checkout. When chosen, it updates a session value with ajax. </p> <p>The problem however is that I need to re-calculate shipping on cart and checkout if the time is changed, but woocommerce is not calculating shipping unless items are added or removed from the cart.</p> <p>It wont even recalculate if i refresh the page, I have to manually change the content of the cart for it to fire.</p> <p>Any suggestions?</p>
[ { "answer_id": 332944, "author": "user164084", "author_id": 164084, "author_profile": "https://wordpress.stackexchange.com/users/164084", "pm_score": 2, "selected": false, "text": "<p>I also have the same issue when I created a shipping method and what I did is on my function for the aja...
2018/08/08
[ "https://wordpress.stackexchange.com/questions/310886", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/90442/" ]
I'm creating a shipping method where the customer can choose a time for the delivery to happen. This choice can be made on product page, cart and checkout. When chosen, it updates a session value with ajax. The problem however is that I need to re-calculate shipping on cart and checkout if the time is changed, but woocommerce is not calculating shipping unless items are added or removed from the cart. It wont even recalculate if i refresh the page, I have to manually change the content of the cart for it to fire. Any suggestions?
I also have the same issue when I created a shipping method and what I did is on my function for the ajax call I add something just to have an update on the cart: ``` global $woocommerce; $packages = $woocommerce->cart->get_shipping_packages(); foreach( $packages as $package_key => $package ) { $session_key = 'shipping_for_package_'.$package_key; $stored_rates = WC()->session->__unset( $session_key ); } ```
310,894
<p>If you create a post whose title has an accent in it and some other unicode character in it, eg <code>à 漢語 title thing</code>, its slug (permalink) will become <code>a-漢語-title-thing</code>... ie, the <code>à</code> was converted into a regular <code>a</code>, but those unicode Chinese characters were left intact. Why doesn't WordPress leave the accented characters alone? I created a code snippet to tell WordPress to leave them alone</p> <pre><code>function mn_sanitize_title($modified_title, $original_title, $context) { // the $modified_title may have had accents removed, but not the $original_title return $original_title; } // set this filter to run BEFORE WP already ran the title through `sanitize_title_with_dashes` add_filter('sanitize_title', 'mn_sanitize_title', 5, 3); </code></pre> <p>and it seems to work fine (accented characters are left intact in post slugs) so I'm wondering why WordPress developers removed accented characters from post slugs in the first place?</p>
[ { "answer_id": 332944, "author": "user164084", "author_id": 164084, "author_profile": "https://wordpress.stackexchange.com/users/164084", "pm_score": 2, "selected": false, "text": "<p>I also have the same issue when I created a shipping method and what I did is on my function for the aja...
2018/08/08
[ "https://wordpress.stackexchange.com/questions/310894", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/52760/" ]
If you create a post whose title has an accent in it and some other unicode character in it, eg `à 漢語 title thing`, its slug (permalink) will become `a-漢語-title-thing`... ie, the `à` was converted into a regular `a`, but those unicode Chinese characters were left intact. Why doesn't WordPress leave the accented characters alone? I created a code snippet to tell WordPress to leave them alone ``` function mn_sanitize_title($modified_title, $original_title, $context) { // the $modified_title may have had accents removed, but not the $original_title return $original_title; } // set this filter to run BEFORE WP already ran the title through `sanitize_title_with_dashes` add_filter('sanitize_title', 'mn_sanitize_title', 5, 3); ``` and it seems to work fine (accented characters are left intact in post slugs) so I'm wondering why WordPress developers removed accented characters from post slugs in the first place?
I also have the same issue when I created a shipping method and what I did is on my function for the ajax call I add something just to have an update on the cart: ``` global $woocommerce; $packages = $woocommerce->cart->get_shipping_packages(); foreach( $packages as $package_key => $package ) { $session_key = 'shipping_for_package_'.$package_key; $stored_rates = WC()->session->__unset( $session_key ); } ```
310,943
<p>I'm looking for a way to open every/any link to a blog post in a lightbox/modal globally and without having to any extra classes or rel attribute to the link element. I know I can access this info from within the page or post itself, but is there a way, through some sort of AJAX call I presume, to get this data before the request for the content is actually made so that when I do retrieve the response content, I can either just display it normally in the same browser tab (in the case of a Page) or trigger a lightbox and populate it with the content instead.</p> <p>At first I was thinking about using regular expression matching on the link element's href and if it matched something looking like a blog post URL, open the lightbox. that seems pretty hacky tho and is definitely not bulletproof.</p> <p>This is what I've got so far...</p> <p><strong>JavaScript:</strong></p> <pre><code>$('a:not([href^="#"])[href]').click(function(e) { e.preventDefault(); var $this = $(this); var lnk = $this.attr('href'); var jqxhr = $.post("/wp-content/themes/mist-child/php/get-post-type.php", {url: lnk}); jqxhr.done(function(data) { if(data === 'post') { $.prettyPhoto.open(lnk + '?iframe=true&amp;width=80%&amp;height=80%'); } }); }); </code></pre> <p><br><br> <strong>get-post-type.php</strong> (/wp-content/themes/CHILD_THEME/php/...)</p> <pre><code>&lt;?php require_once(rtrim($_SERVER['DOCUMENT_ROOT'], '/') . '/wp-load.php'); $url = $_POST['url']; $postid = url_to_postid($url); echo(get_post_type($postid)); ?&gt; </code></pre> <p>The part where Posts get opened in the lightbox is working. It's a little slow - I'm guessing that loading wp-load.php adds quite a bit of overhead. is there any way to add my PHP somewhere in functions.php and call that function (with arguments) via AJAX?</p> <p>I know it needs some work, but as far as a prototype goes, am I moving in the right direction? Please feel free to shoot this full of as many holes as you can find.</p>
[ { "answer_id": 311001, "author": "Balas", "author_id": 17849, "author_profile": "https://wordpress.stackexchange.com/users/17849", "pm_score": 1, "selected": false, "text": "<p>The wordpress way solution is</p>\n\n<pre><code> // put this in header.php\nvar ajax_url =\"&lt;?php echo admin...
2018/08/09
[ "https://wordpress.stackexchange.com/questions/310943", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/118789/" ]
I'm looking for a way to open every/any link to a blog post in a lightbox/modal globally and without having to any extra classes or rel attribute to the link element. I know I can access this info from within the page or post itself, but is there a way, through some sort of AJAX call I presume, to get this data before the request for the content is actually made so that when I do retrieve the response content, I can either just display it normally in the same browser tab (in the case of a Page) or trigger a lightbox and populate it with the content instead. At first I was thinking about using regular expression matching on the link element's href and if it matched something looking like a blog post URL, open the lightbox. that seems pretty hacky tho and is definitely not bulletproof. This is what I've got so far... **JavaScript:** ``` $('a:not([href^="#"])[href]').click(function(e) { e.preventDefault(); var $this = $(this); var lnk = $this.attr('href'); var jqxhr = $.post("/wp-content/themes/mist-child/php/get-post-type.php", {url: lnk}); jqxhr.done(function(data) { if(data === 'post') { $.prettyPhoto.open(lnk + '?iframe=true&width=80%&height=80%'); } }); }); ``` **get-post-type.php** (/wp-content/themes/CHILD\_THEME/php/...) ``` <?php require_once(rtrim($_SERVER['DOCUMENT_ROOT'], '/') . '/wp-load.php'); $url = $_POST['url']; $postid = url_to_postid($url); echo(get_post_type($postid)); ?> ``` The part where Posts get opened in the lightbox is working. It's a little slow - I'm guessing that loading wp-load.php adds quite a bit of overhead. is there any way to add my PHP somewhere in functions.php and call that function (with arguments) via AJAX? I know it needs some work, but as far as a prototype goes, am I moving in the right direction? Please feel free to shoot this full of as many holes as you can find.
Going with @milo's suggestion in the comments of the OP, I added a function to functions.php that rewrites URLs output by the API with a specific query string key/value when the `post_type` is `post`. This allows me to see this on the front end quite easily and take the appropriate action on the link depending on the absence/presence of said query string data. In this case, the frontend script finds all the elements "marked" as linking to `post`s (and not `page`s) and simply opens their `href` in a lightbox. **SO** much simpler than making several AJAX calls when the page is rendered to check the `post_type` for various links on the page. **functions.php** ``` function append_query_string( $url, $post, $leavename=false ) { if ( $post->post_type == 'post' ) { $url = add_query_arg( 'blogLnk', '1', $url ); } return $url; } add_filter( 'post_link', 'append_query_string', 10, 3 ); ``` **JavaScript** ``` var blogLnks = [ 'a[hrf*="blogLnk=1"]', 'a[rel="blogLnk"]' ]; var $blogLnks = $(blogLnks.join(',')); $blogLnks.click(function(e) { e.preventDefault(); console.log('click - open me in lightbox'); var $this = $(this); var qs = '?iframe=true&width=80%&height=90%'; var lnk = $this.attr('href'); $.prettyPhoto.open(lnk + qs); }); ```
310,953
<p>I have successfully forbidden access to any kind of author pages whether trough <code>/author/username/</code> or the <code>?author={#id}</code> query string.</p> <p>I did this with this added to the beginning of my htaccess file:</p> <pre><code>&lt;IfModule mod_rewrite.c&gt; RewriteCond %{REQUEST_URI} ^/author/ RewriteRule .* - [F] RewriteCond %{QUERY_STRING} ^author=([0-9]*) RewriteRule .* - [F] &lt;/IfModule&gt; </code></pre> <p>But the same doesn't work when wordpress is physically in a subdirectory.</p> <p>The first part works:</p> <pre><code>RewriteCond %{REQUEST_URI} ^/subdir/author/ RewriteRule .* - [F] </code></pre> <p>But no matter how I try to edit the second part, the <code>/subdir/?author=1</code> takes me to the <code>/subdir/usernumber1/</code> and that is forbidden alright, but this defeats the whole purpose of this.</p> <p>Any ideas?</p> <p><strong>Edit:</strong></p> <p>Yes, I was trying to prevent user names from showing.</p> <p>In the last moment yesterday I was able to come up with a solution:</p> <pre><code>&lt;IfModule mod_rewrite.c&gt; RewriteCond %{REQUEST_URI} ^/subdir/author/ RewriteRule .* - [F] RewriteCond %{REQUEST_URI} ^/subdir/ RewriteCond %{QUERY_STRING} ^author=([0-9]*) RewriteRule .* - [F] &lt;/IfModule&gt; </code></pre> <p>I may be able to shorten it based on the answers below(for which I'm very thankful).</p> <p>And yes this is placed in the subdir.</p> <p>The first snippet was placed in the root dir, which did not worked(or maybe some of the solutions that I tried along the way actually worked but I had the redirect to the author page already cached, I don't know for sure).</p>
[ { "answer_id": 310955, "author": "Iceable", "author_id": 136263, "author_profile": "https://wordpress.stackexchange.com/users/136263", "pm_score": 1, "selected": false, "text": "<p>The question is about doing this with <code>.htaccess</code>, but why not disabling author pages from withi...
2018/08/09
[ "https://wordpress.stackexchange.com/questions/310953", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/133528/" ]
I have successfully forbidden access to any kind of author pages whether trough `/author/username/` or the `?author={#id}` query string. I did this with this added to the beginning of my htaccess file: ``` <IfModule mod_rewrite.c> RewriteCond %{REQUEST_URI} ^/author/ RewriteRule .* - [F] RewriteCond %{QUERY_STRING} ^author=([0-9]*) RewriteRule .* - [F] </IfModule> ``` But the same doesn't work when wordpress is physically in a subdirectory. The first part works: ``` RewriteCond %{REQUEST_URI} ^/subdir/author/ RewriteRule .* - [F] ``` But no matter how I try to edit the second part, the `/subdir/?author=1` takes me to the `/subdir/usernumber1/` and that is forbidden alright, but this defeats the whole purpose of this. Any ideas? **Edit:** Yes, I was trying to prevent user names from showing. In the last moment yesterday I was able to come up with a solution: ``` <IfModule mod_rewrite.c> RewriteCond %{REQUEST_URI} ^/subdir/author/ RewriteRule .* - [F] RewriteCond %{REQUEST_URI} ^/subdir/ RewriteCond %{QUERY_STRING} ^author=([0-9]*) RewriteRule .* - [F] </IfModule> ``` I may be able to shorten it based on the answers below(for which I'm very thankful). And yes this is placed in the subdir. The first snippet was placed in the root dir, which did not worked(or maybe some of the solutions that I tried along the way actually worked but I had the redirect to the author page already cached, I don't know for sure).
The question is about doing this with `.htaccess`, but why not disabling author pages from within WordPress instead? This would achieve the same result while making the subdirectory concern irrelevant altogether (and also works regardless of permalink structure settings) Sample code that sets all urls to author pages to a 404 error: ``` add_action( 'template_redirect', function() { if ( isset( $_GET['author'] ) || is_author() ) { global $wp_query; $wp_query->set_404(); status_header( 404 ); nocache_headers(); } }, 1 ); add_filter( 'author_link', function() { return '#'; }, 99 ); add_filter( 'the_author_posts_link', '__return_empty_string', 99 ); ``` (code taken from this plugin: [Disable Author Archives](https://wordpress.org/plugins/disable-author-archives/))
310,957
<p>i want to ask a simple question that what to do if i have to check whether a pliugin is installed. for example i want to run a code, which says,</p> <p>if Gutenberg is installed, then run the following code else not.</p> <p>i have created this code, but not sure will this work or not</p> <pre><code> if(defined('Gutenberg')) { } </code></pre> <p>is this the right way or is there any other way to that. thanks in advance</p>
[ { "answer_id": 310961, "author": "Mark Kaplun", "author_id": 23970, "author_profile": "https://wordpress.stackexchange.com/users/23970", "pm_score": 4, "selected": true, "text": "<p>Checking if a plugin is installed is always a bad idea as plugins might be installed but for whatever reas...
2018/08/09
[ "https://wordpress.stackexchange.com/questions/310957", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/140102/" ]
i want to ask a simple question that what to do if i have to check whether a pliugin is installed. for example i want to run a code, which says, if Gutenberg is installed, then run the following code else not. i have created this code, but not sure will this work or not ``` if(defined('Gutenberg')) { } ``` is this the right way or is there any other way to that. thanks in advance
Checking if a plugin is installed is always a bad idea as plugins might be installed but for whatever reason not function, or function in different way than you might expect. Specifically for gutenberg as it stands right now for example, post types that are not exposed in the REST API can not be edited by gutenberg. As always, if you have a functionality that depends on a plugin you should hook to its actions and filters to avoid the need to guess if it is active or not (the fact that the action is "called" is the best indication for activity), or ask the plugin author to add the kind of action/filter you might find useful.
310,969
<p>I need a wordpress function that search all the posts inside my website and if one or multiple posts have the category ID (example 25) <code>echo "yes"</code>, <code>else echo "no"</code> </p> <p>I was trying to do: </p> <pre><code>if ( has_category(25) ) { echo "OK"; } else { echo "NO OK"; } </code></pre> <p>But dont work</p> <p>EDIT: My goal is to show comments section only if the category is "25" the other posts has not to show comments section</p>
[ { "answer_id": 310961, "author": "Mark Kaplun", "author_id": 23970, "author_profile": "https://wordpress.stackexchange.com/users/23970", "pm_score": 4, "selected": true, "text": "<p>Checking if a plugin is installed is always a bad idea as plugins might be installed but for whatever reas...
2018/08/09
[ "https://wordpress.stackexchange.com/questions/310969", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/135486/" ]
I need a wordpress function that search all the posts inside my website and if one or multiple posts have the category ID (example 25) `echo "yes"`, `else echo "no"` I was trying to do: ``` if ( has_category(25) ) { echo "OK"; } else { echo "NO OK"; } ``` But dont work EDIT: My goal is to show comments section only if the category is "25" the other posts has not to show comments section
Checking if a plugin is installed is always a bad idea as plugins might be installed but for whatever reason not function, or function in different way than you might expect. Specifically for gutenberg as it stands right now for example, post types that are not exposed in the REST API can not be edited by gutenberg. As always, if you have a functionality that depends on a plugin you should hook to its actions and filters to avoid the need to guess if it is active or not (the fact that the action is "called" is the best indication for activity), or ask the plugin author to add the kind of action/filter you might find useful.
310,980
<p>I'm trying to use the <code>&lt;?php rewind_posts(); ?&gt;</code> feature to use two loops on my homepage template. Does anyone know how to stop the first loop after the latest post? </p> <p>Here is my Code:</p> <pre><code>&lt;?php if (have_posts()) : while (have_posts()) : the_post(); ?&gt; &lt;h1&gt;&lt;a href="&lt;?php the_permalink(); ?&gt;"&gt;&lt;?php the_title(); ?&gt;&lt;/a&gt;&lt;/h1&gt; &lt;?php endwhile; endif; ?&gt; &lt;?php rewind_posts(); ?&gt; &lt;?php if ( have_posts() ) : if ( is_home() &amp;&amp; ! is_front_page() ) : ?&gt; &lt;header&gt; &lt;h1 class="page-title screen-reader-text"&gt; &lt;?php single_post_title(); ?&gt; &lt;/h1&gt; &lt;/header&gt; &lt;?php endif; while ( have_posts() ) : the_post(); get_template_part( 'template-parts/content-home', get_post_type() ); endwhile; the_posts_navigation(); else : get_template_part( 'template-parts/content', 'none' ); endif; ?&gt; </code></pre>
[ { "answer_id": 311009, "author": "Balas", "author_id": 17849, "author_profile": "https://wordpress.stackexchange.com/users/17849", "pm_score": 1, "selected": true, "text": "<p>Try like this which fill skip first post:</p>\n\n<pre><code>$i = 0;\nwhile ( have_posts() ) :\n the_post();\n...
2018/08/09
[ "https://wordpress.stackexchange.com/questions/310980", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/148419/" ]
I'm trying to use the `<?php rewind_posts(); ?>` feature to use two loops on my homepage template. Does anyone know how to stop the first loop after the latest post? Here is my Code: ``` <?php if (have_posts()) : while (have_posts()) : the_post(); ?> <h1><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></h1> <?php endwhile; endif; ?> <?php rewind_posts(); ?> <?php if ( have_posts() ) : if ( is_home() && ! is_front_page() ) : ?> <header> <h1 class="page-title screen-reader-text"> <?php single_post_title(); ?> </h1> </header> <?php endif; while ( have_posts() ) : the_post(); get_template_part( 'template-parts/content-home', get_post_type() ); endwhile; the_posts_navigation(); else : get_template_part( 'template-parts/content', 'none' ); endif; ?> ```
Try like this which fill skip first post: ``` $i = 0; while ( have_posts() ) : the_post(); if($i > 0) get_template_part( 'template-parts/content-home', get_post_type() ); else { // design your first post as you wish with HTML, CSS the_title(); the_permalink(); the_post_thumbnail(); the_content(); the_author(); the_date(); } $i++; endwhile; ```
311,028
<p>I'm trying to get the url of an image from a MetaBox (plugin) filed on an archive-page. </p> <pre><code>&lt;?php if ( rwmb_meta( 'field-id' ) ) { // Get images $img_srcset_large = rwmb_meta( 'field-id', array( 'size' =&gt; 'image-size', 'limit' =&gt; 1 ) ); echo $img_srcset_large['url'] ?&gt; </code></pre> <p>Unfortunately there is nothing displayed. Can you give me a hint how this code can work on archive-templates? Best</p>
[ { "answer_id": 311009, "author": "Balas", "author_id": 17849, "author_profile": "https://wordpress.stackexchange.com/users/17849", "pm_score": 1, "selected": true, "text": "<p>Try like this which fill skip first post:</p>\n\n<pre><code>$i = 0;\nwhile ( have_posts() ) :\n the_post();\n...
2018/08/10
[ "https://wordpress.stackexchange.com/questions/311028", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/148458/" ]
I'm trying to get the url of an image from a MetaBox (plugin) filed on an archive-page. ``` <?php if ( rwmb_meta( 'field-id' ) ) { // Get images $img_srcset_large = rwmb_meta( 'field-id', array( 'size' => 'image-size', 'limit' => 1 ) ); echo $img_srcset_large['url'] ?> ``` Unfortunately there is nothing displayed. Can you give me a hint how this code can work on archive-templates? Best
Try like this which fill skip first post: ``` $i = 0; while ( have_posts() ) : the_post(); if($i > 0) get_template_part( 'template-parts/content-home', get_post_type() ); else { // design your first post as you wish with HTML, CSS the_title(); the_permalink(); the_post_thumbnail(); the_content(); the_author(); the_date(); } $i++; endwhile; ```
311,035
<p>He everyone i'm a newbie to wordpress/php and have 1 other problem. I am trying to get the date under the post title and not to display the category tags above the title. I tried it to change thing is the index.php but it would not work. How can I fix this for this page <a href="http://www.quintyvandijk.com/gallery/" rel="nofollow noreferrer">http://www.quintyvandijk.com/gallery/</a>.</p> <pre><code>&lt;?php $edgt_blog_type = milieu_edge_get_archive_blog_list_layout(); milieu_edge_include_blog_helper_functions( 'lists', $edgt_blog_type ); $edgt_holder_params = milieu_edge_get_holder_params_blog(); get_header(); milieu_edge_get_title(); ?&gt; &lt;div class="&lt;?php echo esc_attr( $edgt_holder_params['holder'] ); ?&gt;"&gt; &lt;?php do_action( 'milieu_edge_action_after_container_open' ); ?&gt; &lt;div class="&lt;?php echo esc_attr( $edgt_holder_params['inner'] ); ?&gt;"&gt; &lt;?php milieu_edge_get_blog( $edgt_blog_type ); ?&gt; &lt;/div&gt; &lt;?php do_action( 'milieu_edge_action_before_container_close' ); ?&gt; &lt;/div&gt; &lt;?php do_action( 'milieu_edge_action_blog_list_additional_tags' ); ?&gt; &lt;?php get_footer(); ?&gt; </code></pre>
[ { "answer_id": 311009, "author": "Balas", "author_id": 17849, "author_profile": "https://wordpress.stackexchange.com/users/17849", "pm_score": 1, "selected": true, "text": "<p>Try like this which fill skip first post:</p>\n\n<pre><code>$i = 0;\nwhile ( have_posts() ) :\n the_post();\n...
2018/08/10
[ "https://wordpress.stackexchange.com/questions/311035", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/148457/" ]
He everyone i'm a newbie to wordpress/php and have 1 other problem. I am trying to get the date under the post title and not to display the category tags above the title. I tried it to change thing is the index.php but it would not work. How can I fix this for this page <http://www.quintyvandijk.com/gallery/>. ``` <?php $edgt_blog_type = milieu_edge_get_archive_blog_list_layout(); milieu_edge_include_blog_helper_functions( 'lists', $edgt_blog_type ); $edgt_holder_params = milieu_edge_get_holder_params_blog(); get_header(); milieu_edge_get_title(); ?> <div class="<?php echo esc_attr( $edgt_holder_params['holder'] ); ?>"> <?php do_action( 'milieu_edge_action_after_container_open' ); ?> <div class="<?php echo esc_attr( $edgt_holder_params['inner'] ); ?>"> <?php milieu_edge_get_blog( $edgt_blog_type ); ?> </div> <?php do_action( 'milieu_edge_action_before_container_close' ); ?> </div> <?php do_action( 'milieu_edge_action_blog_list_additional_tags' ); ?> <?php get_footer(); ?> ```
Try like this which fill skip first post: ``` $i = 0; while ( have_posts() ) : the_post(); if($i > 0) get_template_part( 'template-parts/content-home', get_post_type() ); else { // design your first post as you wish with HTML, CSS the_title(); the_permalink(); the_post_thumbnail(); the_content(); the_author(); the_date(); } $i++; endwhile; ```
311,044
<p>I am developing a plugin which will show the caller of all the Hooks &amp; Actions on a Page in Wordpress just like QueryMonitor. I know that global $wp_action &amp; $wp_filter has all the information but it does not provide the Caller Component of the Action or Filter.</p> <p>Can you please help me out with this.</p> <p>If you need the Code, Comment down.</p> <p>Thanks in advance.</p> <p>Code : - </p> <pre><code>&lt;?php class MyTracker { static $hooks; static function track_hooks( ) { $filter = current_filter(); if ( ! empty($GLOBALS['wp_filter'][$filter]) ) { foreach ( $GLOBALS['wp_filter'][$filter] as $priority =&gt; $tag_hooks ) { foreach ( $tag_hooks as $hook ) { if ( is_array($hook['function']) ) { if ( is_object($hook['function'][0]) ) { $func = get_class($hook['function'][0]) . '-&gt;' . $hook['function'][1]; } elseif ( is_string($hook['function'][0]) ) { $func = $hook['function'][0] . '::' . $hook['function'][1]; } } elseif( $hook['function'] instanceof Closure ) { $func = 'a closure'; } elseif( is_string($hook['function']) ) { $func = $hook['function']; } self::$hooks[] = 'On hook &lt;b&gt;"' . $filter . '"&lt;/b&gt; run &lt;b&gt;'. $func . '&lt;/b&gt; at priority ' . $priority; } } } } } add_action( 'all', array('MyTracker', 'track_hooks') ); add_action( 'shutdown', function() { echo implode( '&lt;br /&gt;', MyTracker::$hooks ); }, 9999); </code></pre> <p>This displays all the Actions on the Current page, What i Need is that the Execution time by each of these hooks.</p>
[ { "answer_id": 311049, "author": "anmari", "author_id": 3569, "author_profile": "https://wordpress.stackexchange.com/users/3569", "pm_score": 0, "selected": false, "text": "<p>Akash, It sounds like you are want to list out all the plugins &amp; themes that have added actions and filte...
2018/08/10
[ "https://wordpress.stackexchange.com/questions/311044", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/147912/" ]
I am developing a plugin which will show the caller of all the Hooks & Actions on a Page in Wordpress just like QueryMonitor. I know that global $wp\_action & $wp\_filter has all the information but it does not provide the Caller Component of the Action or Filter. Can you please help me out with this. If you need the Code, Comment down. Thanks in advance. Code : - ``` <?php class MyTracker { static $hooks; static function track_hooks( ) { $filter = current_filter(); if ( ! empty($GLOBALS['wp_filter'][$filter]) ) { foreach ( $GLOBALS['wp_filter'][$filter] as $priority => $tag_hooks ) { foreach ( $tag_hooks as $hook ) { if ( is_array($hook['function']) ) { if ( is_object($hook['function'][0]) ) { $func = get_class($hook['function'][0]) . '->' . $hook['function'][1]; } elseif ( is_string($hook['function'][0]) ) { $func = $hook['function'][0] . '::' . $hook['function'][1]; } } elseif( $hook['function'] instanceof Closure ) { $func = 'a closure'; } elseif( is_string($hook['function']) ) { $func = $hook['function']; } self::$hooks[] = 'On hook <b>"' . $filter . '"</b> run <b>'. $func . '</b> at priority ' . $priority; } } } } } add_action( 'all', array('MyTracker', 'track_hooks') ); add_action( 'shutdown', function() { echo implode( '<br />', MyTracker::$hooks ); }, 9999); ``` This displays all the Actions on the Current page, What i Need is that the Execution time by each of these hooks.
As I said in my comment to the question, you can use the PHP internal [ReflectionFunction](https://secure.php.net/manual/en/class.reflectionfunction.php) class to get the filename of the callable. The below code should be a good start to help you. It needs more logic for determining the callbacks and most of that should be abstracted out of the Monitor class anyway. I also didn't write the code that would get the nice name of the theme, plugin, core, or whatever else might have added the hook from the filename. That should be relatively easy to do though once you know the file that added the hook. ``` <?php /** * Plugin Name: Monitor */ namespace WPSE\Monitor; class Monitor { protected $callbacks = []; protected function addCallback( $callback ) { $this->callbacks[] = $callback; } public function shutdown() { var_dump( $this->callbacks ); } public function monitor() { global $wp_filter; $name = \current_filter(); if( ! isset( $wp_filter[ $name ] ) ) { return; } $action = $wp_filter[ $name ]; foreach ( $action->callbacks as $priority => $callbacks ) { foreach( $callbacks as $callback ) { try { if( \is_array( $callback[ 'function' ] ) ) { if( \is_object( $callback[ 'function' ][ 0 ] ) ) { $class = \get_class( $callback[ 'function' ][ 0 ] ); $callback[ 'name' ] = $class . '->' . $callback[ 'function' ][ 1 ] . '()'; $ref = new \ReflectionMethod( $class, $callback[ 'function' ][ 1 ] ); } elseif( \is_string( $callback[ 'function' ][ 0 ] ) ) { $callback[ 'name' ] = $callback[ 'function' ][ 0 ] . '::' . $callback[ 'function' ][ 1 ]; $ref = new \ReflectionMethod( $callback[ 'function' ][ 0 ], $callback[ 'function' ][ 1 ] ); } } elseif( $callback[ 'function' ] instanceOf Closure ) { $callback[ 'name' ] = 'closure'; $ref = new \ReflectionMethod( $callback[ 'function' ] ); } elseif( \is_string( $callback[ 'function' ] ) ) { $callback[ 'name' ] = $callback[ 'function' ] . '()'; $ref = new \ReflectionMethod( $callback[ 'name' ] ); } else{ return; } $callback[ 'filename' ] = $ref->getFileName(); $this->addCallback( $callback ); } catch( \ReflectionException $e ) { $callback['error'] = new \WP_Error( 'reflection_exception', $e->getMessage() ); } } } } } class MonitorInit { private static $monitor; public static function init() { self::$monitor = new Monitor(); \add_action( 'all', [ self::$monitor, 'monitor' ] ); \add_action( 'shutdown', [ self::$monitor, 'shutdown' ] ); } } \add_action( 'plugins_loaded', __NAMESPACE__ . '\MonitorInit::init', 0 ); ``` The `plugins_loaded` hook is the first that's available to regular plugins. So if you want to catch hooks that are added before this, you'll need to do something tricky.
311,076
<p>I initially had a wordpress installation on a free hosting service. After the hosting suffered an attack I got a backup of all files and the database and am recovering the site on my localhost (using wampserver 3.1.0 on windows 10) before I can update it and upload it to my new hosting service.</p> <p>The thing is, links are not working and some (not all) images are not displaying, not even on edit mode, and not at all (I mean, there is not a square indicating a broken image either). As for settings, I set up my wordpress url and site url (in admin console) to point to my new localhost url (<a href="http://localhost/b17_14344318" rel="nofollow noreferrer">http://localhost/b17_14344318</a>). I also used <code>Search-Replace-DB</code> to replace all instances of my old url with my localhost url (the problems existed before I replaced the url using this script).</p> <p>An example of images issue is a facebook logo image I had in my old installation. As it wasn't showing up I tried removing it from my post and re-adding, editing it (on wordpress), deleting it and re-uploading it, changing the file name and re-upload to use this "new file", removing the html code and re-writing it... I also disabled my plugins one by one, and checked if the image showed up, but it didn't. This image (as others that have the same problem) did show up when my site was up on its old hosting service, with the same plugins I have now (however, the Wordpress version I'm using now is newer than the one I had on that hosting).</p> <p>After I add the image through the "add media" button, this is the code it generates:</p> <pre><code>&lt;a href="http://localhost/b17_14344318/2543-2/fb_logo/" rel="attachment wp-att-2549"&gt;&lt;img class="alignnone size-full wp-image-2549" src="http://localhost/b17_14344318/wp-content/uploads/2018/08/fb_logo.png" alt="" width="215" height="215" /&gt;&lt;/a&gt; </code></pre> <p>I tried creating a new page, just in case something was corrupt in the old page I recovered from the backup, but the image is still "invisible". This is how it looks after I add the image through "Add media" button: <a href="https://i.stack.imgur.com/VsmXU.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/VsmXU.png" alt="edit mode"></a></p> <p>And this is the html code behind it: <a href="https://i.stack.imgur.com/362Jh.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/362Jh.png" alt="html code"></a></p> <p>As for links, when clicking on any item (link to a post, a page, a category, etc) I see this un-styled page: <a href="https://i.stack.imgur.com/e3KCm.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/e3KCm.png" alt="links"></a></p> <p>Any ideas on what else I should try?</p>
[ { "answer_id": 311049, "author": "anmari", "author_id": 3569, "author_profile": "https://wordpress.stackexchange.com/users/3569", "pm_score": 0, "selected": false, "text": "<p>Akash, It sounds like you are want to list out all the plugins &amp; themes that have added actions and filte...
2018/08/10
[ "https://wordpress.stackexchange.com/questions/311076", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/148485/" ]
I initially had a wordpress installation on a free hosting service. After the hosting suffered an attack I got a backup of all files and the database and am recovering the site on my localhost (using wampserver 3.1.0 on windows 10) before I can update it and upload it to my new hosting service. The thing is, links are not working and some (not all) images are not displaying, not even on edit mode, and not at all (I mean, there is not a square indicating a broken image either). As for settings, I set up my wordpress url and site url (in admin console) to point to my new localhost url (<http://localhost/b17_14344318>). I also used `Search-Replace-DB` to replace all instances of my old url with my localhost url (the problems existed before I replaced the url using this script). An example of images issue is a facebook logo image I had in my old installation. As it wasn't showing up I tried removing it from my post and re-adding, editing it (on wordpress), deleting it and re-uploading it, changing the file name and re-upload to use this "new file", removing the html code and re-writing it... I also disabled my plugins one by one, and checked if the image showed up, but it didn't. This image (as others that have the same problem) did show up when my site was up on its old hosting service, with the same plugins I have now (however, the Wordpress version I'm using now is newer than the one I had on that hosting). After I add the image through the "add media" button, this is the code it generates: ``` <a href="http://localhost/b17_14344318/2543-2/fb_logo/" rel="attachment wp-att-2549"><img class="alignnone size-full wp-image-2549" src="http://localhost/b17_14344318/wp-content/uploads/2018/08/fb_logo.png" alt="" width="215" height="215" /></a> ``` I tried creating a new page, just in case something was corrupt in the old page I recovered from the backup, but the image is still "invisible". This is how it looks after I add the image through "Add media" button: [![edit mode](https://i.stack.imgur.com/VsmXU.png)](https://i.stack.imgur.com/VsmXU.png) And this is the html code behind it: [![html code](https://i.stack.imgur.com/362Jh.png)](https://i.stack.imgur.com/362Jh.png) As for links, when clicking on any item (link to a post, a page, a category, etc) I see this un-styled page: [![links](https://i.stack.imgur.com/e3KCm.png)](https://i.stack.imgur.com/e3KCm.png) Any ideas on what else I should try?
As I said in my comment to the question, you can use the PHP internal [ReflectionFunction](https://secure.php.net/manual/en/class.reflectionfunction.php) class to get the filename of the callable. The below code should be a good start to help you. It needs more logic for determining the callbacks and most of that should be abstracted out of the Monitor class anyway. I also didn't write the code that would get the nice name of the theme, plugin, core, or whatever else might have added the hook from the filename. That should be relatively easy to do though once you know the file that added the hook. ``` <?php /** * Plugin Name: Monitor */ namespace WPSE\Monitor; class Monitor { protected $callbacks = []; protected function addCallback( $callback ) { $this->callbacks[] = $callback; } public function shutdown() { var_dump( $this->callbacks ); } public function monitor() { global $wp_filter; $name = \current_filter(); if( ! isset( $wp_filter[ $name ] ) ) { return; } $action = $wp_filter[ $name ]; foreach ( $action->callbacks as $priority => $callbacks ) { foreach( $callbacks as $callback ) { try { if( \is_array( $callback[ 'function' ] ) ) { if( \is_object( $callback[ 'function' ][ 0 ] ) ) { $class = \get_class( $callback[ 'function' ][ 0 ] ); $callback[ 'name' ] = $class . '->' . $callback[ 'function' ][ 1 ] . '()'; $ref = new \ReflectionMethod( $class, $callback[ 'function' ][ 1 ] ); } elseif( \is_string( $callback[ 'function' ][ 0 ] ) ) { $callback[ 'name' ] = $callback[ 'function' ][ 0 ] . '::' . $callback[ 'function' ][ 1 ]; $ref = new \ReflectionMethod( $callback[ 'function' ][ 0 ], $callback[ 'function' ][ 1 ] ); } } elseif( $callback[ 'function' ] instanceOf Closure ) { $callback[ 'name' ] = 'closure'; $ref = new \ReflectionMethod( $callback[ 'function' ] ); } elseif( \is_string( $callback[ 'function' ] ) ) { $callback[ 'name' ] = $callback[ 'function' ] . '()'; $ref = new \ReflectionMethod( $callback[ 'name' ] ); } else{ return; } $callback[ 'filename' ] = $ref->getFileName(); $this->addCallback( $callback ); } catch( \ReflectionException $e ) { $callback['error'] = new \WP_Error( 'reflection_exception', $e->getMessage() ); } } } } } class MonitorInit { private static $monitor; public static function init() { self::$monitor = new Monitor(); \add_action( 'all', [ self::$monitor, 'monitor' ] ); \add_action( 'shutdown', [ self::$monitor, 'shutdown' ] ); } } \add_action( 'plugins_loaded', __NAMESPACE__ . '\MonitorInit::init', 0 ); ``` The `plugins_loaded` hook is the first that's available to regular plugins. So if you want to catch hooks that are added before this, you'll need to do something tricky.
311,100
<p>I'm trying to create a proper 'tel:' link for phone numbers that are added in an ACF text field. So I'm just trying to strip extraneous characters, but the spaces are causing a problem.</p> <p><strong>Existing code:</strong></p> <pre><code>$html .= '&lt;p itemprop="telephone" class="member-phone tel"&gt; &lt;a href="tel:+1'.preg_replace("/[^0-9]/","",esc_url( $member_phone )).'"&gt;'.esc_attr( $member_phone ).'&lt;/a&gt;&lt;/p&gt;'; </code></pre> <p>The result of this is:</p> <p><strong>Phone number added:</strong> (323) 555-1212</p> <p><strong>Resulting tel link:</strong> +1323205551212</p> <p>So I'm guessing the space is interpreted as '%20', then the percentage character is stripped, leaving the extra '20'. </p> <ul> <li>How do I modify to strip the space properly (and/or the resulting %20)?</li> </ul>
[ { "answer_id": 311104, "author": "Jacob Peattie", "author_id": 39152, "author_profile": "https://wordpress.stackexchange.com/users/39152", "pm_score": 0, "selected": false, "text": "<p>If you're trying to escape a phone number link, just using <code>esc_url()</code> with the <code>tel:</...
2018/08/10
[ "https://wordpress.stackexchange.com/questions/311100", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/67697/" ]
I'm trying to create a proper 'tel:' link for phone numbers that are added in an ACF text field. So I'm just trying to strip extraneous characters, but the spaces are causing a problem. **Existing code:** ``` $html .= '<p itemprop="telephone" class="member-phone tel"> <a href="tel:+1'.preg_replace("/[^0-9]/","",esc_url( $member_phone )).'">'.esc_attr( $member_phone ).'</a></p>'; ``` The result of this is: **Phone number added:** (323) 555-1212 **Resulting tel link:** +1323205551212 So I'm guessing the space is interpreted as '%20', then the percentage character is stripped, leaving the extra '20'. * How do I modify to strip the space properly (and/or the resulting %20)?
I ended up just changing: `esc_url( $member_phone )`  to  `esc_attr( $member_phone )` Not sure of any drawbacks to this, but it does work as the space is not interpreted as '%20'.
311,116
<p>i need help. My users register to the website. They type their username <strong>user_login</strong> (see chello) but the Display name (see chello04) is not the same. It has a random two digits at the end.</p> <p>Is there a way to force Display names to be the same as usernames?</p> <p><a href="https://i.stack.imgur.com/DiSYE.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/DiSYE.png" alt="enter image description here"></a></p> <p><a href="https://i.stack.imgur.com/E0bpN.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/E0bpN.png" alt="enter image description here"></a></p>
[ { "answer_id": 311120, "author": "Andrea Somovigo", "author_id": 64435, "author_profile": "https://wordpress.stackexchange.com/users/64435", "pm_score": 0, "selected": false, "text": "<p>I would do with jQuery:</p>\n\n<pre><code>add_action('admin_footer','myPlugin_fixed_user_name');\n\nf...
2018/08/11
[ "https://wordpress.stackexchange.com/questions/311116", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/87667/" ]
i need help. My users register to the website. They type their username **user\_login** (see chello) but the Display name (see chello04) is not the same. It has a random two digits at the end. Is there a way to force Display names to be the same as usernames? [![enter image description here](https://i.stack.imgur.com/DiSYE.png)](https://i.stack.imgur.com/DiSYE.png) [![enter image description here](https://i.stack.imgur.com/E0bpN.png)](https://i.stack.imgur.com/E0bpN.png)
You can use the [`wp_pre_insert_user_data`](https://developer.wordpress.org/reference/hooks/wp_pre_insert_user_data/) filter. ``` function wpse_filter_user_data( $data, $update, $id) { if( isset( $data[ 'user_login' ] ) ) { $data[ 'display_name' ] = $data[ 'user_login' ]; return $data; } $user = get_user_by( 'email', $data[ 'user_email' ] ); $data[ 'display_name' ] = $user->user_login; return $data; } add_filter( 'wp_pre_insert_user_data', 'wpse_filter_user_data', 10, 3 ); ``` You'll probably want to use Javascript and/or CSS to hide the field too for a better user experience. ``` $( '.user-display-name-wrap' ).remove(); .user-display-name-wrap { display:none; } ```
311,140
<p>I am using WP-Crontrol and have some CRON jobs running daily to check the age of the posts. If the post is 2 days older, they will be deleted.</p> <p>This works but for some reason, only some of the three days and older posts get deleted. There are still some that remain published.</p> <p>It must be because there are a lot of posts on the site around 3000. Is there a way to make my CRON job more efficient?</p> <p>Here is the current code that I have running:</p> <pre><code>class EventsWPCron { public function __construct() { if ( ! wp_next_scheduled( 'trash_old_events' ) ) { wp_schedule_event( time(), 'daily', 'trash_old_events' ); } add_action( 'trash_old_events', array( $this, 'delete_events' ) ); } public function delete_events() { $args = array( 'post_type' =&gt; 'event', 'post_status' =&gt; 'publish', 'posts_per_page' =&gt; -1, 'date_query' =&gt; array( array( 'before' =&gt; '2 days ago' ) ) ); $query = new WP_Query( $args ); $posts = $query-&gt;get_posts(); foreach( $posts as $post ) { wp_delete_post( $post-&gt;ID, true ); } } } new EventsWPCron(); </code></pre>
[ { "answer_id": 311120, "author": "Andrea Somovigo", "author_id": 64435, "author_profile": "https://wordpress.stackexchange.com/users/64435", "pm_score": 0, "selected": false, "text": "<p>I would do with jQuery:</p>\n\n<pre><code>add_action('admin_footer','myPlugin_fixed_user_name');\n\nf...
2018/08/11
[ "https://wordpress.stackexchange.com/questions/311140", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/139899/" ]
I am using WP-Crontrol and have some CRON jobs running daily to check the age of the posts. If the post is 2 days older, they will be deleted. This works but for some reason, only some of the three days and older posts get deleted. There are still some that remain published. It must be because there are a lot of posts on the site around 3000. Is there a way to make my CRON job more efficient? Here is the current code that I have running: ``` class EventsWPCron { public function __construct() { if ( ! wp_next_scheduled( 'trash_old_events' ) ) { wp_schedule_event( time(), 'daily', 'trash_old_events' ); } add_action( 'trash_old_events', array( $this, 'delete_events' ) ); } public function delete_events() { $args = array( 'post_type' => 'event', 'post_status' => 'publish', 'posts_per_page' => -1, 'date_query' => array( array( 'before' => '2 days ago' ) ) ); $query = new WP_Query( $args ); $posts = $query->get_posts(); foreach( $posts as $post ) { wp_delete_post( $post->ID, true ); } } } new EventsWPCron(); ```
You can use the [`wp_pre_insert_user_data`](https://developer.wordpress.org/reference/hooks/wp_pre_insert_user_data/) filter. ``` function wpse_filter_user_data( $data, $update, $id) { if( isset( $data[ 'user_login' ] ) ) { $data[ 'display_name' ] = $data[ 'user_login' ]; return $data; } $user = get_user_by( 'email', $data[ 'user_email' ] ); $data[ 'display_name' ] = $user->user_login; return $data; } add_filter( 'wp_pre_insert_user_data', 'wpse_filter_user_data', 10, 3 ); ``` You'll probably want to use Javascript and/or CSS to hide the field too for a better user experience. ``` $( '.user-display-name-wrap' ).remove(); .user-display-name-wrap { display:none; } ```
311,154
<p>Hello i have problem. </p> <p>I can't view /blog/page/2/ i klick "_posts_link" and error 404 shows me</p> <p>Blog Page -> home.php</p> <pre><code> &lt;?php $paged = (get_query_var('paged')) ? get_query_var('paged') : 1; $args = array('posts_per_page' =&gt; 5, 'paged' =&gt; $currentPage); query_posts($args); if( have_posts() ): $i = 0; while( have_posts() ): the_post(); ?&gt; </code></pre> <hr> <pre><code> &lt;?php $i++; endwhile; ?&gt; &lt;ul class="uk-pagination uk-background-primary uk-light"&gt; &lt;li&gt;&lt;?php next_posts_link('&lt;span class="uk-margin-small-right" uk-pagination-previous&gt;&lt;/span&gt; Stare Posty'); ?&gt;&lt;/li&gt; &lt;li class="uk-margin-auto-left"&gt;&lt;?php previous_posts_link('Nowe posty &lt;span class="uk-margin-small-left" uk-pagination-next&gt;'); ?&gt;&lt;/li&gt; &lt;/ul&gt; &lt;?php endif; wp_reset_query(); ?&gt; </code></pre>
[ { "answer_id": 311187, "author": "Max", "author_id": 115933, "author_profile": "https://wordpress.stackexchange.com/users/115933", "pm_score": -1, "selected": false, "text": "<p>Use this for pagination</p>\n\n<pre><code>&lt;?php\n$paged = ( get_query_var( 'page' ) ) ? absint( get_query_v...
2018/08/11
[ "https://wordpress.stackexchange.com/questions/311154", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/148538/" ]
Hello i have problem. I can't view /blog/page/2/ i klick "\_posts\_link" and error 404 shows me Blog Page -> home.php ``` <?php $paged = (get_query_var('paged')) ? get_query_var('paged') : 1; $args = array('posts_per_page' => 5, 'paged' => $currentPage); query_posts($args); if( have_posts() ): $i = 0; while( have_posts() ): the_post(); ?> ``` --- ``` <?php $i++; endwhile; ?> <ul class="uk-pagination uk-background-primary uk-light"> <li><?php next_posts_link('<span class="uk-margin-small-right" uk-pagination-previous></span> Stare Posty'); ?></li> <li class="uk-margin-auto-left"><?php previous_posts_link('Nowe posty <span class="uk-margin-small-left" uk-pagination-next>'); ?></li> </ul> <?php endif; wp_reset_query(); ?> ```
I guess you don't need to target a taxonomy. You can use the code below: ``` function query_change_function( $query ) { $query->set( 'posts_per_page', 5 ); } add_action('pre_get_posts', 'query_change_function'); ``` You should wrap the `$query->set( 'posts_per_page', 5 );` around with `if ( ! is_admin() && is_home() ) {//the $query->set code}` to avoid it changing to 5-posts everywhere.
311,157
<p>I have serialized post meta values. It looks like this:</p> <p><a href="https://i.stack.imgur.com/3Aau0.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/3Aau0.png" alt="enter image description here"></a></p> <p>In array:</p> <pre><code>$kisiArray = array( 'option1' =&gt; 7, 'option2' =&gt; 'bar', 'option3' =&gt; 'apple', 'option4' =&gt; 'orange' ); </code></pre> <p>And I want to make a custom query with <strong>meta_query</strong> args. This is my query args:</p> <pre><code>&lt;?php $args = array( 'order' =&gt; 'DESC', 'meta_query' =&gt; array( array( 'key' =&gt; 'themeOps_option1', 'value' =&gt; 6, 'compare' =&gt; '&gt;=', ) ) ); ?&gt; </code></pre> <p>But it doesn't display any result.</p>
[ { "answer_id": 311216, "author": "Fayaz", "author_id": 110572, "author_profile": "https://wordpress.stackexchange.com/users/110572", "pm_score": 3, "selected": true, "text": "<h2>serialised array in a meta_value for query</h2>\n\n<p>It's not a good idea to save serialised array in a <cod...
2018/08/11
[ "https://wordpress.stackexchange.com/questions/311157", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/133897/" ]
I have serialized post meta values. It looks like this: [![enter image description here](https://i.stack.imgur.com/3Aau0.png)](https://i.stack.imgur.com/3Aau0.png) In array: ``` $kisiArray = array( 'option1' => 7, 'option2' => 'bar', 'option3' => 'apple', 'option4' => 'orange' ); ``` And I want to make a custom query with **meta\_query** args. This is my query args: ``` <?php $args = array( 'order' => 'DESC', 'meta_query' => array( array( 'key' => 'themeOps_option1', 'value' => 6, 'compare' => '>=', ) ) ); ?> ``` But it doesn't display any result.
serialised array in a meta\_value for query ------------------------------------------- It's not a good idea to save serialised array in a `meta_value` if you plan to query with any value within that serialized array later. So, the best option is to save meta data as key / value pair. Query Serialized array ---------------------- Although it's not a good approach, it's still possible to query a serialized array within `meta_value` using **regular expression**. > > ***Warning:*** Performance wise this is not a good idea at all. So if you have any other way to achieve the same thing, better do that. I'm giving the answer only to show that it's possible. So use it **only as a last resort**. > > > Example CODE: ``` // this array is serialized and saved in meta_value for meta_key 'themeOps' $serializedArray = array( 'option1' => 7, 'option2' => 'bar', 'option3' => 'apple', 'option4' => 'orange' ); // this is the WP_Query argument $args = array( 'meta_query' => array( array( 'key' => 'themeOps', // this compares if 'option1' >= 6 within the serialized array in meta_value 'value' => wpse311157_serialize_num_greater_equals_regex( 'option1', 6 ), 'compare' => 'REGEXP', ) ) ); ``` As you can see, I've used `'compare' => 'REGEXP'` and used the function `wpse311157_serialize_num_greater_equals_regex( 'option1', 6 )` to generate the proper regular expression (first param is the name of the array `key` and the second param is the number to compare with `>=`). Now, let's implement the `wpse311157_serialize_num_greater_equals_regex` function. Since `meta_value` is a serialized array, it'll look something like: `a:1:{s:3:"key";i:7;}`. To match that, our CODE will look like: ``` function wpse311157_serialize_num_greater_equals_regex( $key, $num ) { return 'a\:[1-9][0-9]*\:\{.*' . preg_quote( serialize( $key ) ) . 'i\:(' . wpse311157_num_greater_equals_regex( $num ) . ');.*\}'; } ``` Now we need to implement the `wpse311157_num_greater_equals_regex( $num )` function by converting `>=` comparison into regular expression. This is **not very efficient**, but this is the only option we have. RegEx algorithm to compare `>=` ------------------------------- The algorithm is simple: (A) For any `n` digit number, any number with `(n+1)` digits is greater than that number. (B) Additionally, we need maximum `n` number of rules to check other `n` digit numbers that are greater than or equal to this number. For example, say we want to compare: `num >= 12` So, RegEx: `[1-9][0-9][0-9]+` will always satisfy it, as it'll match 3 or more digit numbers. Now, to match 2 digit numbers that are `>=` 12, we need 2 rules: 1. `1[2-9]` => this will match numbers: 12 to 19 2. `[2-9][0-9]` => this will match numbers: 20 to 99 So the final RegEx for `num >= 12` is: [`1[2-9]|[2-9][0-9]|[1-9][0-9][0-9]+`](https://regex101.com/r/oGgXtP/1) With this algorithm, let's create our `wpse311157_num_greater_equals_regex( $num )` function: ``` function wpse311157_num_greater_equals_regex( $num ) { $digits = wpse311157_num_digits( $num ); $num_i = $num; $regex = ''; for( $i = 1; $i <= $digits; $i++ ) { $digit = $num_i % 10; $num_i = (int) ( $num_i / 10 ); $regex_i = ''; $need_rule = true; if( 1 === $i ) { if( 9 === $digit ) { $regex_i = '9'; } else { $regex_i = '[' . $digit . '-9]'; } } else { // no rule for 9 if( 9 === $digit ) { $need_rule = false; } else if( 8 === $digit ) { $regex_i = '9'; } else { $regex_i = '[' . ( $digit + 1 ) . '-9]'; } } if( $need_rule ) { if( $i < $digits ) { $regex_i = $num_i . $regex_i; } for( $j = 1; $j < $i; $j++ ) { $regex_i = $regex_i . '[0-9]'; } if( empty( $regex ) ) { $regex = $regex_i; } else { $regex = $regex . '|' . $regex_i; } } } $regex = $regex . '|[1-9]'; for( $i = 1; $i < $digits; $i++ ) { $regex = $regex . '[0-9]'; } $regex = $regex . '[0-9]+'; return $regex; } function wpse311157_num_digits( $num ) { // not considering 0 or negative numbers if( $num < 1 ) return -1; return floor( log10( $num ) + 1 ); } ``` That's all, now you'll be able to compare a value with `>=` within a serialized array.